<!--
 * @Author: ysh
 * @Date: 2024-07-04 17:37:29
 * @LastEditors: wrh
 * @LastEditTime: 2024-09-29 13:59:58
-->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="18" :xs="24">
        <div class="mb20" v-if="showAlter">
          <el-alert title="任务被退回，请修改后重新提交" type="error" :closable="false">
            <return-comment :taskForm="taskForm" @isReturn="isReturn"></return-comment>
          </el-alert>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-form-item label="项目编号：" prop="projectId" v-if="taskForm.procDefName == '技术交底'">
            <el-input v-model="chooseProject.projectNumber" placeholder="请输入项目编号" disabled style="width: 300px" />
            <el-descriptions border v-if="isSelect" style="margin-top: 10px;" :column="1">
              <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.projectLeaderUser ?
      chooseProject.projectLeaderUser.nickName : ''
                }}</el-descriptions-item>
              <el-descriptions-item label="承担部门" label-class-name="my-label">
                <el-tag size="small">{{ chooseProject.undertakingDeptName }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="项目类型" label-class-name="my-label">{{ chooseProject.projectType
                }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <el-form-item label="接受交底人" prop="accepter">
            <el-select v-model="form.accepter" style="width:220px" :disabled="true">
              <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId"
                v-if="item.nickName != 'admin'">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="技术交底内容" prop="content">
            <el-input v-model="form.content" placeholder="请输入技术交底内容" type="textarea" :disabled="taskName != '技术交底'"
              :autosize="{ minRows: 8 }" />
          </el-form-item>
          <el-form-item label="附件" prop="document">
            <FileUpload v-if="!form.document" ref="bsFile" :limit="1" :filePathName="'技术交底'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getTechnicalDoc"></FileUpload>
            <div v-if="form.document">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.document}`)">
                {{ getFileName(form.document) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.document}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
              <span class="el-icon-delete del-file" @click="deleteDoc" v-if="taskName == '技术交底'">删除文件</span>
            </div>
          </el-form-item>
          <el-form-item label="技术交底意见" prop="disclosureComment">
            <el-input v-model="form.disclosureComment" placeholder="请输入技术交底意见" type="textarea"
              :disabled="taskName != '技术交底'" :autosize="{ minRows: 4 }" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="签名" prop="disclosurer">
                <span class="auditor"> {{ form.disclosureUser ? form.disclosureUser.nickName : disclosureUser }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期：" label-width="120px">
                <span> {{ parseTime(form.disclosureTime, '{y}-{m}-{d}') }} </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="接受交底意见" prop="acceptComment" v-if="taskName != '技术交底'">
            <el-input v-model="form.acceptComment" placeholder="请输入接受交底意见" type="textarea" :autosize="{ minRows: 4 }"
              :disabled="taskName != '接受交底'" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="签名" v-if="taskName != '技术交底'">
                <span class="auditor"> {{ form.acceptUser ? form.acceptUser.nickName : acceptUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期：" label-width="120px" v-if="taskName != '技术交底'">
                <span> {{ parseTime(form.acceptTime, '{y}-{m}-{d}') }} </span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="确认交底意见" prop="confirmComment" v-if="taskName != '技术交底' && taskName != '接受交底'">
            <el-input v-model="form.confirmComment" placeholder="请输入确认交底意见" type="textarea" :autosize="{ minRows: 4 }"
              :disabled="taskName == ''" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="签名" v-if="taskName != '技术交底' && taskName != '接受交底'">
                <span class="auditor"> {{ form.confirmUser ? form.confirmUser.nickName : confirmUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期：" label-width="120px" v-if="taskName != '技术交底' && taskName != '接受交底'">
                <span> {{ parseTime(form.confirmTime, '{y}-{m}-{d}') }} </span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: center;" v-if="taskName">
          <el-button type="danger" @click="returnOpen = true" v-show="taskName != '技术交底'">退 回</el-button>
          <el-button type="primary" @click="submitForm">提 交</el-button>
        </div>
      </el-col>
      <el-col :span="6" :xs="24">
        <el-card>
          <h2 style="text-align: center;">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="退回" :visible.sync="returnOpen" width="40%" append-to-body>
      <return-btn :taskForm="taskForm" @goBack="$emit('goBack')" @saves="" @cancel="returnOpen = false"></return-btn>
    </el-dialog>
  </div>
</template>

<script>
import { listTechnical, getTechnical, delTechnical, addTechnical, updateTechnical } from "@/api/oa/technical/technical";
import { getProject } from "@/api/oa/project/project";
import { listUser } from '@/api/system/user';
import flow from '@/views/flowable/task/todo/detail/flow';
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import { flowXmlAndNode } from "@/api/flowable/definition";
import { getUsersManageLeaderByDept, getUsersDeptLeaderByDept, getUserByPost } from '@/api/system/post'
import ReturnBtn from './components/flowBtn/returnBtn.vue';
import ReturnComment from './components/flowBtn/returnComment.vue';

export default {
  components: {
    flow,
    ReturnBtn,
    ReturnComment,
  },
  name: "Technical",
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      disclosureUser: '',
      acceptUser: '',
      confirmUser: '',
      userList: [],
      chooseProject: {},
      isSelect: false,
      // 表单参数
      form: {
        user: {
          nickName: '',
        }
      },
      // 表单校验
      rules: {},
      formTotal: 0,
      flowData: {},
      returnOpen: false,
      showAlter: true,
    };
  },
  created() {
    this.getProjectById();
    this.getUserList();
    flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
      this.flowData = res.data;
    })
  },
  mounted() {
    this.initRules();
    this.initForm();
  },
  methods: {
    initRules() {
      if (this.taskName == '技术交底') {
        this.rules = {
          disclosureComment: [
            { required: true, message: '请输入技术交底意见', trigger: 'blur' },
          ],
        }
      }
      else if (this.taskName == '接受交底') {
        this.rules = {
          acceptComment: [
            { required: true, message: '请输入接受交底意见', trigger: 'blur' },
          ],
        }
      }
      else if (this.taskName == '确认交底') {
        this.rules = {
          confirmComment: [
            { required: true, message: '请输入确认交底意见', trigger: 'blur' },
          ],
        }
      }
    },
    initForm() {
      getTechnical(this.taskForm.formId).then(res => {
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.disclosurer = this.$store.getters.userId;
          this.disclosureUser = this.$store.getters.name;
          this.form.disclosureTime = new Date();
        }
        else {
          this.formTotal = 1;
          this.form = res.data;
          if (this.taskName == '接受交底') {
            this.form.accepter = this.$store.getters.userId;
            this.acceptUser = this.$store.getters.name;
            this.form.acceptTime = new Date();
          }
          if (this.taskName == '确认交底') {
            this.form.confirmer = this.$store.getters.userId;
            this.confirmUser = this.$store.getters.name;
            this.form.confirmTime = new Date();
          }
        }
      })
    },
    // 查询项目
    getProjectById() {
      getProject(this.taskForm.formId).then(response => {
        this.chooseProject = response.data;
        this.isSelect = true;
        this.form.accepter = response.data.projectLeader;
      });
    },
    // 查询用户列表
    getUserList() {
      listUser({ pageSize: 9999, pageNum: 1 }).then(res => {
        this.userList = res.rows
      })
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            updateTechnical(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(async res => {
              if (this.taskName == '技术交底') {
                this.$set(this.taskForm.variables, "approval", this.form.accepter);
                this.handleComplete();
              }
              else if (this.taskName == '接受交底') {
                let res = await getUsersDeptLeaderByDept({ deptId: 109 })
                this.$set(this.taskForm.variables, "approval", res.data.userId);
                this.handleComplete();
              } else if (this.taskName == '确认交底') {
                this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(res => {
                  this.handleComplete();
                })
              }
            })
          } else {
            this.form.technicalId = this.taskForm.formId;
            this.form.projectId = this.taskForm.formId;
            addTechnical(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              this.$set(this.taskForm.variables, "formId", this.taskForm.formId);
              this.$set(this.taskForm.variables, "approval", this.form.accepter);
              this.handleComplete();
            })
          }
        }
      });
    },
    handleComplete() {
      complete(this.taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack')
      });
    },
    getFileName(name) {
      if (name) {
        let arr = name.split('/')
        return arr[arr.length - 1];
      }
    },
    getTechnicalDoc(val) {
      if (val) {
        let arr = val.split('/upload')
        this.form['document'] = arr[1]
        if (val == "") {
          this.form['document'] = ""
        }
      }
    },
    deleteDoc() {
      this.$set(this.form, 'document', undefined)
    },
    isReturn(val) {
      this.showAlter = val
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";
</style>