<!--
 * @Author: ysh
 * @Date: 2025-08-18 10:59:25
 * @LastEditors: wrh
 * @LastEditTime: 2025-11-19 14:01:20
-->
<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="isFlow ? 18 : 24" :xs="24">
        <h2 style="text-align: center;">招聘申请表</h2>
        <div class="mt20 mb20" v-if="showAlter">
          <el-alert title="任务被退回，请修改后重新提交" type="error" :closable="false">
            <return-comment :taskForm="taskForm" @isReturn="isReturn"></return-comment>
          </el-alert>
        </div>
        <el-form :model="form" :rules="formRules" ref="form" label-width="175px" :disabled="taskName == ''"
          class="mt20">
          <el-divider></el-divider>
            <!-- 申请部门 -->
            <el-row :gutter="20" >
                <el-col :md="7" :span="24">
                    <el-form-item label="申请人：" prop="applier" >
                        <span>{{ getUserName(form.applier) }}</span>
                    </el-form-item>
                </el-col>
                <el-col :md="7" :span="24">
                    <el-form-item label="申请部门：" prop="dept.deptName" >
                        <span>{{ form.dept ? form.dept.deptName : '' }}</span>
                    </el-form-item>
                </el-col>
                <el-col :md="7" :span="24">
                    <el-form-item label="申请时间" prop="applyDate">
                        <el-date-picker style="width:140px;" v-model="form.applyDate" value-format="yyyy-MM-dd" type="date"
                    placeholder="选择日期" disabled>
                    </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- 项目 -->
            <el-form-item label="项目招聘：" prop="isProject">
                <el-switch v-model="isProject"  :disabled="taskName != '招聘申请'"></el-switch>
              </el-form-item>
            <el-form-item label="项目编号：" prop="projectId" v-if= this.isProject>
                <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="1">
                  <el-descriptions-item label="项目编号" label-class-name="my-label">{{ chooseProject ? chooseProject.projectNumber : ""
                    }}</el-descriptions-item>
                  <el-descriptions-item label="项目名称" label-class-name="my-label">{{ chooseProject ? chooseProject.projectName : ""
                    }}</el-descriptions-item>
                  <el-descriptions-item label="项目负责人" label-class-name="my-label">{{ chooseProject ? (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 ? chooseProject.projectType : ""
                    }}</el-descriptions-item>
                </el-descriptions>
              </el-form-item>
            <!-- 需求岗位名称和人数 -->
            <el-row :gutter="20" >
                <el-col :md="12" :span="24">
                  <el-form-item label="需求岗位名称：" prop="postName">
                    <el-input type="textarea" :rows="1" placeholder="请输入需求岗位名称" v-model="form.postName"
                      :disabled="taskName != '招聘申请'">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :md="12" :span="24">
                  <el-form-item label="招聘人数：" prop="postNumber">
                    <el-input-number v-model="form.postNumber" :min="1" :disabled="taskName != '招聘申请'"></el-input-number>
                  </el-form-item>
                </el-col>
            </el-row>

            <!-- 岗位职责 -->
            <el-form-item label="岗位职责：" prop="duty" label-width="140px">
                <el-input type="textarea" v-model="form.duty" :autosize="{ minRows: 4 }"
                :disabled="taskName != '招聘申请'"></el-input>
            </el-form-item>
            <!-- 任职资格 -->
            <el-form-item label="任职资格：" prop="qualification" label-width="140px">
                <el-input type="textarea" v-model="form.qualification" :autosize="{ minRows: 4 }"
                :disabled="taskName != '招聘申请'"></el-input>
            </el-form-item>
            <!-- 薪资待遇 -->
            <el-form-item label="薪资待遇：" prop="wage" label-width="140px">
                <el-input type="textarea" v-model="form.wage" :autosize="{ minRows: 4 }"
                :disabled="taskName != '招聘申请'"></el-input>
            </el-form-item>

            <el-divider></el-divider>

          <!-- 部门（项目）负责人意见 -->
            <el-form-item label="部门意见：" prop="deptComment" label-width="130px">
                <el-input type="textarea" v-model="form.deptComment" :autosize="{ minRows: 4 }"
                :disabled="taskName != '部门审批'"></el-input>
                <auditor-row ref="deptRef" :isCurrent="taskName == '部门审批'"
                :signature="form.deptUserId ? form.deptUserId : null" :signTime="form.deptTime"></auditor-row>
            </el-form-item>
            <!-- 分管审核意见： -->
            <el-form-item label="分管审批意见：" prop="managerComment" label-width="130px">
                <el-input type="textarea" v-model="form.managerComment" :autosize="{ minRows: 4 }"
                :disabled="taskName != '分管审批'"></el-input>
                <auditor-row ref="fgRef" :isCurrent="taskName == '分管审批'"
                :signature="form.managerUserId ? form.managerUserId : null" :signTime="form.managerTime"></auditor-row>
            </el-form-item>
            <!-- 总经理审批意见： -->
            <el-form-item label="总经理审批意见：" prop="zjlComment" label-width="130px">
                <el-input type="textarea" v-model="form.zjlComment" :autosize="{ minRows: 4 }"
                :disabled="taskName != '总经理审批'"></el-input>
                <auditor-row ref="zjlRef" :isCurrent="taskName == '总经理审批'"
                :signature="form.zjlUserId ? form.zjlUserId : null" :signTime="form.zjlTime"></auditor-row>
            </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <div style="text-align: center;" v-if="taskName" class="mt30">
          <el-button type="warning" @click="saveDraft" v-if="taskName == '招聘申请'">保存</el-button>
          <el-button type="danger" @click="returnOpen = true" v-if="taskName != '招聘申请'">退回</el-button>
          <el-button type="primary" @click="submitForm">{{ taskName != '总经理审批' ? '提交下一个流程' : '批准' }}</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="退回" :visible.sync="returnOpen" width="40%" append-to-body>
      <return-btn :taskForm="taskForm" :comment="commentByRole()" @goBack="$emit('goBack')" @saves=""
        @cancel="returnOpen = false"></return-btn>
    </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 flow from '@/views/flowable/task/todo/detail/flow';
import { getProject } from "@/api/oa/project/project";
import { flowXmlAndNode } from "@/api/flowable/definition";
import { listRecruit, getRecruit, delRecruit, addRecruit, updateRecruit } from "@/api/oa/recruit/recruit";
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import ReturnComment from "@/views/flowable/form/components/flowBtn/returnComment.vue";
import ReturnBtn from "@/views/flowable/form/components/flowBtn/returnBtn.vue";
import { getUsersDeptLeaderByDept, getUsersManageLeaderByDept, getUserByPost } from '@/api/system/post';
import AuditorRow from '@/views/flowable/form/components/auditorRow.vue';
import projectChoose from '@/views/flowable/form/components/chooseProject.vue';
export default {
  components: {
    flow,
    ReturnComment,
    ReturnBtn,
    AuditorRow,
    projectChoose
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    isFlow: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    isProject(newVal, oldVal) {
      if (newVal === false) {
        this.form.projectId = ''; 
        this.isSelect = false;
      }
    }
  },
  created() {
    if (this.isFlow)
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
    // 初始化表单数据
    this.initFormData()
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      flowData: {},
      isEdit: false,
      form: {
        dept: {
          deptName: '',
        },
      },
      rules: {},
      returnOpen: false,
      showAlter: true,
      openProject:false,
      isSelect:false,
      isProject: false,
    }
  },
  computed: {
    // 动态生成验证规则
    formRules() {
      if (this.taskName == '') {
        return {}; // 当taskName为空时，不进行验证
     }else if(this.taskName == '招聘申请'){
        return {
          postName: [
            { required: true, message: '请输入需求岗位名称', trigger: 'blur' }
          ],
          postNumber: [
            { required: true, message: '请选择招聘人数', trigger: 'change' }
          ],
          duty: [
            { required: true, message: '请输入岗位职责', trigger: 'blur' }
          ],
          qualification: [
            { required: true, message: '请输入任职资格', trigger: 'blur' }
          ],
          wage: [
            { required: true, message: '请输入薪资待遇', trigger: 'blur' }
          ]
     }}else if(this.taskName=='部门审批'){
        return{
          deptComment: [
            { required: true, message: '请填写审批意见', trigger: 'blur' }
          ]
     }}else if(this.taskName=='分管审批'){
        return{
          managerComment: [
            { required: true, message: '请填写审批意见', trigger: 'blur' }
          ]
     }}else if(this.taskName=='总经理审批'){
        return{
          zjlComment: [
            { required: true, message: '请填写审批意见', trigger: 'blur' }
          ]
     }}
    }
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      getRecruit(this.taskForm.formId).then(res => {
        if (res.data) {
          this.form = res.data;
          this.isEdit = true;
          if (this.form.projectId) {
            getProject(this.form.projectId).then(response => {
              this.chooseProject = response.data;
              this.isSelect = true;
              this.isProject = true;
            })
          }
        } else {
          this.form.applier = this.$store.state.user.id;
          this.form.applyDate = this.parseTime(new Date(), '{y}-{m}-{d}');
          this.form.applyDept = this.$store.getters.deptId;
          this.form.dept.deptName = this.$store.getters.deptName;
        }
      })
    },
    // 保存
    async saveDraft() {
      if (this.taskName == '') {
        this.$message.info('当前为只读模式，无法保存')
        return;
      }
      if (this.taskName == '部门审批') {
        this.form.deptUserId = this.$refs.deptRef.localSignatureUserId;
        this.form.deptTime = this.$refs.deptRef.loaclSignTime;
      } else if (this.taskName == '分管审批') {
        this.form.managerUserId = this.$refs.fgRef.localSignatureUserId;
        this.form.managerTime = this.$refs.fgRef.loaclSignTime;
      } else if (this.taskName == '总经理审批') {
        this.form.zjlUserId = this.$refs.zjlRef.localSignatureUserId;
        this.form.zjlTime = this.$refs.zjlRef.loaclSignTime;
      }

      if (this.isEdit) {
        await updateRecruit(this.form);
      } else {
        this.form.recruitId = this.taskForm.formId;
        await addRecruit(this.form);
        this.isEdit = true;
      }
      this.$message.success('保存成功')
    },
    // 提交表单
    submitForm() {
      if (this.taskName == '') {
        this.$message.info('当前为只读模式，无法提交')
        return;
      }

      this.$refs.form.validate((valid) => {
        if (valid) {
          let msg = '确认提交招聘申请表？';
          if (this.taskName == '总经理审批') {
            msg = '最后一个节点，提交将无法修改，是否确认提交？';
          }
          this.$confirm(msg, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.submitFlow()
          }).catch(() => {
            this.$message.info('已取消提交')
          })
        } else {
          this.$message.error('请完善表单信息')
          return false
        }
      })
    },
    async submitFlow() {
      await this.saveDraft();

      if (this.taskName == '招聘申请') {  
        const res = await getUsersDeptLeaderByDept({ deptId: this.$store.getters.deptId });
        this.$set(this.taskForm.variables, "approval", res.data.userId);
      }  else if (this.taskName == '部门审批') {
        let managerList = []
        let result = await getUsersManageLeaderByDept({ deptId: this.form.applyDept });
        result.data.forEach(element => {managerList.push(element.userId)});
        this.$set(this.taskForm.variables, "approvalList", managerList);
      } else if (this.taskName == '分管审批') {
        const res = await getUserByPost({ postName: "总经理" });
        this.$set(this.taskForm.variables, "approval", res.data[0].userId);
      }

      await getNextFlowNode({ taskId: this.taskForm.taskId });
      const response = await complete(this.taskForm);
      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.openProject = false;
    },
    isReturn(val) {
      this.showAlter = val;
    },
    commentByRole() {
      if (this.taskName == '部门审批') {
        return this.form.deptComment
      } else if (this.taskName == '分管审批') {
        return this.form.managerComment
      } else if (this.taskName == '总经理审批') {
        return this.form.zjlComment
      } 
    },
  }
}
</script>

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

.process-steps {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.current-step-info {
  margin: 20px 0;

  .step-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    i {
      color: #409eff;
      margin-right: 8px;
      font-size: 16px;
    }

    .step-title {
      font-weight: bold;
      color: #303133;
      font-size: 16px;
    }
  }

  .step-description {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
  }
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid #409eff;

    i {
      color: #409eff;
      margin-right: 8px;
      font-size: 18px;
    }

    svg {
      color: #409eff;
      margin-right: 8px;
      font-size: 18px;
    }

    span {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
  }
}

.sign {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: 80px;
  line-height: 30px;
  /* 如果需要垂直居中 */
}

.mt20 {
  margin-top: 20px;
}

.mt30 {
  margin-top: 30px;
}

.mb20 {
  margin-bottom: 20px;
}

.ml20 {
  margin-left: 20px;
}

.mr20 {
  margin-right: 20px;
}

.mt10 {
  margin-top: 10px;
}
</style>