<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>发起流程</span>
      </div>
      <el-col :span="18" :offset="3">
        <div class="form-conf" v-if="formOpen">
          <parser :key="parserKey" :form-conf="formData" ref="parser" @getData="getData"/>
        </div>

        <!-- 审批负责人设置 -->
        <el-col :span="10" :offset="3">
          <el-form ref="approvalForm" :model="approvalForm" label-width="120px">
            <el-form-item label="指定审批人">
              <el-tag
                :key="index"
                v-for="(item, index) in approvalUsers"
                closable
                :disable-transitions="false"
                @close="handleClose(item)">
                {{ item.nickName }}
              </el-tag>
              <el-button class="button-new-tag" type="primary" icon="el-icon-plus" size="mini" circle @click="onSelectUsers" />
            </el-form-item>
          </el-form>
        </el-col>

        <!-- 提交和重置按钮 -->
        <div class="submit-buttons" v-if="formOpen">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-col>
    </el-card>

    <!-- 用户选择对话框 -->
    <el-dialog title="选择审批人" :visible.sync="userData.open" width="60%" append-to-body>
      <el-row type="flex" :gutter="20">
        <!--部门数据-->
        <el-col :span="5">
          <el-card shadow="never" style="height: 100%">
            <div slot="header">
              <span>部门列表</span>
            </div>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"/>
              <el-tree
                :data="deptOptions"
                :props="deptProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <KLPTable ref="userTable"
                    height="500"
                    v-loading="userLoading"
                    :data="userList"
                    highlight-current-row
                    @selection-change="handleSelectionChange">
            <el-table-column width="55" type="selection" />
            <el-table-column label="用户名" align="center" prop="nickName" />
            <el-table-column label="手机" align="center" prop="phonenumber" />
            <el-table-column label="部门" align="center" prop="dept.deptName" />
          </KLPTable>
          <pagination
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userData.open = false">取 消</el-button>
        <el-button type="primary" @click="submitUserData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getProcessForm, startProcess } from '@/api/workflow/process'
import Parser from '@/utils/generator/parser'
import { selectUser, deptTreeSelect } from '@/api/system/user'
import Pagination from '@/components/Pagination'

export default {
  name: 'WorkStart',
  components: {
    Parser,
    Pagination
  },
  data() {
    return {
      definitionId: null,
      deployId: null,
      procInsId: null,
      formOpen: false,
      formData: {},
      parserKey: 1,
      // 审批表单
      approvalForm: {
        approvalType: 1, // 默认指定用户
      },
      // 审批用户
      approvalUsers: [],
      userMultipleSelection: [],
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      userLoading: false,
      // 用户表格数据
      userList: null,
      deptProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        deptId: undefined
      },
      total: 0,
      // 用户数据
      userData: {
        open: false
      }
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.deployId = this.$route.params && this.$route.params.deployId;
      this.definitionId = this.$route.query && this.$route.query.definitionId;
      this.procInsId = this.$route.query && this.$route.query.procInsId;
      getProcessForm({
        definitionId: this.definitionId,
        deployId: this.deployId,
        procInsId: this.procInsId
      }).then(res => {
        if (res.data) {
          this.formData = res.data;
          // 表单按钮隐藏
          this.formData.formBtns = false;
          this.parserKey++   // 只有加载新表单时才更新 key
          this.formOpen = true
        }
      })
    },
    /** 接收子组件传的值 */
    getData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach(item => {
          const variableData = {};
          variableData.label = item.__config__.label
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach(val => {
              array.push(val)
            })
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue
          }
          variables.push(variableData)
        })
        this.variables = variables;
      }
    },
    // 提交表单
    submitForm() {
      const parserRef = this.$refs.parser;
      if (!parserRef) {
        this.$modal.msgError("表单未加载完成");
        return;
      }

      // 获取表单数据
      parserRef.getData();

      // 验证表单
      parserRef.$refs[parserRef.formConfCopy.formRef].validate(valid => {
        if (valid) {
          const formData = parserRef[parserRef.formConfCopy.formModel];

          // 添加审批人信息到表单数据
          // 根据审批类型添加不同的审批人信息
          if (this.approvalForm.approvalType === 1 && this.approvalUsers.length > 0) {
            // 指定用户
            formData.flowable = formData.flowable || {};
            formData.flowable.candidateUsers = this.approvalUsers.map(user => user.userId).join(',');
            formData.flowable.candidateGroups = '';
            formData.flowable.text = this.approvalUsers.map(user => user.nickName).join(',');
          }

          // 启动流程并将表单数据加入流程变量
          if (this.definitionId) {
            startProcess(this.definitionId, JSON.stringify(formData)).then(res => {
              this.$modal.msgSuccess(res.msg);
              this.$tab.closeOpenPage({
                path: '/work/own'
              });
            });
          } else {
            this.$modal.msgError("流程定义ID不存在");
          }
        } else {
          this.$modal.msgError("表单验证失败，请检查填写的内容");
        }
      });
    },

    // 重置表单
    resetForm() {
      const parserRef = this.$refs.parser;
      if (parserRef) {
        parserRef.$refs[parserRef.formConfCopy.formRef].resetFields();
      }
      this.approvalUsers = [];
      this.userMultipleSelection = [];
      this.approvalForm.approvalType = 1;
    },
    /** 查询部门下拉树结构 */
    getTreeSelect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询用户列表 */
    getList() {
      this.userLoading = true;
      selectUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.toggleSelection(this.userMultipleSelection);
        this.userLoading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.userMultipleSelection = selection;
    },
    toggleSelection(selection) {
      if (selection && selection.length > 0) {
        this.$nextTick(()=> {
          selection.forEach(item => {
            let row = this.userList.find(k => k.userId === item.userId);
            if (row) {
              this.$refs.userTable.toggleRowSelection(row);
            }
          })
        })
      } else {
        this.$nextTick(() => {
          this.$refs.userTable.clearSelection();
        });
      }
    },
    // 关闭标签
    handleClose(tag) {
      let userObj = this.userMultipleSelection.find(item => item.userId === tag.userId);
      if (userObj) {
        this.userMultipleSelection.splice(this.userMultipleSelection.indexOf(userObj), 1);
      }
      this.approvalUsers = this.userMultipleSelection;
    },
    onSelectUsers() {
      this.userMultipleSelection = this.approvalUsers;
      this.userData.open = true;
      this.getTreeSelect();
      this.getList();
    },
    submitUserData() {
      if (!this.userMultipleSelection || this.userMultipleSelection.length <= 0) {
        this.$modal.msgError("请选择用户");
        return false;
      }
      this.approvalUsers = this.userMultipleSelection;
      this.userData.open = false;
    },
    // 添加日期范围
    addDateRange(params, dateRange, propName) {
      let search = params;
      search = typeof(search) === 'object' && search !== null && !Array.isArray(search) ? search : {};
      dateRange = Array.isArray(dateRange) ? dateRange : [];
      if (typeof(propName) === 'undefined') {
        search['beginTime'] = dateRange[0];
        search['endTime'] = dateRange[1];
      } else {
        search['begin' + propName] = dateRange[0];
        search['end' + propName] = dateRange[1];
      }
      return search;
    }
  }
}
</script>

<style lang="scss" scoped>
.form-conf {
  margin: 15px auto;
  width: 80%;
  padding: 15px;
}
</style>
