<template>
  <div>
    <!-- 列表弹窗 -->
    <el-dialog
      title="任务分配规则"
      :visible.sync="visible"
      width="800px"
      append-to-body
    >
      <el-table v-loading="loading" :data="list">
        <el-table-column
          label="任务名"
          align="center"
          prop="taskDefinitionName"
          width="120"
          fixed
        />
        <el-table-column
          label="任务标识"
          align="center"
          prop="taskDefinitionKey"
          width="120"
          show-tooltip-when-overflow
        />
        <el-table-column
          label="规则类型"
          align="center"
          prop="type"
          width="120"
        >
          <template v-slot="scope">
            {{ getDictValue('工作流任务分配规则的类型', scope.row.type + '') }}
          </template>
        </el-table-column>
        <el-table-column
          label="规则范围"
          align="center"
          prop="options"
          width="440px"
        >
          <template v-slot="scope">
            <el-tag
              size="medium"
              v-if="scope.row.type !== 60 && scope.row.options.length > 0"
              :key="option"
              v-for="option in scope.row.options"
            >
              {{ getAssignRuleOptionName(scope.row, option) }}
            </el-tag>
            <el-tag size="medium" v-if="scope.row.type === 60">
              {{ getAssignRuleOptionName(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="modelId"
          label="操作"
          align="center"
          width="250"
          fixed="right"
        >
          <template v-slot="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdateTaskAssignRule(scope.row)"
              >修改任务规则</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="ccHandleUpdateTaskAssignRule(scope.row)"
              >修改抄送规则</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 添加/修改弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form
        ref="taskAssignRuleForm"
        :model="form"
        :rules="rules"
        label-width="110px"
      >
        <el-form-item label="任务名称" prop="taskDefinitionName">
          <el-input v-model="form.taskDefinitionName" disabled />
        </el-form-item>
        <el-form-item label="任务标识" prop="taskDefinitionKey">
          <el-input v-model="form.taskDefinitionKey" disabled />
        </el-form-item>
        <el-form-item label="规则类型" prop="type">
          <el-select
            v-model="form.typeS"
            clearable
            style="width: 100%"
            @change="emptyingRules"
          >
            <el-option
              v-for="dict in this.dict[
                this.dictEnum['工作流任务分配规则的类型']
              ] || []"
              :key="parseInt(dict.dictCode)"
              :label="dict.dictValue"
              :value="parseInt(dict.dictCode)"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.typeS === 10" label="指定角色" prop="roleIds">
          <el-select
            v-model="form.roleIds"
            multiple
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.typeS === 20 || form.typeS === 21"
          label="指定部门"
          prop="deptIds"
        >
          <treeSelect
            v-model="form.deptIds"
            :options="deptTreeOptions"
            multiple
            flat
            :defaultExpandLevel="3"
            placeholder="请选择指定部门"
            :normalizer="normalizer"
          />
        </el-form-item>
        <el-form-item
          v-if="form.typeS === 22"
          label="指定工种"
          prop="workTypeIds"
        >
          <el-select
            v-model="form.workTypeIds"
            multiple
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in this.dict[this.dictEnum['工种']] || []"
              :key="dict.dictCode"
              :label="dict.dictValue"
              :value="dict.dictCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.typeS === 30 || form.typeS === 31 || form.typeS === 32"
          label="指定用户"
          prop="userIds"
        >
          <el-select
            v-model="form.userIds"
            multiple
            clearable
            style="width: 100%"
            :filterable="true"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.type === 40"
          label="指定用户组"
          prop="userGroupIds"
        >
          <el-select
            v-model="form.userGroupIds"
            multiple
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in userGroupOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.typeS === 50" label="指定脚本" prop="scripts">
          <el-select
            v-model="form.scripts"
            multiple
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in this.dict[
                this.dictEnum['工作流任务分配自定义脚本']
              ] || []"
              :key="dict.dictCode"
              :label="dict.dictValue"
              :value="dict.dictCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.typeS === 70 && title != '修改抄送规则'"
          label="审核方向"
          prop="direction"
        >
          <el-select
            v-model="form.direction"
            clearable
            style="width: 100%"
            @change="handleChangeDirection"
          >
            <el-option key="0" label="从下到上" value="0" />
            <el-option key="1" label="从上到下" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.typeS === 70 && title != '修改抄送规则'"
          label="指定部门负责人"
          prop="topLevel"
        >
          <el-select
            v-if="form.direction == 0"
            v-model="form.topLevel"
            clearable
            style="width: 100%"
          >
            <el-option key="1" label="直接部门负责人" value="1" />
            <el-option key="2" label="上二级部门负责人" value="2" />
            <el-option key="3" label="上三级部门负责人" value="3" />
            <el-option key="4" label="上四级部门负责人" value="4" />
            <el-option key="5" label="上五级部门负责人" value="5" />
            <el-option key="6" label="上六级部门负责人" value="6" />
            <el-option key="7" label="上七级部门负责人" value="7" />
            <el-option key="8" label="上八级部门负责人" value="8" />
            <el-option key="9" label="上九级部门负责人" value="9" />
          </el-select>
          <el-select
            v-else
            v-model="form.topLevel"
            clearable
            style="width: 100%"
          >
            <el-option key="99" label="最高级部门负责人" value="99" />
            <el-option key="2" label="第二层部门负责人" value="2" />
            <el-option key="3" label="第三层部门负责人" value="3" />
            <el-option key="4" label="第四层部门负责人" value="4" />
            <el-option key="5" label="第五层部门负责人" value="5" />
            <el-option key="6" label="第六层部门负责人" value="6" />
            <el-option key="7" label="第七层部门负责人" value="7" />
            <el-option key="8" label="第八层部门负责人" value="8" />
            <el-option key="9" label="第九层部门负责人" value="9" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.typeS === 60"
          label="自定义变量"
          prop="variableName"
        >
          <el-input
            placeholder="请输入自定义变量名称"
            v-model="form.variableName"
            clearable
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitAssignRuleForm"
          v-if="title == '修改任务规则'"
          >确 定</el-button
        >
        <el-button
          type="primary"
          @click="ccSubmitAssignRuleForm"
          v-if="title == '修改抄送规则'"
          >确 定</el-button
        >

        <el-button @click="cancelAssignRuleForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import dictMixins from '@/mixins/dictMixins';
  import {
    createTaskAssignRule,
    getTaskAssignRuleList,
    updateTaskAssignRule
  } from '@/api/bpm/taskAssignRule';
  import { listRoles } from '@/api/system/role';
  import {
    listOrganizations,
    listAllUserBind
  } from '@/api/system/organization';
  // import {listSimplePosts} from "@/api/system/post";
  import { listSimpleUserGroups } from '@/api/bpm/userGroup';

  import treeSelect from '@riophae/vue-treeselect';
  import '@riophae/vue-treeselect/dist/vue-treeselect.css';

  export default {
    name: 'BpmTaskAssignRule',
    components: {
      treeSelect
    },
    mixins: [dictMixins],
    data() {
      const varValidator = (rule, value, callback) => {
        if (/[a-zA-z]$/.test(value) === false) {
          callback(new Error('请输入英文'));
        } else {
          callback();
        }
      };

      return {
        // 如下参数，可传递
        modelId: undefined, // 流程模型的编号。如果 modelId 非空，则用于流程模型的查看与配置
        processDefinitionId: undefined, // 流程定义的编号。如果 processDefinitionId 非空，则用于流程定义的查看，不支持配置
        visible: false,
        title: '',
        // 任务分配规则表单
        row: undefined, // 选中的流程模型
        list: [], // 选中流程模型的任务分配规则们
        loading: false, // 加载中
        open: false, // 是否打开
        form: {}, // 表单
        rules: {
          // 表单校验规则
          type: [
            { required: true, message: '规则类型不能为空', trigger: 'change' }
          ],
          roleIds: [
            { required: true, message: '指定角色不能为空', trigger: 'change' }
          ],
          deptIds: [
            { required: true, message: '指定部门不能为空', trigger: 'change' }
          ],
          workTypeIds: [
            { required: true, message: '指定工种不能为空', trigger: 'change' }
          ],
          userIds: [
            { required: true, message: '指定用户不能为空', trigger: 'change' }
          ],
          userGroupIds: [
            { required: true, message: '指定用户组不能为空', trigger: 'change' }
          ],
          scripts: [
            { required: true, message: '指定脚本不能为空', trigger: 'change' }
          ],
          direction: [
            { required: true, message: '审核方向不能为空', trigger: 'change' }
          ],
          variableName: [
            { required: true, validator: varValidator, trigger: 'blur' }
          ]
        },

        // 各种下拉框
        roleOptions: [],
        deptOptions: [],
        deptTreeOptions: [],
        postOptions: [],
        userOptions: [],
        userGroupOptions: []
      };
    },
    created() {
      this.requestDict('工作流任务分配规则的类型');
      this.requestDict('工作流任务分配自定义脚本');
      this.requestDict('工种');
    },
    methods: {
      initModel(modelId) {
        this.modelId = modelId;
        this.processDefinitionId = undefined;

        // 初始化所有下拉框
        this.init0();
      },
      initProcessDefinition(processDefinitionId) {
        this.modelId = undefined;
        this.processDefinitionId = processDefinitionId;

        // 初始化所有下拉框
        this.init0();
      },
      /** 初始化 */
      init0() {
        // 设置可见
        this.visible = true;
        // 获得列表
        this.getList();

        // 获得角色列表
        this.roleOptions = [];
        listRoles({
          current: 1,
          size: 9999
        }).then((data) => {
          this.roleOptions.push(...data.list);
        });
        // 获得部门列表
        this.deptOptions = [];
        this.deptTreeOptions = [];
        listOrganizations().then((data) => {
          this.deptOptions.push(...data);
          this.deptTreeOptions.push(...this.handleTree(data, 'id'));
        });
        // 获得岗位列表 暂无岗位概念
        this.postOptions = [];
        /*listSimplePosts().then(response => {
          this.postOptions.push(...response.data);
        });*/
        // 获得用户列表
        this.userOptions = [];
        listAllUserBind().then((data) => {
          this.userOptions.push(...data);
        });
        // 获得用户组列表
        this.userGroupOptions = [];
        listSimpleUserGroups().then((response) => {
          this.userGroupOptions.push(...response);
        });
      },

      /**
       * 构造树型结构数据
       * @param {*} data 数据源
       * @param {*} id id字段 默认 'id'
       * @param {*} parentId 父节点字段 默认 'parentId'
       * @param {*} children 孩子节点字段 默认 'children'
       * @param {*} rootId 根Id 默认 0
       */
      handleTree(data, id, parentId, children, rootId) {
        id = id || 'id';
        parentId = parentId || 'parentId';
        children = children || 'children';
        rootId =
          rootId ||
          Math.min.apply(
            Math,
            data.map((item) => {
              return item[parentId];
            })
          ) ||
          0;
        //对源数据深度克隆
        const cloneData = JSON.parse(JSON.stringify(data));
        //循环所有项
        const treeData = cloneData.filter((father) => {
          let branchArr = cloneData.filter((child) => {
            //返回每一项的子级数组
            return father[id] == child[parentId];
          });
          branchArr.length > 0 ? (father.children = branchArr) : '';
          //返回第一层
          return father[parentId] == rootId;
        });
        return treeData !== '' ? treeData : data;
      },

      /** 获得任务分配规则列表 */
      getList() {
        this.loading = true;
        getTaskAssignRuleList({
          modelId: this.modelId,
          processDefinitionId: this.processDefinitionId
        }).then((data) => {
          this.loading = false;
          this.list = data;
        });
      },

      // 选择规则清空上一次选择内容
      emptyingRules(val) {
        if (this.title == '修改任务规则') {
          this.form.options = [];
          this.form.variableName = '';
          this.$set(this.form, 'direction', val == '70' ? '0' : '');
          this.$set(this.form, 'topLevel', val == '70' ? '1' : '');
        } else {
          this.form.ccOptions = [];
          this.form.ccVariableName = '';
        }
        this.form.roleIds = [];
        this.form.deptIds = [];
        this.form.workTypeIds = [];
        this.form.userIds = [];
        this.form.userGroupIds = [];
        this.form.scripts = [];
      },
      // 选择规则清空上一次选择内容
      handleChangeDirection(val) {
        this.$set(this.form, 'topLevel', val == '0' ? '1' : '99');
      },
      /** 处理修改抄送 分配规则的按钮操作 */
      ccHandleUpdateTaskAssignRule(row) {
        this.title = '修改抄送规则';
        // 先重置标识
        this.resetAssignRuleForm();
        // 设置表单
        this.form = {
          ...row,
          ccOptions: [],
          roleIds: [],
          deptIds: [],
          workTypeIds: [],
          userIds: [],
          userGroupIds: [],
          scripts: []
        };
        this.$set(this.form, 'typeS', row.ccType);
        // 将 options 赋值到对应的 roleIds 等选项
        if (row.ccType === 10) {
          this.form.roleIds.push(...row.ccOptions);
        } else if (row.ccType === 20 || row.ccType === 21) {
          this.form.deptIds.push(...row.ccOptions);
        } else if (row.ccType === 22) {
          this.form.workTypeIds.push(...row.ccOptions);
        } else if (
          row.ccType === 30 ||
          row.ccType === 31 ||
          row.ccType === 32
        ) {
          this.form.userIds.push(...row.ccOptions);
        } else if (row.ccType === 40) {
          this.form.userGroupIds.push(...row.ccOptions);
        } else if (row.ccType === 50) {
          this.form.scripts.push(...row.ccOptions);
        }
        this.open = true;
      },
      /** 处理修改任务分配规则的按钮操作 */
      handleUpdateTaskAssignRule(row) {
        this.title = '修改任务规则';
        // 先重置标识
        this.resetAssignRuleForm();
        // 设置表单
        this.form = {
          ...row,
          options: [],
          roleIds: [],
          deptIds: [],
          workTypeIds: [],
          userIds: [],
          userGroupIds: [],
          scripts: []
        };
        this.$set(this.form, 'typeS', row.type);
        // 将 options 赋值到对应的 roleIds 等选项
        if (row.type === 10) {
          this.form.roleIds.push(...row.options);
        } else if (row.type === 20 || row.type === 21) {
          this.form.deptIds.push(...row.options);
        } else if (row.type === 22) {
          this.form.workTypeIds.push(...row.options);
        } else if (row.type === 30 || row.type === 31 || row.type === 32) {
          this.form.userIds.push(...row.options);
        } else if (row.type === 40) {
          this.form.userGroupIds.push(...row.options);
        } else if (row.type === 50) {
          this.form.scripts.push(...row.options);
        } else if (row.type === 70) {
          let res = JSON.parse(row.variableName);
          this.$set(this.form, 'direction', res.direction);
          this.$set(this.form, 'topLevel', res.topLevel);
        }
        this.open = true;
      },
      /** 提交任务分配规则的表单 */
      submitAssignRuleForm() {
        this.$refs['taskAssignRuleForm'].validate((valid) => {
          if (valid) {
            // 构建表单
            this.form.type = this.form.typeS;
            let form = {
              ...this.form,
              taskDefinitionName: undefined
            };
            // 将 roleIds 等选项赋值到 options 中
            if (form.type === 10) {
              form.options = form.roleIds;
            } else if (form.type === 20 || form.type === 21) {
              form.options = form.deptIds;
            } else if (form.type === 22) {
              form.options = form.workTypeIds;
            } else if (
              form.type === 30 ||
              form.type === 31 ||
              form.type === 32
            ) {
              form.options = form.userIds;
            } else if (form.type === 40) {
              form.options = form.userGroupIds;
            } else if (form.type === 50) {
              form.options = form.scripts;
            } else if (form.type === 70) {
              form.variableName = JSON.stringify({
                direction: form.direction,
                topLevel: form.topLevel
              });
            }
            form.roleIds = undefined;
            form.deptIds = undefined;
            form.workTypeIds = undefined;
            form.userIds = undefined;
            form.userGroupIds = undefined;
            form.scripts = undefined;
            form.direction = undefined;
            form.topLevel = undefined;
            // 新增
            if (!form.id) {
              form.modelId = this.modelId; // 模型编号
              createTaskAssignRule(form).then((response) => {
                this.$message.success('修改成功');
                this.open = false;
                this.getList();
              });
              // 修改
            } else {
              form.taskDefinitionKey = undefined; // 无法修改
              updateTaskAssignRule(form).then((response) => {
                this.$message.success('修改成功');
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 提交任务分配规则的表单 */
      ccSubmitAssignRuleForm() {
        this.$refs['taskAssignRuleForm'].validate((valid) => {
          if (valid) {
            // 构建表单
            this.form.ccType = this.form.typeS;

            let form = {
              ...this.form,
              taskDefinitionName: undefined
            };
        
            // 将 roleIds 等选项赋值到 options 中
            if (form.ccType === 10) {
              form.ccOptions = form.roleIds;
              console.log( form.ccOptions)
           
            } else if (form.ccType === 20 || form.ccType === 21) {
              form.ccOptions = form.deptIds;
            } else if (form.ccType === 22) {
              form.ccOptions = form.workTypeIds;
            } else if (
              form.ccType === 30 ||
              form.ccType === 31 ||
              form.ccType === 32
            ) {
              form.ccOptions = form.userIds;
            } else if (form.ccType === 40) {
              form.ccOptions = form.userGroupIds;
            } else if (form.ccType === 50) {
              form.ccOptions = form.scripts;
            }
            form.roleIds = undefined;
            form.deptIds = undefined;
            form.workTypeIds = undefined;
            form.userIds = undefined;
            form.userGroupIds = undefined;
            form.scripts = undefined;
            form.direction = undefined;
            form.topLevel = undefined;
            console.log( form)
            // 新增
            if (!form.id) {
              form.modelId = this.modelId; // 模型编号
              createTaskAssignRule(form).then((response) => {
                this.$message.success('修改成功');
                this.open = false;
                this.getList();
              });
              // 修改
            } else {
              form.taskDefinitionKey = undefined; // 无法修改
              updateTaskAssignRule(form).then((response) => {
                this.$message.success('修改成功');
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 取消任务分配规则的表单 */
      cancelAssignRuleForm() {
        this.resetAssignRuleForm();
        this.open = false;
      },
      /** 表单重置 */
      resetAssignRuleForm() {
        this.form = {};
        this.resetForm('taskAssignRuleForm');
      },
      getAssignRuleOptionName(row, option) {
        if (row.type === 10) {
          for (const roleOption of this.roleOptions) {
            if (roleOption.id === option) {
              return roleOption.name;
            }
          }
        } else if (row.type === 20 || row.type === 21) {
          for (const deptOption of this.deptOptions) {
            if (deptOption.id === option) {
              return deptOption.name;
            }
          }
        } else if (row.type === 22) {
          option = option + ''; // 转换成 string
          for (const dictData of this.dict[this.dictEnum['工种']] || []) {
            if (dictData.dictCode === option) {
              return dictData.dictValue;
            }
          }
        } else if (row.type === 30 || row.type === 31 || row.type === 32) {
          for (const userOption of this.userOptions) {
            if (userOption.id === option) {
              return userOption.nickname || userOption.name;
            }
          }
        } else if (row.type === 40) {
          for (const userGroupOption of this.userGroupOptions) {
            if (userGroupOption.id === option) {
              return userGroupOption.name;
            }
          }
        } else if (row.type === 50) {
          option = option + ''; // 转换成 string
          for (const dictData of this.dict[
            this.dictEnum['工作流任务分配自定义脚本']
          ] || []) {
            if (dictData.dictCode === option) {
              return dictData.dictValue;
            }
          }
        } else if (row.type === 60) {
          return row.variableName;
        }
        return '未知(' + option + ')';
      },
      // 格式化部门的下拉框
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      }
    }
  };
</script>
