<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申报计划名称" prop="planName" label-width="100px" >
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入申报计划名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申报计划级别" prop="planLevel" label-width="100px">
        <el-input
          v-model="queryParams.planLevel"
          placeholder="请输入申报计划级别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申报开始日期" prop="projectAppStTime" label-width="100px">
        <el-date-picker clearable
          v-model="queryParams.projectAppStTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申报开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申报结束日期" prop="projectAppEndTime" label-width="100px">
        <el-date-picker clearable
          v-model="queryParams.projectAppEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申报结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['scientific:plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['scientific:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['scientific:plan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['scientific:plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column label="申报计划名称" align="center" prop="planName" :min-width="100"/>
      <el-table-column label="申报计划级别" align="center" width="100px" :min-width="100">
        <template slot-scope="scope">
          <el-tag size="medium" :type="getTagLevelType(scope.row.planLevel)">
            {{ formatplanLevel(scope.row.planLevel) }}
          </el-tag>
        </template>
      </el-table-column>


      <el-table-column label="申报开始日期" align="center" prop="projectAppStTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.projectAppStTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申报结束日期" align="center" prop="projectAppEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.projectAppEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="已申报项目" align="center" prop="projectAppStTime" width="180">
        <template slot-scope="scope">
          <el-button plain
            size="mini"
            @click="listProjectInPlan(scope.row.planId)"
            v-hasPermi="['scientific:plan:list']"
          >{{ scope.row.nProject }}</el-button>
        </template>
      </el-table-column>

      <el-table-column label="申报状态" align="center" width="100px" :min-width="100">
        <template slot-scope="scope">
          <el-tag size="medium" :type="getTagType(isCurrentDateInRange(scope.row.projectAppStTime, scope.row.projectAppEndTime))">
            {{ isCurrentDateInRange(scope.row.projectAppStTime, scope.row.projectAppEndTime) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-top"
            size="mini"
            @click="planDetail(scope.row)"
            v-hasPermi="['scientific:plan:list']"
            style="width: 80px"
          >查看计划</el-button>

          <el-button
            type="primary"
            icon="el-icon-top"
            size="mini"
            @click="projectApply(scope.row)"
            :disabled="isCurrentDateInRange(scope.row.projectAppStTime, scope.row.projectAppEndTime) !== '申报中'"
            v-hasPermi="['scientific:plan:list']"
            style="width: 80px"
          >进入申报</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目申报v2对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申报信息名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入申报信息名称" />
        </el-form-item>
        <el-form-item label="项目立项流程实例Id" prop="planProcId">
          <el-input v-model="form.planProcId" placeholder="请输入项目立项流程实例Id" />
        </el-form-item>
        <el-form-item label="项目指南级别(0市级 1区级 3省级 4国家级)" prop="planLevel">
          <el-input v-model="form.planLevel" placeholder="请输入项目指南级别(0市级 1区级 3省级 4国家级)" />
        </el-form-item>
        <el-form-item label="申报开始日期" prop="projectAppStTime">
          <el-date-picker clearable
            v-model="form.projectAppStTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择申报开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申报结束日期" prop="projectAppEndTime">
          <el-date-picker clearable
            v-model="form.projectAppEndTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择申报结束日期">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/scientific/project_application_plan";
import { listProcess } from '@/api/workflow/process'
import { listApplication } from '@/api/scientific/application'

export default {
  name: "Plan",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目申报v2表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planName: undefined,
        planProcId: undefined,
        planStatus: "3",
        planCategory: undefined,
        planLevel: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planName: [
          { required: true, message: "申报信息名称不能为空", trigger: "blur" }
        ],
        planLevel: [
          { required: true, message: "项目指南级别(0市级 1区级 3省级 4国家级)不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询项目申报v2列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        // 使用Promise.all来处理异步操作
        const promises = this.planList.map(item => {
          const queryParams = {
            pageNum: 1,
              pageSize: 10,
              projectPlanId: item.planId,
          };
          listApplication(queryParams).then(res => {
            // zqjia:后续考虑是否保存整个res的信息
            this.$set(item, "nProject", res.total);
          });
        });

        Promise.all(promises).then(() => {
          // 所有异步操作完成后，更新loading状态
          this.loading = false;
        });
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planId: undefined,
        planName: undefined,
        planProcId: undefined,
        planStatus: undefined,
        planCategory: undefined,
        planLevel: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.planId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目申报v2";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const planId = row.planId || this.ids
      getPlan(planId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改项目申报v2";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.planId != null) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm('是否确认删除项目申报计划编号为"' + planIds + '"的数据项？').then(() => {
        this.loading = true;
        return delPlan(planIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('scientific/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    },
        /**
     * 把项目状态的申报code转换为文字: 0 : 未申报  1: 审核中  2: 已申报
     * @param   {number|string} cellValue - 原始数值
     * @returns {string} 转换后的字符串
     * @author  zhanli
     */

    formatplanLevel(cellValue) {
      switch (cellValue) {
        case '1':
          return "国家级";
        case '2':
          return "省级";
        case '3':
          return "市级";
        case '4':
          return "院级";
        default:
          return "未知";
      }
    },
    getTagType(status) {
      switch (status) {
        case '已结束':
          // 显示红色 停止申报
          return 'danger';
        case '申报中':
          // 审核中 显示绿色
          return 'success';
        case '未开始':
          // 未申报, 灰色
          return 'info';
        default:
          return '';
      }
    },
    getTagLevelType(status) {
      switch (status) {
        case '2':
          // 省级 蓝色
          return 'primary';
        case '3':
          // 市级 显示绿色
          return 'success';
        case '4':
          // 院级, 灰色
          return 'info';
        case '1':
          // 国家级 红色
          return 'danger';
        default:
          return '';
      }
    },
    isCurrentDateInRange(startDate, endDate) {
      // 获取当前时间
      const currentDate = new Date();

      // 将字符串日期转换为Date对象
      const start = new Date(startDate);
      const end = new Date(endDate);

      // 判断当前时间是否在范围内
      if(currentDate >= start && currentDate <= end) {
        return "申报中";
      }
      else {
        if(currentDate < start) {
          return "未开始";
        }
        else {
          return "已结束";
        }
      }
    },
    projectApply(row) {
      // 跳转到项目申报
      this.$router.push({
        name: 'ProjectApply',
        params: {
          plan: row
        }
      })
    },
    listProjectInPlan(planId) {
      if (planId === undefined) {
        planId = 1;
      }
      let queryParams = {
        pageNum: 1,
        pageSize: 10,
        projectPlanId: planId,
      };
      this.$router.push({
        name: 'planProjectQuery',
        params: {
          planId: planId,
          queryParams: queryParams,
        }
      })
    },
    planDetail(row) {
      this.$router.push({
        path: '/scientific/project_application_plan/detail/' + row.planProcId,
        query: {
          processed: false,
        }
      })
    },
  }
};
</script>
