<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="filter-container">
        <modelSearch @search="reload" :processTypeList="processTypeList"></modelSearch>
      </div>
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        cache-key="systemRoleTable5"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="handleAdd"
            class="ele-btn-icon"
          >新建流程
          </el-button>
        </template>

        <template v-slot:suspensionState="{ row }">
          <el-switch v-if="row.processDefinition" v-model="row.processDefinition.suspensionState"
                     :active-value="1" :inactive-value="2" @change="handleChangeState(row)"/>
        </template>
        <template v-slot:version="{ row }">
          <el-tag size="medium" v-if="row.processDefinition" v-model="row.processDefinition.version">
            v{{ row.processDefinition.version }}
          </el-tag>
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)">修改流程</el-button>
          <el-button size="mini" type="text" icon="el-icon-setting" @click="handleDesign(row)">设计流程</el-button>
          <el-button size="mini" type="text" icon="el-icon-s-custom" @click="handleAssignRule(row)">分配规则</el-button>
          <el-button size="mini" type="text" icon="el-icon-thumb" @click="handleDeploy(row)">发布流程</el-button>
          <el-button size="mini" type="text" icon="el-icon-ice-cream-round" @click="handleDefinitionList(row)">
            流程定义
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="流程分类" prop="processTypeId">
          <!--          <el-select v-model="form.processTypeId" clearable style="width: 100%" @change="handleProcessType">-->
          <!--            <el-option v-for="item in processTypeList" :value="item.id" :label="item.name" :key="item.id"></el-option>-->
          <!--          </el-select>-->
          <ele-tree-select
            clearable
            ref="processTypeRef"
            filterable
            :data="processTypeList"
            v-model="form.processTypeId"
            childrenKey="children"
            valueKey="id"
            labelKey="name"
            placeholder="请选择"
            default-expand-all
            @change="handleProcessType"
          />

        </el-form-item>
        <el-form-item label="流程标识" prop="key">
          <el-input v-model="form.key" placeholder="请输入流标标识" style="width: 330px;" :disabled="!!form.id"/>
          <el-tooltip v-if="!form.id" class="item" effect="light" content="新建后，流程标识不可修改！" placement="top">
            <i style="padding-left: 5px;" class="el-icon-question"/>
          </el-tooltip>
          <el-tooltip v-else class="item" effect="light" content="流程标识不可修改！" placement="top">
            <i style="padding-left: 5px;" class="el-icon-question"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入流程名称" :disabled="!!form.id" clearable/>
        </el-form-item>
        <el-form-item label="流程描述" prop="description">
          <el-input type="textarea" v-model="form.description" clearable/>
        </el-form-item>
        <div v-if="form.id">
          <el-form-item label="表单路由" prop="formCustomCreatePath">
            <el-input v-model="form.formCustomCreatePath" placeholder="请按格式输入表单路由" style="width: 330px;"
                      type="textarea" rows="3"/>
            <div style="line-height: 16px; color: red;">
              提示：<br/>
              1、表单路由中包含PC端和手机端的页面路由，路由分为处理路由和查看路由。<br/>
              2、若整个流程的表单路由为同一个，则在此填写。若流程中的每个节点都有自己的个性化的处理页面，则此处留空。在流程设计器中设置节点的路由。<br/>
              3、必须按照以下格式填入：{"pcHandle":"/xx/xx", "pcView":"/xx/xx", "miniHandle":"/xx/xx","miniView":"/xx/xx"}
            </div>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- ========== 流程任务分配规则 ========== -->
    <taskAssignRuleDialog ref="taskAssignRuleDialog"/>

  </div>
</template>

