<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="$t('bpmprocess.processName')" prop="processName">
        <el-input
          v-model="queryParams.processName"
          :placeholder="$t('bpmprocess.pleaseEnterProcessName')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('bpmprocess.processKey')" prop="processKey">
        <el-input
          v-model="queryParams.processKey"
          :placeholder="$t('bpmprocess.pleaseEnterProcessKey')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('bpmprocess.processType')" prop="processType">
        <!-- <el-input
          v-model="queryParams.processType"
          placeholder="请输入流程别名"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-radio
          @change="handleQuery"
          v-model="queryParams.processType"
          label="0"
          >{{ $t('bpmprocess.productionProcess') }}</el-radio
        >
        <el-radio
          @change="handleQuery"
          v-model="queryParams.processType"
          label="1"
          >{{ $t('bpmprocess.approvalProcess') }}</el-radio
        >
      </el-form-item>
      <!-- <el-form-item
        label="流程开启状态"
        class="item_label"
        prop="processOpneState"
      >
        <el-input
          v-model="queryParams.processOpneState"
          placeholder="请输入流程开启状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="流程部署时间"
        class="item_label"
        prop="processDeployTime"
      >
        <el-date-picker
          clearable
          v-model="queryParams.processDeployTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择流程部署时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="版本状态" prop="processVersion">

        <el-select
          v-model="queryParams.processVersion"
          value-key="value"
          placeholder="请输入版本状态"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in dict.type.bpm_version"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t('normal.search') }}
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >{{ $t('normal.reset') }}
        </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="['system:process:add']"
          >{{ $t('normal.insert') }}
        </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="['system:process:remove']"
          >{{ $t('normal.delete') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          v-if="selection.length == 0"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:process:export']"
          >{{ $t('bpmprocess.exportAll') }}
        </el-button>
        <ExcelDownLoad
          v-else
          :headerList="headerList"
          :fieldList="selection"
          :excelTitle="excelTitle"
        ></ExcelDownLoad>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleFileExport"
          v-hasPermi="['system:process:export']"
          >{{ $t('bpmprocess.exportProcessFile') }}
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="processList"
      @selection-change="handleSelectionChange"
      ref="tableRef"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('bpmprocess.primaryKey')" align="center" prop="processId" />
      <el-table-column :label="$t('bpmprocess.processName')" align="center" prop="processName">
        <template slot-scope="scope">
          <span class="process_name" @click="prviewHandle(scope.row)">{{
            scope.row.processName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bpmprocess.processKey')" align="center" prop="processKey" />
      <!-- <el-table-column label="流程状态" align="center" prop="processOpneState">
        <template slot-scope="scope">
          <span>{{
            getDictLabel(scope.row.processOpneState, dict.type.bpm_state)
          }}</span>
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('bpmprocess.processType')" align="center" prop="processType">
        <template slot-scope="scope">
          <span>{{
            getDictLabel(scope.row.processType, dict.type.bpm_type)
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="流程部署时间"
        align="center"
        prop="processDeployTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.processDeployTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        :label="$t('bpmprocess.startEventType')"
        align="center"
        prop="startEventType"
      >
        <template slot-scope="scope">
          <span>{{
            getDictLabel(
              scope.row.startEventType,
              dict.type.bpm_start_event_type
            )
          }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('bpmprocess.versionNote')" align="center" prop="note" />
      <el-table-column :label="$t('bpmprocess.versionStatus')" align="center" prop="processVersion">
        <template slot-scope="scope">
          <span
            style="color: #337ab7; cursor: pointer"
            @click="versionStatusHandle(scope.row)"
            >{{
              getDictLabel(scope.row.processVersion, dict.type.bpm_version)
            }}</span
          >
        </template>
      </el-table-column>
      <!-- <el-table-column label="节点json串" align="center" prop="processJson" /> -->
      <!-- <el-table-column
        label="xml文件存放地址"
        align="center"
        prop="processXmlPath"
      /> -->
      <el-table-column :label="$t('normal.remark')" align="center" prop="remark" />
      <el-table-column
        :label="$t('normal.operation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              {{ $t('normal.process') }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="backupProcess(scope.row)"
                  v-hasPermi="['system:user:edit']"
                  >{{ $t('bpmprocess.backupFlowChart') }}
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEditbpmn(scope.row)"
                  v-hasPermi="['system:user:edit']"
                  >{{ $t('bpmprocess.designFlowChart') }}
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:user:remove']"
                  >{{ $t('normal.delete') }}
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 预览流程图对话框 -->
    <el-dialog
      :title="previewData.processName"
      :visible.sync="preOpen"
      width="100%"
      height="100%"
      append-to-body
    >
      <Preview ref="previewRef" @preCloseHandler="preCloseHandler"></Preview>
    </el-dialog>

    <!-- 版本状态对话框 -->
    <el-dialog :title="$t('bpmprocess.versionStatusDialog')" width="800px" :visible.sync="isVersionsStatus">
      <el-table :data="versionForm" style="width: 100%">
        <el-table-column prop="processId" :label="$t('bpmprocess.primaryKey')" align="center">
        </el-table-column>
        <el-table-column prop="processName" :label="$t('bpmprocess.processName')" align="center">
        </el-table-column>
        <el-table-column prop="processKey" :label="$t('bpmprocess.processKey')" align="center">
        </el-table-column>
        <el-table-column prop="processType" :label="$t('bpmprocess.processType')" align="center">
        </el-table-column>
        <el-table-column
          prop="startEventType"
          :label="$t('bpmprocess.startEventType')"
          align="center"
          width="100px"
        >
        </el-table-column>
        <el-table-column prop="note" :label="$t('bpmprocess.versionNote')" align="center">
        </el-table-column>
        <el-table-column prop="remark" :label="$t('normal.remark')" align="center">
        </el-table-column>
        <el-table-column
          :label="$t('normal.operation')"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-dropdown>
              <el-button type="warning" plain size="small">
                {{ $t('normal.process') }}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    v-hasPermi="['system:user:edit']"
                    @click="statusStartHandle(scope.row)"
                    >{{ $t('bpmprocess.enable') }}
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :total="statustotal"
        :page.sync="statusParams.pageNum"
        :limit.sync="statusParams.pageSize"
        @pagination="pagelist(versionForm)"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  listProcess,
  getProcess,
  delProcess,
  addProcess,
  updateProcess,
  bpmBackups,
  exportFileProcess,
  enableProcess,
} from "@/api/bpmprocess/process";
import Preview from "./components/preview.vue";
import ExcelDownLoad from "@/components/ExcelDownLoad/index.vue";

export default {
  name: "Process",
  dicts: ["bpm_state", "bpm_type", "bpm_start_event_type", "bpm_version"],
  components: { Preview, ExcelDownLoad },
  data() {
    return {
      // 前端导出数据
      headerList: {
        流程名称: "processName",
        流程别名: "processKey",
        流程开启状态: "processOpenState",
        流程类型: "processType",
        流程部署时间: "processDeployTime",
        启动事件类型: "startEventType",
        版本注释: "note",
        版本状态: "processVersion",
        xml流文件: "processXml",
        节点ison串: "processJson",
        xml标签内容: "processXmlContent",
        xml文件存放地址: "processXmlPath",
      },
      // fieldList: [],
      excelTitle: "process",
      // 预览的数据
      previewData: {},
      // 预览弹窗
      preOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组(包含所有数据)
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程定义表格数据
      processList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示版本控制弹出层
      isVersionsStatus: false,
      versionForm: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processName: null,
        processKey: null,
        processOpneState: null,
        processType: null,
        processDeployTime: null,
        startEventType: null,
        note: null,
        processXml: null,
        processJson: null,
        processXmlContent: null,
        processXmlPath: null,
        processVersion: 0,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 版本状态参数
      statusParams: {
        pageNum: 1,
        pageSize: 10,
        processKey: null,
        processVersion: 1,
      },
      statustotal: 0,
      processKey: null,
    };
  },
  created() {
    this.getList();
  },
  activated() {
    this.getList();
  },
  methods: {
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      let tempSelection = JSON.parse(JSON.stringify(this.selection));
      listProcess(this.queryParams).then((response) => {
        this.processList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        processId: null,
        processName: null,
        processKey: null,
        processOpneState: null,
        processType: null,
        processDeployTime: null,
        startEventType: null,
        note: null,
        processVersion: null,
        processXml: null,
        processJson: null,
        processXmlContent: null,
        processXmlPath: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      let endFormData = {
        // 节点脚本关联表
        BpmNodeExceptionList: [
          {
            id: null,
            nodeKey: null, // 节点别名
            scriptKey: null, // 脚本别名
            scriptTriggerType: null, // 脚本触发机制（0:手动 1:自动）
          },
        ],
        // 节点操作人 -》 数据传输分两种情况：1.当前节点勾选了指定用户，就需要前端生成一个虚拟的角色编码、以及指定的用户id、真实的角色编码null即可
        // 2.当前节点根据角色勾选的执行人，就需要存贮真实的角色权限字符 生成一个虚拟的角色编码，其他为null即可
        // 节点处理人表
        BpmNodeHandleUser: [
          {
            id: null,
            virtuallyRole: null, // 前端生成的虚拟角色编码
            realRole: null, // 真实的角色编码  [1,2,3]/[1]
            executeUserNo: null, // 用户编码  [1,2,3]/[1]
          },
        ],
        // 所有节点表
        BpmProcessConfigurationList: [
          {
            id: null,
            nodeKey: null, // 节点别名
            nodeName: null, // 节点名称
            nodeFormKey: null, // 节点表单别名
            nodeProcessKey: null, // 流程别名
            nodeType: null, // 节点类型（判断节点、正常节点。。。）根据字典维护
            nodeBefor: null, // 节点前
            nodeAfter: null, // 节点后
            nodeRolePermission: null, // 节点对应的角色权限字符(只存虚拟角色编码)
            spare1: null, // 备用列
            spare2: null,
            spare3: null,
            createBy: null, // 创建者
            updateBy: null, // 修改者
            remark: null, // 节点描述
          },
        ],
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.processId);
      this.selection = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: "/processModeling/bpmnPro",
      });
      // this.reset();
      // this.open = true;
      // this.title = "添加流程定义";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const processId = row.processId || this.ids;
      getProcess(processId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改流程定义";
      });
    },
    /** */
    handleEditbpmn(row) {
      this.$router.push({
        path: "/processModeling/bpmnPro",
        query: {
          id: row.processId,
        },
      });
    },
    // 备份流程图
    backupProcess(row) {
      this.$prompt("请输入备份描述:", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            if (instance.inputValue?.trim().length) {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = "保存中...";

              try {
                let data = {
                  processId: row.processId,
                  remark: instance.inputValue.trim(),
                };
                let res = await bpmBackups(data);
                if (res.code == 200) {
                  this.$message.success("备份成功");
                  instance.confirmButtonLoading = false;
                  instance.confirmButtonText = "确定";
                  this.getList();
                  done();
                } else {
                  this.$message.error("备份失败");
                }
                instance.confirmButtonLoading = false;
                instance.confirmButtonText = "确定";
              } catch (error) {
                instance.confirmButtonLoading = false;
                instance.confirmButtonText = "确定";
                console.log(error);
              }
            } else {
              this.$message({
                type: "error",
                message: "备份描述不能为空",
              });
            }
          } else {
            this.getList();
            done();
          }
        },
      })
        .then(({ value }) => {})
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消备份",
          });
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.processId != null) {
            updateProcess(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProcess(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const processIds = row.processId || this.ids;
      this.$modal
        .confirm(this.$t('normal.isConfirmDelete') + processIds + '"的数据项？')
        .then(function () {
          return delProcess(processIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('normal.deleteSuccess'));
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        process.env.VUE_APP_BASE_API4 + "system/process/export",
        {
          ...this.queryParams,
        },
        `process_${new Date().getTime()}.xlsx`
      );
    },
    handleFileExport() {
      if (this.ids.length != 0) {
        exportFileProcess(this.ids).then((res) => {
          const content = res;
          const blob = new Blob([content], { type: "application/zip" });
          const fileName = this.$t('bpmprocess.exportProcessFile');
          if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
            this.loading = false;
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
            this.loading = false;
          }
        });
      } else {
        this.$message.warning(this.$t('normal.pleaseSelectData'));
      }
    },
    // 获取字典对应label
    getDictLabel(value, dictLsit = []) {
      return dictLsit.find((item) => {
        return item.value == value;
      })?.label;
    },
    // 版本状态
    versionStatusHandle(row) {
      this.statusParams.processKey = this.processKey
        ? this.processKey
        : row.processKey;
      listProcess(this.statusParams).then((res) => {
        this.statustotal = res.total;
        res.rows.forEach((item) => {
          // 启动事件类型
          item.startEventType = this.getDictLabel(
            item.startEventType,
            this.dict.type.bpm_start_event_type
          );
          // 流程类型
          item.processType = this.getDictLabel(
            item.processType,
            this.dict.type.bpm_type
          );
        });
        this.versionForm = res.rows;
      });
      this.isVersionsStatus = true;
    },
    // 版本状态分页器
    pagelist(row) {
      this.processKey = row[0].processKey;
      this.versionStatusHandle(this.processKey);
    },
    // 版本状态启用
    statusStartHandle(row) {
      enableProcess({
        processId: row.processId,
        processKey: row.processKey,
      }).then((res) => {
        if (res.code == 200) {
          this.getList();
          this.$message.success(this.$t('bpmprocess.enableSuccess'));
          this.isVersionsStatus = false;
        }
      });
    },
    // 预览流程图
    prviewHandle(row) {
      this.previewData = row;
      this.preOpen = true;
      this.$nextTick(() => {
        this.$refs.previewRef.getImg(row.processXmlContent);
      });
    },
    // 关闭预览回调
    preCloseHandler() {
      this.$refs.previewRef.destroyPreventMenu();
      this.preOpen = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.process_name {
  color: #337ab7;
  cursor: pointer;
}
::v-deep .el-form-item__label {
  width: 98px !important;
}
::v-deep .el-dialog {
  margin-top: 0px !important;
}
</style>
