<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="environmentComment">
              <div v-if="taskName == '安全交底'">
                <el-button size="mini" plain @click="chooseSafe('0')" type="primary" icon="el-icon-plus">选择要求</el-button>
              </div>
            <el-input v-model="form.environmentComment" placeholder="请输入环境管理要求" type="textarea"
              :disabled="taskName != '安全交底'" :autosize="{ minRows: 8 }" />
          </el-form-item>
          <el-form-item label="安全生产与职业健康要求" prop="outsideComment">
              <div v-if="taskName == '安全交底'">
                <el-button size="mini" plain @click="chooseSafe('1')" type="primary" icon="el-icon-plus">选择要求</el-button>
              </div>
            <el-input v-model="form.outsideComment" placeholder="请输入安全生产与职业健康要求" type="textarea"
              :disabled="taskName != '安全交底'" :autosize="{ minRows: 8 }" />
          </el-form-item>
          <el-form-item label="信息安全管理要求" prop="insideComment">
              <div v-if="taskName == '安全交底'">
                <el-button size="mini" plain @click="chooseSafe('2')" type="primary" icon="el-icon-plus">选择要求</el-button>
              </div>
            <el-input v-model="form.insideComment" placeholder="请输入信息安全管理要求" type="textarea" :autosize="{ minRows: 8 }"
              :disabled="taskName != '安全交底'" />
          </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>

    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <choose-saferequest :safeType="safeType" @close="open = false" @confirm="setRequestVals"></choose-saferequest>
    </el-dialog>
  </div>
</template>

<script>
import { listSafe, getSafe, delSafe, addSafe, updateSafe } from "@/api/oa/safe/safe";
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 ChooseSaferequest from './components/chooseSaferequest.vue';

export default {
  components: {
    flow,
    ChooseSaferequest
  },
  name: "Safe",
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      disclosurerUser: '',
      accepterUser: '',
      safeType:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc安全交底表格数据
      safeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        disclosureAccepter: null,
        disclosurer: null,
        environmentComment: null,
        outsideComment: null,
        insideComment: 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() {
      getSafe(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;
      listSafe(this.queryParams).then(response => {
        this.safeList = 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 = {
        safeId: null,
        projectId: null,
        disclosureAccepter: null,
        disclosurer: null,
        environmentComment: null,
        outsideComment: null,
        insideComment: 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.safeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加cmc安全交底";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const safeId = row.safeId || this.ids
      getSafe(safeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改cmc安全交底";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            updateSafe(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.safeId = this.taskForm.formId;
            this.form.projectId = this.taskForm.formId;
            addSafe(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')
              });
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const safeIds = row.safeId || this.ids;
      this.$modal.confirm('是否确认删除cmc安全交底编号为"' + safeIds + '"的数据项？').then(function () {
        return delSafe(safeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/safe/export', {
        ...this.queryParams
      }, `safe_${new Date().getTime()}.xlsx`)
    },
    chooseSafe(type){
      this.safeType = type
      this.open = true;
    },
    setRequestVals(input){
      if(this.safeType == '0'){
        this.form.environmentComment = input
      }else if(this.safeType == '1'){
        this.form.outsideComment = input
      }else{
        this.form.insideComment = input
      }
    }
  }
};
</script>

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