<script>
import {
  createModel,
  deleteModel,
  deployModel,
  getModel,
  getModelPage,
  updateModel,
  updateModelState
} from "@/api/bpm/model";
import Pagination from '@/components/Pagination';
import dictMixins from '@/mixins/dictMixins';
import modelSearch from './components/modelSearch.vue';
import taskAssignRuleDialog from '../taskAssignRule/taskAssignRuleDialog.vue';
import {getProduceTreeByCode} from "@/api/bpm/processClass";
import {getTreeByPid} from "@/api/classifyManage";
export default {
  mixins: [dictMixins],
  name: 'BpmModel',
  components: {
    modelSearch, Pagination, taskAssignRuleDialog,
  },
  data() {
    return {
      columns: [
        {
          type: 'index',
          label: '序号',
          width: 50,
          align: 'center',
          fixed: 'left'
        },
        {
          prop: 'processTypeName',
          label: '流程分类',
          align: 'center',
          width: 150,
          showOverflowTooltip: true
        },
        {
          prop: 'key',
          label: '流程标识',
          align: 'center',
          width: 150,
          showOverflowTooltip: true
        },
        {
          prop: 'name',
          label: '流程名称',
          align: 'center',
          width: 150,
          showOverflowTooltip: true
        },
        {
          prop: 'formCustomCreatePath',
          label: '表单信息',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'createTime',
          label: '创建时间',
          align: 'center',
          width: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'version',
          label: '流程版本',
          align: 'center',
          width: 80,
          slot: "version",
          showOverflowTooltip: true
        },
        {
          prop: 'suspensionState',
          label: '激活状态',
          align: 'center',
          width: 80,
          slot: 'suspensionState',
          showOverflowTooltip: true
        },
        {
          prop: 'processDefinition.deploymentTime',
          label: '部署时间',
          align: 'center',
          width: 160,
          showOverflowTooltip: true
        },

        {
          columnKey: 'action',
          label: '操作',
          width: 500,
          align: 'center',
          resizable: false,
          slot: 'action',
          showOverflowTooltip: true
        }
      ],

      // 流程表单详情
      detailOpen: false,
      detailForm: {
        fields: []
      },

      // 流程表单
      title: "",
      open: false,
      form: {},

      // BPMN 数据
      showBpmnOpen: false,
      bpmnXML: null,
      processTypeList: [],
      bpmnControlForm: {
        prefix: "flowable"
      },

      // 表单校验
      rules: {
        key: [{required: true, message: "流程标识不能为空", trigger: "blur"}],
        name: [{required: true, message: "流程名称不能为空", trigger: "blur"}],
        processTypeId: [{required: true, message: "流程分类不能为空", trigger: "change"}],
      },


    };
  },
  created() {
    this.requestDict('工作流任务分配规则的类型');
    this.getProcessTypeList()
  },
  computed: {
    // 是否开启响应式布局
    styleResponsive() {
      return this.$store.state.theme.styleResponsive;
    }
  },
  watch: {
    open(nV) {
      if (!nV) {
        this.reset();
      }

    }
  },
  methods: {
    handleProcessType(val) {
      if (!val) return this.form.processTypeName = ''
      let node = this.$refs.processTypeRef.$refs.tree.getCurrentNode()
      this.form.processTypeName = node.name
    },
    async getProcessTypeList() {
      this.processTypeList = []
      const data = await getProduceTreeByCode('PROCESS001')

      if (data[0]?.id) {
        const res = await getTreeByPid(data[0]?.id)
        this.processTypeList = res.data[0]?.children || []
      }
    },

    /* 表格数据源 */
    async datasource({page, where, limit}) {
      return await getModelPage({
        pageNo: page,
        pageSize: limit,
        ...where
      });
    },
    /* 刷新表格 */
    reload(params) {
      if (params && params.reset) {
        this.$refs.table.reload({page: 1, where: params});
      } else {
        this.$refs.table.reload({where: params});
      }
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        key: undefined,
        name: undefined,
        description: undefined,
        category: undefined,
        formType: undefined,
        formId: undefined,
        formCustomCreatePath: undefined,
        formCustomViewPath: undefined
      };
      console.log(this.$refs.form);
      this.$refs.form.resetFields();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.title = "新建模型";
      this.open = true;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true;
      this.title = "修改模型";
      // 设置 form
      this.form = {
        ...row
      };
    },

    /** 设计按钮操作 */
    handleDesign(row) {
      this.$router.push({
        name: "设计流程",
        query: {
          modelId: row.id
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        const that = this;
        if (!valid) {
          return;
        }
        // 更新
        if (this.form.id) {
          updateModel({
            ...this.form,
          }).then(response => {
            this.$message.success('修改模型成功');
            that.reload();
            that.cancel();
          });
          return;
        }
        // 创建
        createModel(this.form).then(response => {
          this.open = false;
          this.reload();
          this.$alert('<strong>新建模型成功！</strong>后续需要执行如下 4 个步骤：' +
            '<div>1. 点击【修改流程】按钮，配置流程的分类、表单信息</div>' +
            '<div>2. 点击【设计流程】按钮，绘制流程图</div>' +
            '<div>3. 点击【分配规则】按钮，设置每个用户任务的审批人</div>' +
            '<div>4. 点击【发布流程】按钮，完成流程的最终发布</div>' +
            '另外，每次流程修改后，都需要点击【发布流程】按钮，才能正式生效！！！',
            '重要提示', {
              dangerouslyUseHTMLString: true,
              type: 'success'
            });
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const that = this;
      this.$confirm('是否删除该流程？？？', '删除', {
        type: 'warning'
      })
        .then(() => {
          deleteModel(row.id).then(response => {
            that.reload();
            this.$message.success('删除成功');
          })
        })
        .catch(() => {
        });
    },
    /** 部署按钮操作 */
    handleDeploy(row) {
      const that = this;
      this.$confirm('是否部署该流程？？？')
        .then(() => {
          deployModel(row.id).then(response => {
            that.reload();
            this.$message.success('部署成功');
          }).catch(() => {
          });
        })
        .catch(() => {
        });
    },
    /** 流程图的详情按钮操作 */
    handleBpmnDetail(row) {
      getModel(row.id).then(response => {
        this.bpmnXML = response.data.bpmnXml
        // 弹窗打开
        this.showBpmnOpen = true
      })
    },
    /** 跳转流程定义的列表 */
    handleDefinitionList(row) {
      this.$router.push({
        name: "流程定义",
        query: {
          key: row.key
        }
      });
    },
    /** 更新状态操作 */
    handleChangeState(row) {
      const that = this;

      const id = row.id;
      let state = row.processDefinition.suspensionState;
      let statusState = state === 1 ? '激活' : '挂起';

      this.$confirm('是否确认' + statusState + '流程名字为"' + row.name + '"的数据项?')
        .then(() => {
          return updateModelState(id, state);
        }).then(() => {
        that.reload();
        this.$message.success(statusState + "成功");
      })
        .catch(() => {
          // 取消后，进行恢复按钮
          row.processDefinition.suspensionState = (state === 1 ? 2 : 1);
        });
    },

    /** 处理任务分配规则列表的按钮操作 */
    handleAssignRule(row) {
      this.$refs['taskAssignRuleDialog'].initModel(row.id);
    },

  }
};
</script>
<style scoped>
.app-container {
  padding: 10px;
}

.filter-container .filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 5px;
  margin-right: 4px;
}

.filter-container {
  padding-bottom: 5px;
}
</style>
