<!--
 * @Author: ysh
 * @Date: 2024-06-21 18:51:51
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-01-23 09:10:56
-->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="isFlow ? 18 : 24" :xs="24">
        <h2 class="text-center">成果归档记录表</h2>
        <el-divider></el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <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">
              <el-descriptions-item label="项目编号" label-class-name="my-label">{{ chooseProject.projectNumber
                }}</el-descriptions-item>
              <el-descriptions-item label="项目名称" label-class-name="my-label">{{ chooseProject.projectName
                }}</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">{{ contractCode
                }}</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-item label="技术负责人" label-class-name="my-label">{{
                chooseProject.technicalDirectorUser ? chooseProject.technicalDirectorUser.nickName :
                  '' }}</el-descriptions-item>
              <el-descriptions-item label="质检审核员" label-class-name="my-label">{{
                chooseProject.qualityInspectorName
              }}</el-descriptions-item>
              <!-- <el-descriptions-item label="坐标经度" label-class-name="my-label">{{ chooseProject.kmlLng
              }}</el-descriptions-item>
              <el-descriptions-item label="坐标纬度" label-class-name="my-label">{{ chooseProject.kmlLat
              }}</el-descriptions-item> -->
            </el-descriptions>
          </el-form-item>
          <el-form-item label="归档状态">
            <el-tag :type="typeStyle(hasArchievement)">{{ typeText(hasArchievement) }}</el-tag>
          </el-form-item>
          <el-form-item label="成果提交日期" prop="submitTime">
            <el-date-picker clearable v-model="form.submitTime" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择成果提交日期" :disabled="taskName != '归档发起'">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注说明" prop="submitSituation">
            <el-input type="textarea" v-model="form.submitSituation" placeholder="请输入备注说明"
              :disabled="taskName != '归档发起'" :autosize="{ minRows: 4 }" />
          </el-form-item>
          <el-form-item label="技术质量与安全部负责人审核" prop="deptComment">
            <el-input type="textarea" v-model="form.deptComment" placeholder="请输入技术质量与安全部负责人审核意见"
              :disabled="taskName != '技术质量与安全部审核'" :autosize="{ minRows: 4 }" />
          </el-form-item>
          <auditor-row key="1" :isCurrent="taskName == '技术质量与安全部审核'" :signature="form.deptLeader"
            :signTime="form.deptTime"></auditor-row>
          <!-- <el-form-item label="资料管理">
            <el-button type="success" size="mini" @click="gotoFile" :disabled="taskName != '成果归档'">前往资料管理系统</el-button>
          </el-form-item> -->
          <!-- 成果列表 -->
          <archive-file :project="chooseProject" :taskName="taskName"></archive-file>
          <div class="mb20" style="color:#E23D28;font-size:12px;padding-left:120px;" v-if="taskName == '成果归档'">
            tips:上传成果之后，请刷新页面，归档状态即可变为已归档，才能提交并结束流程。
          </div>
          <el-form-item label="技术质量与安全部归档" prop="archiveComment">
            <el-input type="textarea" v-model="form.archiveComment" placeholder="请输入技术质量与安全部归档意见"
              :disabled="taskName != '成果归档'" :autosize="{ minRows: 4 }" />
          </el-form-item>
          <auditor-row key="2" :isCurrent="taskName == '成果归档'" :signature="form.archiver"
            :signTime="form.archiveTime"></auditor-row>
        </el-form>
        <div style="text-align: center;" v-if="isFlow">
          <el-button type="primary" @click="submitForm" v-if="taskName == '成果归档'"
            :disabled="taskName == '成果归档' && hasArchievement == false">
            提交并结束流程</el-button>
          <el-button type="primary" @click="submitForm" v-else
            :disabled="taskName == '成果归档' && hasArchievement == false">
            提交</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="completeTitle" :visible.sync="completeOpen" width="60%" append-to-body>
      <el-form ref="taskForm" :model="taskForm">
        <el-form-item prop="targetKey">
          <flow-user v-if="checkSendUser" :checkType="checkType" @handleUserSelect="handleUserSelect"></flow-user>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="completeOpen = false">取 消</el-button>
        <el-button type="primary" @click="taskComplete">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择项目" :visible.sync="openProject" width="70%" append-to-body>
      <project-choose @chooseProject="confirmProject"></project-choose>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { listProject, getProject } from "@/api/oa/project/project";
