<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="18" :xs="24">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="项目信息" prop="projectId">
            <el-button type="primary" size="mini" @click="openProject = true" v-if="taskName == '变更登记'">选择项目</el-button>
            <el-descriptions border v-if="isSelect" style="margin-top: 10px;" :column="2" direction="vertical">
              <el-descriptions-item label="项目名称" label-class-name="my-label">{{ chooseProject.projectName
                }}</el-descriptions-item>
              <el-descriptions-item label="项目编号" label-class-name="my-label">{{ chooseProject.projectNumber
                }}</el-descriptions-item>
              <el-descriptions-item label="甲方单位" label-class-name="my-label">{{ chooseProject.partyA.partyAName
                }}</el-descriptions-item>
              <el-descriptions-item label="项目类型" label-class-name="my-label">{{ chooseProject.projectType
                }}</el-descriptions-item>
              <el-descriptions-item label="承担部门" label-class-name="my-label">{{
      chooseProject.undertakingDeptName
    }}</el-descriptions-item>
              <el-descriptions-item label="项目负责人" label-class-name="my-label">{{ chooseProject.projectLeaderUser
      ? chooseProject.projectLeaderUser.nickName : ''
                }}</el-descriptions-item>=
            </el-descriptions>
          </el-form-item>
          <el-form-item label="变更内容" prop="content">
            <el-input type="textarea" :rows="10" v-model="form.content" :disabled="taskName != '变更登记'" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="签名：" label-width="120px">
                <span class="auditor"> {{ registrantName }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="登记时间" label-width="120px">
                <span> {{ parseTime(form.registerTime, '{y}-{m}-{d}') }} </span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: center;" v-if="taskName && taskName == '变更登记'">
          <el-button type="primary" @click="submitForm">提交申请</el-button>
        </div>
        <div style="text-align: center;" v-if="taskName && taskName == '变更确认'">
          <el-button type="primary" @click="submitForm">确认变更</el-button>
        </div>
      </el-col>
      <el-col :span="6" :xs="24" v-if="isFlow">
        <el-card>
          <h2 style="text-align: center;">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="选择项目" :visible.sync="openProject" width="70%" append-to-body>
      <project-choose @chooseProject="confirmProject"></project-choose>
    </el-dialog>
  </div>
</template>

<script>
import { listProjectChange, getProjectChange, delProjectChange, addProjectChange, updateProjectChange } from "@/api/oa/project/projectChange";
import { getProject } from "@/api/oa/project/project";
import { getUsersManageLeaderByDept, getUsersDeptLeaderByDept } from '@/api/system/post'
import flow from '@/views/flowable/task/todo/detail/flow';
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import { flowXmlAndNode } from "@/api/flowable/definition";
import projectChoose from '@/views/flowable/form/components/chooseProject.vue';
import { getDept } from "@/api/system/dept";

export default {
  components: {
    projectChoose,
    flow
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    isFlow: {
      type: Boolean,
      default: true
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc项目变更表格数据
      projectChangeList: [],
      leaderList: [],
      undertakingDeptNameList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openProject: false,
      chooseProject: {},
      isSelect: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        content: null,
        registrant: null,
        registerTime: null
      },
      // 表单参数
      form: {
        registerTime: undefined,
      },
      flowData: {},
      formTotal: 0,
      registrantName: '',
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: '请选择项目编号', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入变更内容', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.initForm();
    this.getList();
    if (this.$route.query.projectId) {
      getProject(this.$route.query.projectId).then(res => {
        if (res.data) {
          this.$set(this.form, 'projectId', res.data.projectId);
          this.handleSelectProject(res.data.projectId)
        }
      })
    }
    if (this.isFlow) {
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
    }
  },
  methods: {
    // 初始化表单
    initForm() {
      getProjectChange(this.taskForm.formId).then(res => {
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.registrant = this.$store.getters.userId;
          this.registrantName = this.$store.getters.name;
          this.form.registerTime = new Date();
        }
        else {
          this.formTotal = 1;
          this.form = res.data;
          this.registrantName = res.data.registrantUser.nickName
          if (res.data.projectId) {
            getProject(res.data.projectId).then(response => {
              this.chooseProject = response.data;
              this.isSelect = true;
            })
          }
          this.loading = false
        }
      })
    },
    /** 查询cmc项目变更列表 */
    getList() {
      this.loading = true;
      listProjectChange(this.queryParams).then(response => {
        this.projectChangeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    // 选择项目
    handleSelectProject(val) {
      if (val != "" && val != undefined && val != null) {
        getProject(val).then(response => {
          this.chooseProject = response.data;
          this.isSelect = true;
          if (this.chooseProject.undertakingDept) {
            this.getLeader(arr);
          }
        })
      } else {
        this.isSelect = false
      }
    },
    confirmProject(val) {
      if (val.length > 1) {
        this.$message.error('请选择一个项目');
        return
      } else if (val.length == 1) {
        this.chooseProject = val[0]
        this.isSelect = true
        this.form.projectId = val[0].projectId
        this.$refs.form.validateField('projectId');
        if (this.chooseProject.projectLeader)
          this.leaderList.push(this.chooseProject.projectLeader);
        getUsersDeptLeaderByDept({ deptId: 109 }).then(res => {
          this.leaderList.push(res.data.userId);
        })
        if (this.chooseProject.undertakingDept) {
          let arr = this.chooseProject.undertakingDept.split(',')
          this.getLeader(arr);
        }
      }
      this.openProject = false;
    },
    getLeader(val) {
      for (let v of val) {
        getUsersDeptLeaderByDept({ deptId: Number(v) }).then(res => {
          this.leaderList.push(res.data.userId);
        })
        getUsersManageLeaderByDept({ deptId: Number(v) }).then(res => {
          this.leaderList.push(res.data[0].userId);
        })
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            updateProjectChange(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              if (this.taskName == '变更登记') {
                this.$set(this.taskForm.variables, "approvalList", this.leaderList);
              }
              complete(this.taskForm).then(response => {
                this.$modal.msgSuccess(response.msg);
                this.$emit('goBack')
              });
            })
          } else {
            this.form.changeId = this.taskForm.formId;
            addProjectChange(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              this.$set(this.taskForm.variables, "approvalList", this.leaderList);
              complete(this.taskForm).then(response => {
                this.$modal.msgSuccess(response.msg);
                this.$emit('goBack')
              });
            })
          }
        }
      });
    },
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";
</style>
