
<template>
  <div class="page">
    <LayoutTable :data="tableData" :config="tableConfig" notAdd notDel>
    </LayoutTable>

    <el-dialog
      append-to-body
      :title="taskDialog.title"
      :visible.sync="taskDialog.visible"
    >
      <el-form ref="form1" :model="form" label-width="120px">
        <el-form-item label="选择人员">
          <el-select
            style="width: 50%"
            v-model="assignee"
            @change="handleCheckChange"
            :multiple="taskDialog.multiple"
            placeholder="请选择"
          >
            <el-option
              v-for="item in userDataList"
              :key="item.loginName"
              :label="item.realName"
              :value="item.loginName"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="taskConfirm">确 定</el-button>
        <el-button @click="taskCancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      append-to-body
      :title="siteDialog.title"
      :visible.sync="siteDialog.visible"
    >
      <el-form label-width="120px">
        <el-form-item label="选择站点">
          <treeselect
            v-model="siteId"
            :options="siteOptions"
            placeholder="请选择站点"
          />
        </el-form-item>

        <el-form-item label="选择角色">
          <el-select
            v-model="roleId"
            :multiple="siteDialog.multiple"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="siteConfirm">确 定</el-button>
        <el-button @click="siteDialog.visible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="configDialog.title"
      :visible.sync="configDialog.visible"
      width="90%"
      append-to-body
    >
      <!-- 动态创建对应关系 表格 -->

      <el-form ref="form" :model="form" label-width="120px">
        <el-table
          :data="dataList"
          border
          style="margin-top: 10px"
          max-height="480"
          :key="Math.random()"
        >
          <el-table-column prop="name" label="任务名称"> </el-table-column>

          <el-table-column prop="assignee" label="审批人员"> </el-table-column>
          <el-table-column prop="candidateUsers" label="审批候选人">
          </el-table-column>

          <el-table-column prop="candidateGroups" label="审批候选组">
          </el-table-column>

          <!-- <el-table-column prop="el" label="EL变量表达式"> </el-table-column> -->

          <el-table-column
            prop="multiple"
            label="是否并行"
            :formatter="formatter"
          >
          </el-table-column>

          <el-table-column prop="assigneeName" label="对应人员">
          </el-table-column>

          <el-table-column prop="candidateUsersName" label="对应候选人员">
          </el-table-column>

          <el-table-column prop="candidateGroupsName" label="对应站点与角色">
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-user"
                  @click="handSelectUser(scope.$index, scope.row)"
                  >选择审批人员</el-button
                >

                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-user"
                  @click="handSelectCandidateUsers(scope.$index, scope.row)"
                  >选择候选人员</el-button
                >

                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-user"
                  @click="handSelectSiteAndRole(scope.$index, scope.row)"
                  >选择站点角色</el-button
                >
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfigForm">确 定</el-button>
        <el-button @click="configDialog.visible = false">取 消</el-button>
      </div>
    </el-dialog>

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

