<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="18" :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-select v-model="form.projectId" filterable placeholder="请选择" @change="handleSelectProject"
              :disabled="taskName != '成果上传'" clearable>
              <el-option v-for="item in projectList" :key="item.value" :label="item.projectName" :value="item.projectId">
              </el-option>
            </el-select> -->
            <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">{{ 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-divider></el-divider>
          <el-form-item label="部门检查员检查" prop="produceComment">
            <el-input type="textarea" v-model="form.produceComment" placeholder="请输入部门检查员检查意见"
              :disabled="taskName != '部门检查'" :autosize="{ minRows: 4 }" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="签名：" label-width="120px" v-if="taskName != '成果上传'">
                <span class="auditor"> {{ form.produceUser ? form.produceUser.nickName : produceUser }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期：" label-width="120px" v-if="taskName != '成果上传'">
                <span> {{ form.produceTime ? form.produceTime : produceTime }} </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="资料接收时间" prop="receiveTime">
            <el-date-picker clearable v-model="form.receiveTime" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择资料接收时间" :disabled="taskName != '质检审核'">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="质量检查员审核" prop="qualityComment">
            <el-input type="textarea" v-model="form.qualityComment" placeholder="请输入质量检查员审核意见"
              :disabled="taskName != '质检审核'" :autosize="{ minRows: 4 }" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="签名：" label-width="120px" v-if="taskName != '成果上传' && taskName != '部门检查'">
                <span class="auditor"> {{ form.qualityUser ? form.qualityUser.nickName : qualityUser }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期：" label-width="120px" v-if="taskName != '成果上传' && taskName != '部门检查'">
                <span> {{ form.qualityTime ? form.qualityTime : qualityTime }} </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="技术质量部负责人审核" prop="deptComment">
            <el-input type="textarea" v-model="form.deptComment" placeholder="请输入技术质量部负责人审核意见"
              :disabled="taskName != '技术部审核'" :autosize="{ minRows: 4 }" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="签名：" label-width="120px" v-if="taskName == '技术部审核' || taskName == '成果归档'">
                <span class="auditor"> {{ form.deptUser ? form.deptUser.nickName : deptUser }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期：" label-width="120px" v-if="taskName == '技术部审核' || taskName == '成果归档'">
                <span> {{ form.deptTime ? form.deptTime : deptTime }} </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="资料管理">
            <el-button type="success" size="mini" @click="gotoFile" :disabled="taskName != '成果归档'">前往资料管理系统</el-button>
          </el-form-item>
          <el-form-item label="技术质量部归档" prop="archiveComment">
            <el-input type="textarea" v-model="form.archiveComment" placeholder="请输入技术质量部归档意见"
              :disabled="taskName != '成果归档'" :autosize="{ minRows: 4 }" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="签名：" label-width="120px" v-if="taskName == '成果归档'">
                <span class="auditor"> {{ form.archiveUser ? form.archiveUser.nickName : archiveUser }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="归档日期：" label-width="120px" v-if="taskName == '成果归档'">
                <span> {{ form.archiveTime ? form.archiveTime : archiveTime }} </span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: center;">
          <el-button type="primary" @click="submitForm" :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";

export default {
  components: {
    FlowUser,
    projectChoose,
    flow
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    isFlow: {
      type: Boolean,
      default: true
    }
  },
  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: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        submitTime: null,
        submitSituation: null,
        locationLng: null,
        locationLat: null,
        produceInspector: null,
        qualityInspector: null,
        deptLeader: null,
        archiver: null,
        receiveTime: null,
        qualityTime: null,
        produceTime: null,
        deptTime: null,
        archiveTime: null,
        produceComment: null,
        qualityComment: null,
        deptComment: null,
        archiveComment: null
      },
      // 表单参数
      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();
    this.getList();
    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;
              listProjectContract({ projectId: response.data.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 = '';
              })
            })
          }
          this.loading = false
        }
      })
    },
    initRules() {
      if (this.taskName == '成果上传') {
        this.rules = {
          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' }
          ]
        }
      }
    },
    /** 查询cmc成果归档列表 */
    getList() {
      this.loading = true;
      listArchive(this.queryParams).then(response => {
        this.archiveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 查询项目列表
    getProjectList() {
      this.loading = true
      listProject({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.projectList = response.rows;
      })
    },
    // 选择项目
    handleSelectProject(val) {
      if (val != "" && val != undefined && val != null) {
        getProject(val).then(response => {
          this.chooseProject = response.data;
          this.isSelect = true;
          listProjectContract({ projectId: response.data.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 = '';
          })
        })
      } else {
        this.isSelect = false
      }
    },
    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')
        });
      }
    },
    // 表单重置
    reset() {
      this.form = {
        archiveId: null,
        projectId: null,
        submitTime: null,
        submitSituation: null,
        locationLng: null,
        locationLat: null,
        produceInspector: null,
        qualityInspector: null,
        deptLeader: null,
        archiver: null,
        receiveTime: null,
        qualityTime: null,
        produceTime: null,
        deptTime: null,
        archiveTime: null,
        produceComment: null,
        qualityComment: null,
        deptComment: null,
        archiveComment: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.archiveId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加cmc成果归档";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const archiveId = row.archiveId || this.ids
      getArchive(archiveId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改cmc成果归档";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            updateArchive(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 == '成果上传') {
                const params = { taskId: this.taskForm.taskId };
                this.checkSendUser = true;
                this.completeOpen = true;
                this.completeTitle = "流程审批";
              }
              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 == '成果归档') {
                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("新增成功");
              this.open = false;
              this.getList();
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              this.checkSendUser = true;
              this.completeOpen = true;
              this.completeTitle = "流程审批";
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const archiveIds = row.archiveId || this.ids;
      this.$modal.confirm('是否确认删除cmc成果归档编号为"' + archiveIds + '"的数据项？').then(function () {
        return delArchive(archiveIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/archive/export', {
        ...this.queryParams
      }, `archive_${new Date().getTime()}.xlsx`)
    },
    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.openProject = false;
      listAchievement({ projectId: this.form.projectId }).then(response => {
        if (response.total > 0)
          this.hasArchievement = true;
        else
          this.hasArchievement = false;
      });
    },
    gotoFile() {
      this.$router.push({ path: '/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>