<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="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="disclosureAccepter">
            <el-select v-model="form.disclosureAccepter" 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="taskName == '技术交底'" ref="bsFile" :limit="1" :filePathName="'技术交底'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf']" @input="getTechnicalDoc"></FileUpload>
            <div v-if="form.document && taskName != '技术交底'">
              <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>
            </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.disclosurerUser ? form.disclosurerUser.nickName : disclosurerUser }}
                </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.accepterUser ? form.accepterUser.nickName : accepterUser }} </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>
        <div style="text-align: center;" v-if="taskName">
          <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>
  </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";

export default {
  components: {
    flow
  },
  name: "Technical",
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      disclosurerUser: '',
      accepterUser: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc技术交底表格数据
      technicalList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        disclosureAccepter: null,
        disclosurer: null,
        content: null,
        document: null,
        disclosureComment: null,
        disclosureTime: null,
        acceptTime: null
      },
      userList: [],
      chooseProject: {},
      isSelect: false,
      // 表单参数
      form: {
        user: {
          nickName: '',
        }
      },
      // 表单校验
      rules: {},
      formTotal: 0,
      flowData: {}
    };
  },
  created() {
    this.getProjectById();
    this.getUserList();
    this.getList();
    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' },
          ],
        }
      }
    },
    initForm() {
      getTechnical(this.taskForm.formId).then(res => {
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.disclosurer = this.$store.getters.userId;
          this.disclosurerUser = this.$store.getters.name;
          this.form.disclosureTime = new Date();
        }
        else {
          this.formTotal = 1;
          this.form = res.data;
          this.accepterUser = this.$store.getters.name;
          this.form.acceptTime = new Date();
        }
      })
    },
    // 查询项目
    getProjectById() {
      getProject(this.taskForm.formId).then(response => {
        this.chooseProject = response.data;
        this.isSelect = true;
        this.form.disclosureAccepter = response.data.projectLeader;
      });
    },
    // 查询用户列表
    getUserList() {
      listUser({ pageSize: 9999, pageNum: 1 }).then(res => {
        this.userList = res.rows
      })
    },
    /** 查询cmc技术交底列表 */
    getList() {
      this.loading = true;
      listTechnical(this.queryParams).then(response => {
        this.technicalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    // 表单重置
    reset() {
      this.form = {
        technicalId: null,
        projectId: null,
        disclosureAccepter: null,
        disclosurer: null,
        content: null,
        document: null,
        disclosureComment: null,
        disclosureTime: null,
        acceptTime: 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.technicalId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加cmc技术交底";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const technicalId = row.technicalId || this.ids
      getTechnical(technicalId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改cmc技术交底";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            updateTechnical(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, "approval", this.form.disclosureAccepter);
              complete(this.taskForm).then(response => {
                this.$modal.msgSuccess(response.msg);
                this.$emit('goBack')
              });
            })
          } else {
            this.form.technicalId = this.taskForm.formId;
            this.form.projectId = this.taskForm.formId;
            addTechnical(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, "formId", this.taskForm.formId);
              this.$set(this.taskForm.variables, "approval", this.form.disclosureAccepter);
              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'] = ""
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const technicalIds = row.technicalId || this.ids;
      this.$modal.confirm('是否确认删除cmc技术交底编号为"' + technicalIds + '"的数据项？').then(function () {
        return delTechnical(technicalIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/technical/export', {
        ...this.queryParams
      }, `technical_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

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