
<template>
  <div class="page">
    <LayoutTable :data="tableData" :config="tableConfig" notAdd notDel>
      <el-button
        slot="table-head-left2"
        style="margin-left: 10px"
        icon="el-icon-tickets"
        size="mini"
        @click="handleImport"
        >导入</el-button
      >

      <el-button
        slot="table-head-left2"
        style="margin-left: 10px"
        icon="el-icon-tickets"
        size="mini"
        @click="handleLoadXml"
        >新增</el-button
      >

      <el-button
        slot="table-head-left2"
        style="margin-left: 10px"
        icon="el-icon-tickets"
        size="mini"
        disabled
        @click="handleExport"
        >导出</el-button
      >
    </LayoutTable>

    <!-- bpmn20.xml导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xml"
        :headers="upload.headers"
        :action="
          upload.url + '?name=' + upload.name + '&category=' + upload.category
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          流程名称：<el-input v-model="upload.name" /> 流程分类：<el-input
            v-model="upload.category"
          />
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“bpmn20.xml”格式文件！
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 流程图 -->
    <el-dialog
      :title="readImage.title"
      :visible.sync="readImage.open"
      width="70%"
      append-to-body
    >
      <!-- <el-image :src="readImage.src"></el-image> -->
      <flow :xmlData="xmlData" />
    </el-dialog>

    <!--表单配置详情-->
    <el-dialog
      :title="formTitle"
      :visible.sync="formConfOpen"
      width="50%"
      append-to-body
    >
      <div class="test-form">
        <parser :key="new Date().getTime()" :form-conf="formConf" />
      </div>
    </el-dialog>

    <!--挂载表单-->
    <el-dialog
      :title="formDeployTitle"
      :visible.sync="formDeployOpen"
      width="30%"
      append-to-body
    >
      <el-select v-model="formDeployParam.formId" placeholder="请选择表单">
        <el-option
          v-for="form in formList"
          :key="form.id"
          :label="form.formName"
          :value="form.id"
        />
      </el-select>
      <el-button type="primary" @click="submitFormDeploy">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { treeCache } from "@/assets/utils/tree";
import {
  listDefinition,
  updateState,
  delDeployment,
  addDeployment,
  updateDeployment,
  exportDeployment,
  definitionStart,
  readXml,
} from "@/api/flowable/definition";
import { getForm,addForm, addDeployForm ,listForm } from "@/api/flowable/form";
import table from "@/assets/mixins/table";
import Parser from "@/components/parser/Parser";
import flow from "@/views/flowable/task/record/flow";

