<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="流程标识" prop="processKey">
        <el-input
          v-model="queryParams.processKey"
          placeholder="请输入流程标识"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程名称" prop="processName">
        <el-input
          v-model="queryParams.processName"
          placeholder="请输入流程名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程分类" prop="category">
        <el-select v-model="queryParams.category" clearable placeholder="请选择" size="small">
          <el-option
            v-for="item in categoryOptions"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="提交时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></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="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          v-hasPermi="['workflow:process:ownExport']"
          @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>


    <el-table v-loading="loading" :data="showList" @selection-change="handleSelectionChange">
      <el-table-column label="指南名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.handbookname }}
        </template>
      </el-table-column>
      <el-table-column label="指南类别" align="center">
        <template slot-scope="scope">
          {{ scope.row.handbookclass }}
        </template>
      </el-table-column>
      <el-table-column label="指南级别" align="center">
        <template slot-scope="scope">
          {{ scope.row.handbooklevel }}
        </template>
      </el-table-column>
      <el-table-column label="截至日期" align="center">
        <template slot-scope="scope">
          {{ scope.row.handbookdate }}
        </template>
      </el-table-column>
      <el-table-column label="指南文件" align="center">
        <template slot-scope="scope">
          <el-button class="file" @click="handbookDownload(scope.row.handbookfile)">下载</el-button>
        </template>
      </el-table-column>

      <el-table-column label="项目申报" align="center">
        <template slot-scope="scope">
          <el-button class="file" @click="projectApply(scope.row)">项目申报</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"
    />

  </div>
</template>

<script>
import {
  stopProcess,
  delProcess,
  listHandbook,
  detailProcess,
  detailProcesses,
  listProcess
} from '@/api/workflow/process';
import { listAllCategory } from '@/api/workflow/category';
import Parser from '@/utils/generator/parser'
import {getToken} from "@/utils/auth";
// import {deepClone} from "@/utils";

export default {
  name: "handbookQuery",
  dicts: ['wf_process_status'],
  components: {
    Parser,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      processLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      categoryOptions: [],
      processTotal:0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      src: "",
      definitionList:[],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processKey: undefined,
        processName: undefined,
        category: "007"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      // 从后端查询的原始列表数据
      handbookList: [],
      // 解析用于显示的数据
      showList: [],
    };
  },

  async created() {
     await this.getList();
     await this.getProcessDetails();
  },

  methods: {
    // 文件下载
    handbookDownload(handbookfile) {
      handbookfile.forEach( file => {
        if(file.response.code === 200 && file.ossId) {
          this.$download.oss(file.ossId);
        }
      })
    },

    projectApply(row) {
      let queryParams = {
        pageNum: 1,
          pageSize: 10,
          processKey: undefined,
          processName: "项目申报",
          category: "002"
      };
      // 跳转到项目申报
      listProcess(queryParams).then(response => {
        const apply = response.rows[0];
        if(apply) {
          this.$router.push({
            path: '/workflow/process/start/' + apply.deploymentId,
            query: {
              definitionId: apply.definitionId,
              processName: apply.processName,
            }
          })
        }
      });
    },

    /** 查询流程定义列表 */
    getList() {
      // zqjia:这个解析要模仿parser.js重写
      return new Promise((resolve,reject)=>{
        this.showList = [];
        this.loading = true;
        listHandbook(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.handbookList = response.rows;
          this.total = response.total;
          this.loading = false;
          resolve();
        });
      })
    },

    // 流程任务重获取变量表单
    getProcessDetails() {
      return new Promise((resolve, reject)=>{
        let pId = [];
        let tId = [];
        this.handbookList.forEach(handbook => {
          pId.push(handbook.procInsId);
          tId.push(undefined);
        })
        const params = {procInsIds: pId};
        detailProcesses(pId).then(res => {
          res.rows.forEach(row => {
            let processForm = row.processFormList[0];
            let formData = [];
            this.initFormData(processForm.fields, formData);
            formData["procDefId"] = row.procInsId;

            this.showList.push(formData);
          })
        })
      })
    },

    /** 查询流程分类列表 */
    getCategoryList() {
      listAllCategory().then(response => this.categoryOptions = response.data)
    },


    initFormData(componentList, formData) {
      componentList.forEach(cur => {
        this.buildOptionMethod(cur)
        const config = cur.__config__;
        if (cur.__vModel__) {
          if(cur.__slot__ && 'options' in cur.__slot__) {
            formData[cur.__vModel__] = cur.__slot__.options[config.defaultValue-1].label;
          }
          else {
            formData[cur.__vModel__] = config.defaultValue;
          }

        }

        if (config.children) {
          this.initFormData(config.children, formData);
        }
      })

    },

    // 特殊处理的 Option
    buildOptionMethod(scheme) {
      const config = scheme.__config__;
      if (config && config.tag === 'el-cascader') {
        if (config.dataType === 'dynamic') {
          this.$axios({
            method: config.method,
            url: config.url
          }).then(resp => {
            var { data } = resp
            scheme[config.dataConsumer] = data[config.dataKey]
          });
        }
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.procInsId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAgain(row) {
      this.$router.push({
        path: '/workflow/process/start/' + row.deployId,
        query: {
          definitionId: row.procDefId,
          procInsId: row.procInsId
        }
      })
    },
    /**  取消流程申请 */
    handleStop(row){
      const params = {
        procInsId: row.procInsId
      }
      stopProcess(params).then( res => {
        this.$modal.msgSuccess(res.msg);
        this.getList();
      });
    },
    /** 流程流转记录 */
    handleFlowRecord(row) {
      this.$router.push({
        path: '/workflow/process/detail/' + row.procInsId,
        query: {
          processed: false
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.procInsId || this.ids;
      this.$confirm('是否确认删除流程定义编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delProcess(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('workflow/process/ownExport', {
        ...this.queryParams
      }, `wf_own_process_${new Date().getTime()}.xlsx`)
    },
    categoryFormat(row, column) {
      return this.categoryOptions.find(k => k.code === row.category)?.categoryName ?? '';
    }
  }
};
</script>

<style scoped>
.file {
  border: none;
  background: none;
  /* 取消其他默认样式 */
  box-shadow: none;
  padding: 0;
  margin: 0;
}

.file:hover {
  background: none; /* 去掉鼠标悬停时的背景 */
  /* 如果需要，可以添加其他hover效果 */
}
</style>