import { listArchive, getArchive, delArchive, addArchive, updateArchive } from "@/api/oa/archive/archive";
import { listProjectContract } from "@/api/oa/contract/projectContract";
import { getContract } from "@/api/oa/contract/contract";
import { getUsersDeptLeaderByDept } from '@/api/system/post'
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import FlowUser from '@/components/flow/User';
import flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";
import { getUserByRole } from "@/api/system/role";
import projectChoose from '@/views/flowable/form/components/chooseProject.vue';
import { listAchievement } from "@/api/file/achievement";
import auditorRow from './components/auditorRow.vue';
import ArchiveFile from './archiveFile.vue';

export default {
  components: {
    FlowUser,
    projectChoose,
    flow,
    auditorRow,
    ArchiveFile
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    isFlow: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    'taskForm.formId'() {
      this.initForm()
    }
  },
  name: "Archive",
  data() {
    return {
      produceUser: '',
      qualityUser: '',
      deptUser: '',
      archiveUser: '',
      produceTime: undefined,
      qualityTime: undefined,
      deptTime: undefined,
      archiveTime: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc成果归档表格数据
      archiveList: [],
      // 弹出层标题
      title: "",
      // 表单参数
      form: {
        submitTime: undefined,
      },
      // 表单校验
      rules: {
      },
      chooseProject: {},
      isSelect: false,
      openProject: false,
      formTotal: 0,
      flowData: {},
      projectList: [],
      contractCode: '',
      checkSendUser: false,
      completeOpen: false,
      completeTitle: '',
      checkType: 'single',
      hasArchievement: false,
    };
  },
  mounted() {
    this.initRules();
    this.initForm();
    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)
        }
      })
    }
  },
  created() {
    if (this.taskName == '部门检查') {
      this.produceUser = this.$store.getters.name;
      this.produceTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    else if (this.taskName == '质检审核') {
      this.qualityUser = this.$store.getters.name;
      this.qualityTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    else if (this.taskName == '技术质量与安全部审核') {
      this.deptUser = this.$store.getters.name;
      this.deptTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    else if (this.taskName == '成果归档') {
      this.archiveUser = this.$store.getters.name;
      this.archiveTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    this.getProjectList();
    if (this.isFlow) {
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
    }
  },
  methods: {
    // 初始化表单
    initForm() {
      getArchive(this.taskForm.formId).then(res => {
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.applier = this.$store.getters.userId;
          this.form.submitTime = new Date();
        }
        else {
          this.formTotal = 1;
          this.form = res.data;
          if (res.data.projectId) {
            listAchievement({ projectId: res.data.projectId }).then(response => {
              if (response.total > 0)
                this.hasArchievement = true;
              else
                this.hasArchievement = false;
            });
            getProject(res.data.projectId).then(response => {
              this.chooseProject = response.data;
              this.isSelect = true;
              this.getContractByProjectId(this.chooseProject.projectId);
            })
          }
          this.loading = false
        }
      })
    },
    initRules() {
      if (this.taskName == '归档发起') {
        this.rules = {
          projectId: [
            { required: true, message: '请选择项目', trigger: 'blur' }
          ],
          submitTime: [
            { required: true, message: '请选择成果提交日期', trigger: 'change' }
          ]
        }
      } else if (this.taskName == '部门检查') {
        this.rules = {
          produceComment: [
            { required: true, message: '请填写检查意见', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '质检审核') {
        this.rules = {
          receiveTime: [
            { required: true, message: '请选择资料接收时间', trigger: 'change' }
          ],
          qualityComment: [
            { required: true, message: '请填写审核意见', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '技术质量与安全部审核') {
        this.rules = {
          deptComment: [
            { required: true, message: '请填写审核意见', trigger: 'blur' }
          ]
        }
      }
    },
    // 查询项目列表
    getProjectList() {
      this.loading = true
      listProject({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.projectList = response.rows;
      })
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    // 用户信息选中数据
    handleUserSelect(selection) {
      if (selection) {
        //不多选
        this.$set(this.taskForm.variables, "approval", selection.userId.toString());
      }
    },
    /** 用户审批任务 */
    taskComplete() {
      if (!this.taskForm.variables && this.checkSendUser) {
        this.$modal.msgError("请选择流程接收人员!");
        return;
      }
      if (this.taskForm) {
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit('goBack')
        });
      }
    },
    saves() {
      let uploadKmlData = new FormData();
      uploadKmlData.append("kmlfile", this.kmlfile);
      uploadKmlData.append("cpfile", this.cpfile);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            updateArchive(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              if (this.taskName == '归档发起') {
                // const params = { taskId: this.taskForm.taskId };
                // this.checkSendUser = true;
                // this.completeOpen = true;
                // this.completeTitle = "流程审批";
                getUsersDeptLeaderByDept({ deptId: 109 }).then(res => {
                  let userId = res.data.userId;
                  this.$set(this.taskForm.variables, "approval", userId);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                });
              }
              if (this.taskName == '部门检查') {
                let approvalList = this.chooseProject.qualityInspector.split(',')
                this.$set(this.taskForm.variables, "approvalList", approvalList);
                complete(this.taskForm).then(response => {
                  this.$modal.msgSuccess(response.msg);
                  this.$emit('goBack')
                });
              }
              if (this.taskName == '质检审核') {
                getUsersDeptLeaderByDept({ deptId: 110 }).then(res => {
                  let userId = res.data.userId;
                  this.$set(this.taskForm.variables, "approval", userId);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                });
              }
              if (this.taskName == '技术质量与安全部审核') {
                getUserByRole({ roleId: 6 }).then(result => {
                  this.$set(this.taskForm.variables, "approval", result.data[0]);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                })
              }
              if (this.taskName == '成果归档') {
                this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(() => {
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                })
              }
            })
          } else {
            this.form.archiveId = this.taskForm.formId;
            addArchive(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              // this.checkSendUser = true;
              // this.completeOpen = true;
              // this.completeTitle = "流程审批";
              getUsersDeptLeaderByDept({ deptId: 109 }).then(res => {
                let userId = res.data.userId;
                this.$set(this.taskForm.variables, "approval", userId);
                complete(this.taskForm).then(response => {
                  this.$modal.msgSuccess(response.msg);
                  this.$emit('goBack')
                });
              });
            })
          }
        }
      });
    },
    confirmProject(val) {
      if (val.length > 1) {
        this.$message.error('请选择一个项目');
        return
      } else if (val.length == 1) {
        this.chooseProject = val[0]
        this.isSelect = true
        this.$set(this.form, 'projectId', val[0].projectId)
        this.$refs.form.validateField('projectId');
      }
      this.openProject = false;
      listAchievement({ projectId: this.form.projectId }).then(response => {
        if (response.total > 0)
          this.hasArchievement = true;
        else
          this.hasArchievement = false;
      });
      this.getContractByProjectId(this.chooseProject.projectId);
    },
    getContractByProjectId(projectId) {
      this.contractCode = '';
      listProjectContract({ projectId: projectId }).then(res => {
        if (res.rows.length > 0) {
          for (let row of res.rows) {
            getContract(row.contractId).then(res => {
              if (res.data) {
                if (this.contractCode != '') {
                  this.contractCode = this.contractCode + '、' + res.data.contractCode;
                } else {
                  this.contractCode = res.data.contractCode;
                }
              }
            })
          }
        }
        else
          this.contractCode = '';
      })
    },
    gotoFile() {
      this.$router.push({ path: '/product/archive/file' })
    },
    typeText(flag) {
      if (flag == true)
        return '已归档'
      else
        return '未归档'
    },
    typeStyle(flag) {
      if (flag == true)
        return 'success'
      else
        return 'warning'
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";
</style>