<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    append-to-body
    :close-on-click-modal="false"
    width="70%"
    :before-close="cancel">
    <headerTitle title="计划信息"></headerTitle>
    <plan-form ref="planForm" :dialog-type.sync="dialogType" :dialogForm="dialogForm" :deptList="deptList"
               :deptTreeList="deptTreeList" :userList="userList" @changeProject="changeProject"></plan-form>
    <headerTitle title="计划节点"></headerTitle>
    <plan-info-table ref="planInfoTable" :dialog-type.sync="dialogType" :dialogForm="dialogForm" :deptList="deptList"
                     :deptTreeList="deptTreeList" :userList="userList"></plan-info-table>
    <div slot="footer">
      <el-button type="primary" size="small" @click="submit">保 存</el-button>
<!--      <el-button type="primary" size="small" @click="submit('sub')">提 交</el-button>-->
      <el-button size="small" @click="cancel">关 闭</el-button>
    </div>


  </ele-modal>
</template>


<script>
import projectForm from "./project-form.vue";
import planForm from "./plan-form.vue";
import planInfoTable from "./planInfoTable.vue";
import {
  getTargetPlanCode,
  projectsPlanGetByIdAPI,
  projectsPlanSaveAPI,
  projectsPlanUpdateAPI,
  submit
} from "@/api/project-manage/plan";
import {deepClone} from "@/utils";
import {getUserPage, listOrganizations} from "@/api/system/organization";
import {projectsTeamGetByIdAPI} from "@/api/project-manage/team";
import {projectsGetByIdAPI} from "@/api/project-manage";

export default {
  name: "addOrEditDialog",
  components: {
    projectForm,
    planForm,
    planInfoTable
  },
  props: {
    addOrEditDialogFlag: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      title: '',
      dialogType: '',
      dialogForm: {},
      userList: [],
      deptList: [],
      deptTreeList: [],
      allUserList: [],
    }
  },
  async created() {
    this.getDeptList();
    let {list} = await getUserPage({pageNum: 1, size: -1});
    this.allUserList = list
  },
  methods: {
    async init(row = {}, type) {
      this.title = type === 'add' ? '新增' : '编辑';
      this.dialogType = type;
      if (type !== 'add') {
        await this.getProjectPlanInfo(row.id)
      } else {
        this.dialogForm = {
          projectId: row.projectId,
          projectBomId: row.projectBomId,
          projectStageId: row.projectStageId,
          parentId: row.parentPlanId,
          code: await getTargetPlanCode()
        };

        if (this.dialogForm.projectId && !row.teamId) {
          const data = await projectsGetByIdAPI(this.dialogForm.projectId)
          if (data.teamId) this.getUserList(data.teamId);
        }else {
          if (row.teamId) this.getUserList(row.teamId);
        }

        //从项目直接新建计划，则获取项目团队

      }

    },
    async changeProject(id) {
      let projectInfo = await projectsGetByIdAPI(id)
      this.getUserList(projectInfo.teamId)
    },
    // 获取项目团队下团队人员集合
    getUserList(val) {
      if (!val) {
        this.userList = []
        return
      }
      projectsTeamGetByIdAPI(
        val
      ).then((list) => {
        this.userList = deepClone(list.teamUserList)
      });
    },
    // 获取部门数据
    getDeptList() {
      listOrganizations().then((list) => {
        this.deptList = list;
        this.deptTreeList = this.$util.toTreeData({
          data: list,
          idField: 'id',
          parentIdField: 'parentId'
        });
      });
    },
    // 获取计划信息
    async getProjectPlanInfo(id = '') {
      let res = await projectsPlanGetByIdAPI(id)
      this.dialogForm = deepClone(res)
      this.dialogForm.responsibleUserIds = this.dialogForm.responsibleUserList.map(i => i.userId) || []
      this.dialogForm.planStageList.forEach((item, index) => {
        let userIds = item.responsibleUserList.map(i => i.userId) || []
        this.$set(item, 'responsibleUserIds', userIds)
      })
      if (this.dialogForm.projectId) await this.changeProject(this.dialogForm.projectId)
    },
    async submit(type = '') {
      let form = await this.$refs.planForm.validForm();
      form.planStageList = await this.$refs.planInfoTable.getTableValidate() || [];
      form.realStartDate = null
      form.realEndDate = null
      for (const item of form.planStageList) {
        item.responsibleUserList = await this.getResponsibleUserList(item.responsibleUserIds)
      }
      form.responsibleUserList = await this.getResponsibleUserList(form.responsibleUserIds)
      const API = this.dialogType === 'add' ? projectsPlanSaveAPI : projectsPlanUpdateAPI;
      const id = await API(form)
      if (type === 'sub') {
        this.processSubmit(id);
        return
      }
      this.$message.success('操作成功');
      this.cancel()
      this.$emit('reload');
    },
    async getResponsibleUserList(list = []) {
      return list.map(
        i => {
          return {
            userId: i,
            userName: this.allUserList?.find(u => u.id === i).name
          }
        });
    },
    //流程提交
    processSubmit(id = '') {
      submit({
        planId: id || this.dialogForm.id
      }).then((res) => {
        this.$message.success('提交成功');
        this.cancel();
        this.$emit('reload');
      });
    },
    cancel() {
      this.$emit('update:addOrEditDialogFlag', false);
    },
  }
}
</script>


<style scoped lang="scss">

</style>
