<!--
 * @Author: ysh
 * @Date: 2024-03-19 09:24:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-07-10 17:51:06
-->
<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="deptId">
            <el-select v-model="form.deptId" multiple clearable style="width:100%" @change="getDeptLeader">
              <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId"
                v-if="item.deptName != '四川中水成勘院测绘工程有限责任公司'">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="部门负责人：" prop="deptLeader">
            <el-select v-model="form.deptLeader" multiple clearable style="width:100%">
              <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="项目负责人：" prop="projectLeader">
            <el-select v-model="form.projectLeader" placeholder="请选择项目负责人" size="large" disabled>
              <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
            </el-select>
            <!-- <el-tag effect="plain" type="warning" style="margin-right: 10px;"
              v-if="form.projectLeader != '' && form.projectLeader != undefined">{{
      form.projectLeaderName }}</el-tag> -->
            <el-button type="primary" plain icon="el-icon-plus" @click="choosePeople">选择</el-button>
          </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 in $store.state.user.userList" :key="item.userId" :label="item.nickName"
                :value="item.userId" v-if="item.nickName != 'admin'">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="组织交底日期：" prop="organizeTime">
            <el-date-picker style="width: 100%;" v-model="form.organizeTime" value-format="yyyy-MM-dd" type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="组织交底文档：" prop="organizeDocument">
            <div v-if="form.organizeDocument" class="upload-list">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.organizeDocument}`)">
                {{ getFileName(form.organizeDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.organizeDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
            <FileUpload v-if="taskName == '项目安排'" ref="orz" :limit="1" :filePathName="'组织交底文件'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf']" @input="setOrganizeDocument">
            </FileUpload>
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <!-- 人员选择对话框 -->
    <el-dialog width="320px" title="选择项目负责人" :visible.sync="peopleVisible" append-to-body>
      <el-form>
        <el-form-item label="部门：">
          <el-select v-model="peopleForm.deptId" @change="handleChangeDept">
            <el-option v-for="item in peopleForm.deptList" :key="item.deptId" :label="item.deptName"
              :value="item.deptId" v-if="item.deptName != '四川中水成勘院测绘工程有限责任公司'">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人员：">
          <el-select v-model="peopleForm.userId">
            <el-option v-for="item in peopleForm.userList" :key="item.userId" :label="item.nickName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button @click="confirmPeople" type="primary">确定</el-button>
          <el-button @click="cancelChoosePeople">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <!-- <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";
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: []
      },
    }
  },
  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);
          } 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
      })
    },
    getDeptLeader(val) {
      this.deptLeaderList = [];
      for (let v of val) {
        getUsersDeptLeaderByDept({ deptId: Number(v) }).then(res => {
          this.deptLeaderList.push(res.data.userId);
          this.form.deptLeader = this.deptLeaderList;
        })
      }
    },
    // 人员选择
    choosePeople() {
      this.peopleVisible = true;
    },
    // 改变部门选择
    handleChangeDept(deptId) {
      this.peopleForm.userId = '';
      listUser({ pageSize: 999999, deptId }).then(res => {
        this.peopleForm.userList = res.rows
      })
    },
    // 确定项目负责人
    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
          }
        }
      }
    },
    cancelChoosePeople() {
      this.peopleForm.deptId = '';
      this.peopleForm.userId = '';
      this.peopleVisible = false;
    },
    save() {
      this.$refs['arrangeForm'].validate((vaild) => {
        if (vaild) {
          this.form.projectId = this.taskForm.formId;
          this.form.undertakingDept = this.form.deptId.join(',');
          updateProject(this.form)
        }
      })
    },
    confirmPlanForm() {
      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;
        }
        console.log(approvalId);
        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.peopleForm.userId || this.form.projectLeader);
          this.$set(this.taskForm.variables, "planInitiator", this.peopleForm.userId || this.form.projectLeader);
          this.$set(this.taskForm.variables, "approval", approvalId);
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('goBack');
          });
        })
      })

    },
    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>