<!--
 * @Author: ysh
 * @Date: 2024-06-21 18:51:54
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-07-21 12:28:43
-->
<template>
  <div class="app-container">
    <h2 style="text-align: center;">项目安排</h2>
    <el-form ref="arrangeForm" :model="form" :rules="rules" label-width="120px" :disabled="disabled">
      <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="项目负责人：" prop="projectLeader">
            <el-select v-model="peopleForm.deptId" filterable @change="handleChangeDept" clearable style="width:60%">
              <el-option v-for="item, index in peopleForm.deptList" :key="'d' + index" :label="item.deptName"
                :value="item.deptId" v-if="item.deptName != '四川中水成勘院测绘工程有限责任公司'">
              </el-option>
            </el-select>
            <el-select v-model="form.projectLeader" placeholder="请选择项目负责人" clearable style="width:40%">
              <el-option v-for="item, index in peopleForm.userList" :key="'l' + index" :label="item.nickName"
                :value="item.userId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="现场负责人：" prop="siteLeader">
            <el-select v-model="form.siteLeader" filterable clearable style="width:100%">
              <el-option v-for="item, index in peopleForm.allDeptUserList" :key="'s' + index" :label="item.nickName"
                :value="item.userId" v-if="item.nickName != 'admin'">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button type="danger" @click="$emit('returnBack')" :disabled="disabled">退 回</el-button>
      <el-button type="warning" @click="save" :disabled="disabled">保 存</el-button>
      <el-button type="primary" @click="confirmPlanForm" :disabled="disabled">提 交</el-button>
    </div>
  </div>
</template>