export default {
  name: "Definition",
  components: {
    Parser,
    flow,
  },
  mixins: [table],
  methods: {
    /** 查询流程定义列表 */
    // getList() {
    //   this.loading = true;
    //   listDefinition(this.queryParams).then(response => {
    //     this.definitionList = response.data.records;
    //     this.total = response.data.total;
    //     this.loading = false;
    //   });
    // },
    // 取消按钮
    
    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");
    },

    /** 新增按钮操作 */
    handleAdd() {
      console.log("新增按钮操作");
      this.reset();
      this.open = true;
      this.title = "添加流程定义";
    },
    /** 跳转到流程设计页面 */
    handleLoadXml(row) {
      console.log("跳转到流程设计页面");

      this.$router.push({
        path: "/flowable/definition/model",
        query: { deployId: row.deploymentId },
      });
    },
    /** 流程图查看 */
    handleReadImage(row) {
      console.log("流程图查看");

  this.readImage.title = "流程图";
      this.readImage.open = true;
      // this.readImage.src = process.env.VUE_APP_BASE_API + "/flowable/definition/readImage/" + deploymentId;
       // 发送请求，获取xml
      readXml(row.deploymentId).then(res =>{
        this.xmlData = res.data
      })

    },
    /** 表单查看 */
    handleForm(formId) {
      console.log("formId:"+formId);
      getForm(formId).then((res) => {
      
        this.formTitle = "表单详情";
        this.formConfOpen = true;
        this.formConf = JSON.parse(res.data.entity.formContent);
      });
    },

    readXml(row) {

      definitionStart(row.id).then((res) => {
        this.msgSuccess(res.msg);
      });
    },

    /** 启动流程 */
    handleDefinitionStart(row) {
      console.log("启动流程");

      definitionStart(row.id).then((res) => {
        this.msgSuccess(res.msg);
      });
    },
    /** 挂载表单弹框 */
    handleAddForm(row) {
      console.log("挂载表单！");
      this.formDeployParam.deployId = row.deploymentId;
         const pageInfo = {
            prePageResult: 100
         }
      listForm({},pageInfo).then((res) => {
      
        this.formList = res.data.result;
        this.formDeployOpen = true;
        this.formDeployTitle = "挂载表单";
      });
    },
    // /** 更改挂载表单弹框 */
    // handleEditForm(row){
    //   this.formDeployParam.deployId = row.deploymentId
    //   const queryParams = {
    //     pageNum: 1,
    //     pageSize: 10
    //   }
    //   listForm(queryParams).then(res =>{
    //     this.formList = res.rows;
    //     this.formDeployOpen = true;
    //     this.formDeployTitle = "挂载表单";
    //   })
    // },
    /** 挂载表单 */
    submitFormDeploy() {
      //提交表单
      addForm();
      console.log("提交表单!");
      console.log(this.formDeployParam);
      addDeployForm(this.formDeployParam).then(res =>{
        console.log(res);
        this.$message.success("表单关联成功！");
        this.formDeployOpen = false;
        this.getData();
      })
    },
    /** 挂起/激活流程 */
    handleUpdateSuspensionState(row) {
      console.log("挂起/激活流程!");
      let state = 1;
      if (row.suspensionState === 1) {
          state = 2
      }
      const params = {
        deployId: row.deploymentId,
        state: state
      }
      updateState(params).then(res => {
        this.$message.success("更新成功！");
        this.getData();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log("修改按钮操作!");
      // this.reset();
      // const id = row.id || this.ids
      // getDeployment(id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改流程定义";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDeployment(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeployment(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.deploymentId || this.ids;
      const params = {
        deployId: row.deploymentId
      }
      this.$confirm('是否确认删除流程定义编号为"' + params.deployId + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delDeployment(params);
      }).then(() => {
         this.$message.success("删除成功");
        this.getData();
       
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams;
      // this.$confirm('是否确认导出所有流程定义数据项?', "警告", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(function() {
      //   return exportDeployment(queryParams);
      // }).then(response => {
      //   this.download(response.msg);
      // })
    },
    /** 导入bpmn.xml文件 */
    handleImport() {
      this.upload.title = "bpmn20.xml文件导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$message.success(response.msg);
      this.getData();
    },
    // 提交上传文件
    submitFileForm() {
      console.log("上传附件");
     this.$refs.upload.submit();
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程定义表格数据
      definitionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      formConfOpen: false,
      formTitle: "",
      formDeployOpen: false,
      formDeployTitle: "",
      formList: [],
      formConf: {}, // 默认表单数据
      readImage: {
        open: false,
        src: "",
      },
      // bpmn.xml 导入
      upload: {
        // 是否显示弹出层（xml导入）
        open: false,
        // 弹出层标题（xml导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        name: null,
        category: null,
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: "/m/flowable/definition/upload",

      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null,
      },
      formDeployParam: {
        formId: '1',
        deployId: null,
      },
      // xml
      xmlData: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      config: {
        search: [
          {
            name: "name",
            type: "text",
            label: "名称",
          },
          {
            name: "area",
            type: "cascader",
            label: "区域",
          },
        ],
        columns: [
          {
            type: "selection",
            width: 60,
          },

          {
            prop: "deploymentId",
            label: "流程编号",
          },

          {
            prop: "key",
            label: "流程标识",
          },

          {
            prop: "name",
            label: "流程名称(流程图)",
             formatter: row => {
                return (
                    <el-button
                    type="text"
                    onClick={() => {
                      this.handleReadImage(row);
                    }}
                  >
                  {row.name}
                  </el-button>
                )
            }
          },

          {
            prop: "category",
            label: "流程分类",
          },

        
          {
            prop: "formName",
            label: "挂载表单",
            formatter: row => {
                return (
                    <el-button
                    type="text"
                    onClick={() => {
                      this.handleForm(row.formId);
                    }}
                  >
                  {row.formName}
                  </el-button>
                )
            }
          },

          {
            prop: "version",
            label: "流程版本",
          },

          {
            prop: "suspensionState",
            label: "状态",
            formatter: this.formatter,
          },

          {
            prop: "deploymentTime",
            label: "部署时间",
            width: 140,
            formatter: this.formatterDate,
          },

          {
            label: "操作",
            width: 180,
            formatter: (row) => {
              return (
                <el-row>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit-outline"
                    onClick={() => {
                      this.handleLoadXml(row);
                    }}
                  >
                    编辑
                  </el-button>

                  <span> </span>

                  {row && row.formId == null ? (
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-connection"
                      v-if="row.formId != null"
                      onClick={() => {
                        this.handleAddForm(row);
                      }}
                    >
                      配置表单
                    </el-button>
                  ) : (
                    ""
                  )}
                  <span> </span>
                  {row && row.suspensionState === 1 ? (
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-video-pause"
                      v-if="row.formId != null"
                      onClick={() => {
                        this.handleUpdateSuspensionState(row);
                      }}
                    >
                      挂起
                    </el-button>
                  ) : (
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-video-play"
                      onClick={() => {
                        this.handleUpdateSuspensionState(row);
                      }}
                    >
                      激活
                    </el-button>
                  )}

                  <span> </span>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    onClick={() => {
                      this.handleDelete(row);
                    }}
                  >
                    删除
                  </el-button>


                  <span> </span>

                  {row && row.formId !=null ? (
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    onClick={() => {
                      this.handleForm(row.formId);
                    }}
                  >
                    查看表单
                  </el-button>
                  ) : (
                    ""
                  )}
                </el-row>
              );
            },
          },
        ],
      },
    };
  },
};
</script>