<script>
import {
  updateState,
  definitionStart,
  readXml,
  userList,
} from "@/api/flowable/definition";
import table from "@/assets/mixins/table";
import flow from "@/views/flowable/task/record/flow";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Definition",
  components: {
    flow,
    Treeselect,
  },
  mixins: [table],

  created() {
    userList({}).then(({ data }) => {
      this.userDataList = data.result;

      for (let item of data.result) {
        this.userDict[item.loginName] = item.realName;
      }
    });

    this.getTreeselect();
    this.getRoleList();
  },

  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      this.loading = true;
      this.$post("/site/treeselect", {})
        .then((res) => {
          if (res && res.code && res.code == 1) {
            this.siteOptions = res.data.result;
            this.loading = false;
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },

    getRoleList() {
      this.loading = true;
      this.$post("/role/list", {"query.roleType":2, "pageInfo.prePageResult": "-1" })
        .then((res) => {
          if (res && res.code && res.code == 1) {
            this.roleList = res.data.result;
            this.loading = false;
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },

    submitConfigForm() {
      let params = {};
      params[this.configDialog.key] = JSON.stringify(this.dataList);

      this.$post("/flowable/definition/setVars", params).then(({ data }) => {
        this.configDialog.visible = false;
        //弹出框配置对应关系
      });
    },
    taskConfirm() {
      if (this.taskDialog.multiple == 0) {
        this.dataList[this.taskDialog.index].assignee = this.assignee;
        this.dataList[this.taskDialog.index].assigneeName =
          this.userDict[this.assignee];
      } else {
        let temp = "";
        for (let item of this.assignee) {
          temp += this.userDict[item] + ",";
        }
        this.dataList[this.taskDialog.index].assigneeName = temp;
        this.dataList[this.taskDialog.index].assigneeList = this.assignee;
      }

      this.taskDialog.visible = false;
    },

    taskCancel() {
      this.assignee = null;
      this.taskDialog.visible = false;
    },

    siteConfirm() {
      if (this.siteDialog.multiple == 0) {
        //组合选择的站点与角色  站点[角色]   目前都为单选

        console.log("this.siteID",this.siteId)
        console.log("siteOptions",this.tableData.dict)
        let siteName=this.tableData.dict["site"][this.siteId];
        let roleName="";
       //查找站点
      //  this.siteOptions.map(item=>{
      //    if(item.id===this.siteId){
      //      siteName=item.label;
      //    }
      //  })
        this.roleList.map(item=>{
         if(item.id===this.roleId){
           roleName=item.name;
         }
       })
        this.dataList[this.siteDialog.index].candidateGroupsIds = this.siteId+"["+this.roleId+"]";
        this.dataList[this.siteDialog.index].candidateGroupsName =siteName+"["+roleName+"]";
      } else {
        let temp = "";
        for (let item of this.assignee) {
          temp += this.userDict[item] + ",";
        }
        this.dataList[this.siteDialog.index].assigneeName = temp;
        this.dataList[this.siteDialog.index].assigneeList = this.assignee;
      }

      this.siteDialog.visible = false;
    },

    handleCheckChange(val) {
      if (val instanceof Array) {
        console.log(1111, val);
      } else {
        console.log(222222, val);
      }
    },

    handSelectUser(index, row) {
      console.log("审批人员选择，单选", index, row);
      this.assignee = null;
      this.assigneeName = "";

      this.taskDialog.index = index;

      if (row.multiple == 0) {
        this.taskDialog.multiple = false;
      } else {
        this.taskDialog.multiple = true;
      }
      this.taskDialog.visible = true;
    },

    handSelectCandidateUsers(index, row) {
      console.log("审批候选人员选择，多选", index, row);
      this.assignee = null;
      this.assigneeName = "";

      this.taskDialog.index = index;

      if (row.multiple == 0) {
        this.taskDialog.multiple = false;
      } else {
        this.taskDialog.multiple = true;
      }
      this.taskDialog.visible = true;
    },

    handSelectSiteAndRole(index, row) {
      console.log("审批候选组选择，多选", index, row);
      this.assignee = null;
      this.assigneeName = "";

      this.siteDialog.index = index;

      if (row.multiple == 0) {
        this.siteDialog.multiple = false;
      } else {
        this.siteDialog.multiple = true;
      }
      this.siteDialog.visible = true;
    },

    /** 流程图查看 */
    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;
      });
    },

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

    /** 挂起/激活流程 */
    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();
      });
    },
    /** 修改配置参数 */
    handleUpdateVars(row) {
      console.log("修改配置参数!");
      console.log(row);

      let query = {};
      query.processDefinitionKey = row.key;

      this.$post("/flowable/definition/getAllProcessInstanceEl", query).then(
        ({ data }) => {
          console.log(data);

          this.dataList = data;
          this.configDialog.visible = true;
          this.configDialog.key = row.key;
        }
      );
      //查询所有el表达式
    },
  },
  data() {
    return {
      taskDialog: {
        visible: false,
        title: "选择人员",
        multiple: false,
        index: 0,
        type: "",
      },
      siteDialog: {
        visible: false,
        title: "选择站点角色",
        multiple: false,
        index: 0,
        type: "",
      },
      configDialog: {
        visible: false,
        title: "流程人员配置",
        index: 0,
      },
      siteOptions: [],
      roleList: [],
      userDataList: [], // 流程候选人
      userDict: {},
      siteId: null,
      roleId: null,
      assignee: null,
      dataList: [],
      // 遮罩层
      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: "",
      },

      // 查询参数
      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: "名称",
          },
        ],
        columns: [
          {
            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: "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.handleUpdateVars(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>
                  )}
                </el-row>
              );
            },
          },
        ],
      },
    };
  },
};
</script>