<script>
import { listDept } from '@/api/system/dept'
import { listUser } from '@/api/system/user'
import { getUsersDeptLeaderByDept, getDeptLeadersByDeptId, getUsersManageLeaderByDept } from '@/api/system/post'
import { complete, rejectTask, returnList, returnTask, getNextFlowNode, delegate, flowTaskForm, } from "@/api/flowable/todo";
import { listProject, getProject, addProject, updateProject, delProject, submitProject, modifyProject } from "@/api/oa/project/project";
import { listSubProcInstId, delDeployment } from "@/api/flowable/finished"
import { cancelSubProcess } from '@/utils/cancelSubProcess';
export default {
  props: {
    disabled: {
      type: Boolean
    },
    taskForm: {
      type: Object,
      required: true
    },
    taskName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      form: {},
      rules: {
        deptId: [
          { required: true, message: "请选择承担部门", trigger: "change" }
        ],
        projectLeader: [
          { required: true, message: "请选择项目负责人", trigger: "change" }
        ]
      },
      deptList: [],
      deptLeaderList: [],
      file: {
        fileList: []
      },
      peopleVisible: false,
      peopleForm: {
        deptId: '',
        deptList: [],
        userId: '',
        userList: [],
        allDeptUserList: []
      },
    }
  },
  created() {

  },
  mounted() {
    this.getDeptList();
    this.initForm();
  },
  methods: {
    async initForm() {
      let datas = await listProject({ projectId: this.taskForm.formId });
      if (datas.rows.length > 0) {
        getProject(this.taskForm.formId).then(res => {
          this.form = res.data;
          if (this.form.undertakingDept != null && this.form.undertakingDept != "" && this.form.undertakingDept != undefined) {
            this.form.deptId = this.form.undertakingDeptName.split(',')
          }
          if (this.form.projectLeaderUser) {
            this.form.projectLeaderName = this.form.projectLeaderUser.nickName
          }
          this.$set(this.form, 'deptLeader', [])
          if (this.form.undertakingDept) {
            let arr = (this.form.undertakingDept.split(',')).map(Number)
            this.$set(this.form, 'deptId', arr)
            this.getDeptLeader(arr);
            this.getProjectLeaderDeptId();
          } else {
            this.$set(this.form, 'deptId', [])
          }
          this.$store.commit('SET_PROJECTNUMBER', this.form.projectNumber)
          this.$store.commit('SET_PROJECTNAME', this.form.projectName)
          this.$store.commit('SET_PROJECT', this.form)
        })
      } else {
        let kcDatas = await listProject({ projectId: this.taskForm.formId, undertakingDept: 113 }); //勘察设计事业部的项目
        if (kcDatas.rows.length > 0) {
          getProject(this.taskForm.formId).then(res => {
            this.form = res.data;
            if (this.form.undertakingDept != null && this.form.undertakingDept != "" && this.form.undertakingDept != undefined) {
              this.form.deptId = this.form.undertakingDeptName.split(',')
            }
            if (this.form.projectLeaderUser) {
              this.form.projectLeaderName = this.form.projectLeaderUser.nickName
            }
            this.$set(this.form, 'deptLeader', [])
            if (this.form.undertakingDept) {
              let arr = (this.form.undertakingDept.split(',')).map(Number)
              this.$set(this.form, 'deptId', arr);
              this.getDeptLeader(arr);
            } else {
              this.$set(this.form, 'deptId', [])
            }
            this.$store.commit('SET_PROJECTNUMBER', this.form.projectNumber)
            this.$store.commit('SET_PROJECTNAME', this.form.projectName)
            this.$store.commit('SET_PROJECT', this.form)
          })
        }
      }

    },
    getDeptList() {
      listDept({
        deptName: undefined,
        status: undefined
      }).then(res => {
        this.deptList = res.data
        this.peopleForm.deptList = res.data
        console.log(this.peopleForm.deptList)
      })
    },
    async getDeptLeader(val) {
      this.deptLeaderList = [];
      for (let v of val) {
        let res = await getUsersDeptLeaderByDept({ deptId: Number(v) })
        this.deptLeaderList.push(res.data.userId);
        this.form.deptLeader = this.deptLeaderList;
      }
      val.forEach(item => {
        listUser({ pageSize: 999, deptId: item }).then(res => {
          res.rows.forEach(row => {
            this.peopleForm.allDeptUserList.push(row)
          })
        })
      })
    },
    // 人员选择
    choosePeople() {
      this.peopleVisible = true;
    },
    // 改变部门选择
    handleChangeDept(deptId) {
      this.peopleForm.userId = '';
      listUser({ pageSize: 999999, deptId: deptId }).then(res => {
        this.peopleForm.userList = res.rows
        for (let a of res.rows) {
          this.peopleForm.allDeptUserList.push(a)
        }
        // 去重
        const seenIds = new Set();
        const uniqueArray = [];
        this.peopleForm.allDeptUserList.forEach(item => {
          if (!seenIds.has(item.userId)) {
            seenIds.add(item.userId);
            uniqueArray.push(item);
          }
        });
        this.peopleForm.allDeptUserList = uniqueArray
      })
    },
    getProjectLeaderDeptId() {
      let userList = this.$store.state.user.userList;
      let leaderUser = userList.find(item => item.userId == this.form.projectLeader);
      this.peopleForm.deptId = leaderUser.deptId;
      this.handleChangeDept(leaderUser.deptId);
    },
    // 确定项目负责人
    confirmPeople() {
      this.form.projectLeader = this.peopleForm.userId;
      this.form.projectLeaderName = this.tagLeader()
      this.peopleVisible = false
    },
    tagLeader() {
      if (this.form.projectLeader == '' || this.form.projectLeader == undefined || this.form.projectLeader == null) {
        return undefined
      } else {
        for (let user of this.peopleForm.userList) {
          if (this.form.projectLeader == user.userId) {
            return user.nickName
          }
        }
      }
    },
    save() {
      this.$refs['arrangeForm'].validate((vaild) => {
        if (vaild) {
          this.form.projectId = this.taskForm.formId;
          this.form.undertakingDept = this.form.deptId.join(',');
          updateProject(this.form).then(res => {
            this.$message.success('保存成功')
          })
        } else {
          this.$message.error('请完善必填项')
        }
      })
    },
    async confirmPlanForm() {
      let resProcInstId = await listSubProcInstId({ instanceId: this.taskForm.procInsId });
      let ids = resProcInstId.data.map(item => item.id);
      if (ids.length > 0) {
        cancelSubProcess(ids, this.taskForm.formId).then(res => {
          if (res.code == 200) {
            this.sendConfirm();
          }
        })
      } else {
        this.sendConfirm();
      }
    },
    sendConfirm() {
      this.$confirm('项目安排之后会自动发起预算编制、技术方案、安全交底三个子流程，将无法进行撤回操作，是否继续提交？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.save();
        let resData = await getUsersManageLeaderByDept({ deptId: 105 });
        let approvalId;
        if (resData.data) {
          approvalId = resData.data[0].userId;
        }
        this.$refs['arrangeForm'].validate((vaild) => {
          if (vaild) {
            const params = { taskId: this.taskForm.taskId };
            // 获取下一个流程节点
            getNextFlowNode(params).then(res => {
              this.$set(this.taskForm.variables, "formId", this.taskForm.formId);
              this.$set(this.taskForm.variables, "budgetInitiator", this.form.projectLeader);
              this.$set(this.taskForm.variables, "planInitiator", this.deptLeaderList[0]);
              this.$set(this.taskForm.variables, "approval", approvalId);
              complete(this.taskForm).then(response => {
                this.$modal.msgSuccess(response.msg);
                this.$emit('goBack');
              });
            })
          } else {
            this.$message.error('请完善必填项')
          }
        })
      })
    },
    cancel() {
      this.form = {}
    },
    setOrganizeDocument(val) {
      let arr = val.split('/upload')
      this.form.organizeDocument = arr[1]
      if (val == "") {
        this.form.organizeDocument = ""
      }
    },
    getFileName(name) {
      if (name != null) {
        let arr = name.split('/')
        return arr[arr.length - 1];
      }

    },
    handleFileDelete() {
      // this.$refs.orz.handleDelete(0);
    },
  }
}
</script>

<style lang="scss" scoped></style>