<!--
 * @Author: ysh
 * @Date: 2025-08-18 10:59:25
 * @LastEditors: wrh
 * @LastEditTime: 2026-01-09 15:52:07
-->
<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="isFlow ? 18 : 24" :xs="24">
        <h2 style="text-align: center;">职称申请表</h2>

        <!-- 流程步骤指示器 -->
        <div class="process-steps" v-if="isFlow && taskName">
          <el-steps :active="getCurrentStepIndex()" finish-status="success" align-center>
            <el-step title="评审申请" description="填写基本信息并上传材料"></el-step>
            <el-step title="初步审核" description="审核申请材料并填写意见"></el-step>
            <el-step title="盖章上传" description="上传盖章后的评审表"></el-step>
            <el-step title="确认信息" description="最终确认并完成流程"></el-step>
          </el-steps>
        </div>

        <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>

        <!-- 当前步骤提示 -->
        <div class="current-step-info" v-if="isFlow && taskName">
          <el-card shadow="never" :body-style="{ padding: '15px' }">
            <div class="step-header">
              <i class="el-icon-info"></i>
              <span class="step-title">当前步骤：{{ taskName }}</span>
            </div>
            <div class="step-description">{{ getStepDescription() }}</div>
          </el-card>
        </div>

        <el-form :model="form" :rules="formRules" ref="form" label-width="135px" :disabled="taskName == ''" class="mt20">
          <!-- 基本信息区域 -->
          <div class="form-section" v-if="showBasicInfo()">
            <div class="section-title">
              <i class="el-icon-user"></i>
              <span>基本信息</span>
            </div>

            <!-- 申请人 -->
            <el-form-item label="申请人" prop="userId">
              <span class="auditor">{{ getUserName(form.userId) }}</span>
            </el-form-item>

            <!-- 申请时间 -->
            <el-form-item label="申请时间" prop="applyTime">
              {{ form.applyTime }}
            </el-form-item>

            <!-- 评审年度 -->
            <el-form-item label="评审年度" prop="annual">
              {{ form.annual }}
            </el-form-item>

            <!-- 评审单位 -->
            <el-form-item label="评审单位" prop="institude">
              <el-select v-model="form.institude" placeholder="请选择评审单位" style="width: 100%"
                :disabled="taskName == '' || taskName != '评审申请'">
                <el-option label="中国电建" value="中国电建" />
                <el-option label="成都人社" value="成都人社" />
                <el-option label="四川省测绘局" value="四川省测绘局" />
                <el-option label="四川省建设厅" value="四川省建设厅" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>

            <!-- 职称类型 -->
            <el-form-item label="职称类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择职称类型" style="width: 100%"
                :disabled="taskName == '' || taskName != '评审申请'">
                <el-option label="工程类" value="工程类" />
                <el-option label="经济类" value="经济类" />
                <el-option label="政工类" value="政工类" />
                <el-option label="企业法律顾问类" value="企业法律顾问类" />
              </el-select>
            </el-form-item>

            <!-- 职称级别 -->
            <el-form-item label="职称级别" prop="level">
              <el-select v-model="form.level" placeholder="请选择职称级别" style="width: 100%"
                :disabled="taskName == '' || taskName != '评审申请'">
                <el-option label="员级" value="员级" />
                <el-option label="助理级" value="助理级" />
                <el-option label="中级" value="中级" />
                <el-option label="副高级" value="副高级" />
                <el-option label="正高级" value="正高级" />
              </el-select>
            </el-form-item>

            <!-- 职称专业名称 -->
            <el-form-item label="职称专业名称" prop="titleProfession">
              <el-input v-model="form.titleProfession" placeholder="请输入职称专业名称" maxlength="50" show-word-limit
                :disabled="taskName == '' || taskName != '评审申请'" />
            </el-form-item>
          </div>

          <!-- 申请材料区域 -->
          <div class="form-section" v-if="showApplicationMaterials()">
            <div class="section-title">
              <i class="el-icon-document"></i>
              <span>申请材料</span>
            </div>

            <!-- 盖章前评审表 -->
            <el-form-item label="评审表（盖章前）" prop="sheet">
              <FileUpload v-if="taskName == '评审申请' && !form.sheet" :disabled="taskName == '' || taskName != '评审申请'"
                ref="sheetFile" :limit="1" :filePathName="'职称评审/盖章前评审表/' + form.annual + '/' + getUserName(form.userId)" :fileType="['pdf']" @input="getSheetPath">
              </FileUpload>
              <div v-if="form.sheet">
                <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.sheet}`)">
                  {{ getFileName(form.sheet) }}
                </el-link>
                <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.sheet}`"
                  :underline="false" target="_blank">
                  <span class="el-icon-download">下载文件</span>
                </el-link>
                <span class="el-icon-delete del-file" @click="deleteDoc('sheet')"
                  v-if="taskName == '评审申请' && taskName != ''">删除文件</span>
              </div>
            </el-form-item>
            <el-form-item label="保密审核意见单及承诺书" prop="secretOpinion">
              <el-button v-if="taskName == '评审申请' && !form.secretOpinion" type="primary" size="small" @click="openUploadDialog">选取文件</el-button>
              <div v-if="form.secretOpinion">
                <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.secretOpinion}`)">
                  {{ getFileName(form.secretOpinion) }}
                </el-link>
                <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.secretOpinion}`"
                  :underline="false" target="_blank">
                  <span class="el-icon-download">下载文件</span>
                </el-link>
                <span class="el-icon-delete del-file" @click="deleteDoc('secretOpinion')"
                  v-if="taskName == '评审申请' && taskName != ''">删除文件</span>
              </div>
            </el-form-item>
            <!-- 其他材料 -->
            <el-form-item label="其他材料" prop="material">
              <FileUpload v-if="taskName == '评审申请' && !form.material" :disabled="taskName == '' || taskName != '评审申请'"
                ref="materialFile" :limit="1" :filePathName="'职称评审/其他材料/' + form.annual + '/' + getUserName(form.userId)" :fileType="['rar', 'zip']"
                @input="getMaterialPath">
              </FileUpload>
              <div v-if="form.material">
                <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.material}`)">
                  {{ getFileName(form.material) }}
                </el-link>
                <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.material}`"
                  :underline="false" target="_blank">
                  <span class="el-icon-download">下载文件</span>
                </el-link>
                <span class="el-icon-delete del-file" @click="deleteDoc('material')"
                  v-if="taskName == '评审申请' && taskName != ''">删除文件</span>
              </div>
            </el-form-item>
          </div>

          <!-- 审核意见区域 -->
          <div class="form-section" v-if="showReviewOpinion()">
            <div class="section-title">
              <i class="el-icon-edit-outline"></i>
              <span>审核意见</span>
            </div>

            <!-- 职称评审意见 -->
            <el-form-item label="职称评审意见" prop="titleComment" v-if="taskName != '评审申请'">
              <el-input v-model="form.titleComment" type="textarea" :rows="3" placeholder="请输入职称评审意见" maxlength="200"
                show-word-limit :disabled="taskName == '' || taskName != '初步审核'" />
              <div class="sign mt10" v-if="form.titleUserId">
                <div class="mr20">签名：<span class="auditor">{{ getUserName(form.titleUserId) }}</span>
                </div>
                <div class="ml20"><span>审核时间：{{ form.titleTime }}</span></div>
              </div>
            </el-form-item>
          </div>

          <!-- 盖章材料区域 -->
          <div class="form-section" v-if="showStampMaterials()">
            <div class="section-title">
              <!-- <i class="el-icon-edit"></i> -->
              <svg-icon icon-class="skill" />
              <span>盖章材料</span>
            </div>

            <!-- 盖章后评审表 -->
            <el-form-item label="评审表（盖章后）" prop="sheetStamp">
              <FileUpload v-if="taskName == '盖章上传' && !form.sheetStamp" :disabled="taskName == '' || taskName != '盖章上传'"
                ref="sheetStampFile" :limit="1" :filePathName="'职称评审/盖章后评审表/' + form.annual + '/' + getUserName(form.userId)" :fileType="['pdf']"
                @input="getSheetStampPath">
              </FileUpload>
              <div v-if="form.sheetStamp">
                <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.sheetStamp}`)">
                  {{ getFileName(form.sheetStamp) }}
                </el-link>
                <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.sheetStamp}`"
                  :underline="false" target="_blank">
                  <span class="el-icon-download">下载文件</span>
                </el-link>
                <span class="el-icon-delete del-file" @click="deleteDoc('sheetStamp')"
                  v-if="taskName == '盖章上传' && taskName != ''">删除文件</span>
              </div>
            </el-form-item>
          </div>
        </el-form>

        <!-- 操作按钮 -->
        <div style="text-align: center;" v-if="taskName" class="mt30">
          <el-button type="warning" @click="saveDraft">保存</el-button>
          <el-button type="danger" @click="returnOpen = true" v-if="taskName != '评审申请' && taskName != '盖章上传'">退
            回</el-button>
          <el-button type="primary" @click="submitForm">{{ taskName == '盖章上传' || 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="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" accept=".pdf" :headers="upload.headers" :action="upload.url" :data="upload.data"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-change="handleFileUploadChange"
        :on-success="handleFileSuccess" :auto-upload="false" drag v-loading="uploadLoading"
        element-loading-text="正在上传，请稍等">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入pdf格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";
import { listEval, getEval, delEval, addEval, updateEval } from "@/api/oa/titles/titles";
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import { getToken } from "@/utils/auth";
import { downloadTemplate } from "@/api/file/project";
import { allocatedUserList } from "@/api/system/role";
import ReturnComment from "@/views/flowable/form/components/flowBtn/returnComment.vue";
import ReturnBtn from "@/views/flowable/form/components/flowBtn/returnBtn.vue";
export default {
  components: {
    flow,
    ReturnComment,
    ReturnBtn,
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    isFlow: {
      type: Boolean,
      default: true
    }
  },
  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: {
        userId: '',
        annual: '',
        institude: '',
        type: '',
        level: '',
        titleProfession: '',
        sheet: '',
        secretOpinion: '',
        material: ''
      },
      rules: {},
      returnOpen: false,      
      upload: {
        open: false,
        title: "上传保密审核意见单",
        isUploading: false,
        updateSupport: 0,
        headers: { 'Authorization': "Bearer " + getToken() },
        data: { 'fileType': '' },
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      uploadLoading: false,
      uploadFormData: undefined,
      showAlter: true
    }
  },
  computed: {
    // 动态生成验证规则
    formRules() {
      if (this.taskName == '') {
        return {}; // 当taskName为空时，不进行验证
      }

      return {
        institude: [
          { required: true, message: '请选择评审单位', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择职称类型', trigger: 'change' }
        ],
        level: [
          { required: true, message: '请选择职称级别', trigger: 'change' }
        ],
        titleProfession: [
          { required: true, message: '请输入职称专业名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        sheet: [
          { required: true, message: '请上传盖章前评审表', trigger: 'change' }
        ],
        secretOpinion: [
          { required: true, message: '请上传保密审核意见单', trigger: 'change' }
        ],
        material: [
          { required: true, message: '请上传其他材料', trigger: 'change' }
        ],
        titleComment: [
          { required: this.taskName == '初步审核', message: '请输入职称评审意见', trigger: 'blur' },
          { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
        ],
        sheetStamp: [
          { required: this.taskName == '盖章上传', message: '请上传盖章后评审表', trigger: 'change' },
        ]
      };
    }
  },
  methods: {
    // 获取当前步骤索引
    getCurrentStepIndex() {
      const stepMap = {
        '评审申请': 0,
        '初步审核': 1,
        '盖章上传': 2,
        '确认信息': 3
      };
      return stepMap[this.taskName] || 0;
    },

    // 获取步骤描述
    getStepDescription() {
      const descriptions = {
        '评审申请': '请填写基本信息并上传相关材料文件',
        '初步审核': '请审核申请材料并填写评审意见',
        '盖章上传': '请上传盖章后的评审表文件',
        '确认信息': '请确认所有信息无误后完成流程'
      };
      return descriptions[this.taskName] || '';
    },

    // 显示基本信息区域
    showBasicInfo() {
      return true; // 所有步骤都显示基本信息
    },

    // 显示申请材料区域
    showApplicationMaterials() {
      return this.taskName == '' || ['评审申请', '初步审核', '盖章上传', '确认信息'].includes(this.taskName);
    },

    // 显示审核意见区域
    showReviewOpinion() {
      return this.taskName == '' || ['初步审核', '盖章上传', '确认信息'].includes(this.taskName);
    },

    // 显示盖章材料区域
    showStampMaterials() {
      return this.taskName == '' || ['盖章上传', '确认信息'].includes(this.taskName);
    },

    // 初始化表单数据
    initFormData() {
      getEval(this.taskForm.formId).then(res => {
        if (res.data) {
          this.form = res.data;
          this.isEdit = true;
        } else {
          this.form = {
            userId: this.$store.state.user.id,
            annual: new Date().getFullYear().toString(),
            applyTime: this.parseTime(new Date(), '{y}-{m}-{d}'),
            institude: '',
            type: '',
            level: '',
          }
        }
      })
    },
    // 保存
    async saveDraft() {
      if (this.taskName == '') {
        this.$message.info('当前为只读模式，无法保存')
        return;
      }

      if (this.taskName == '初步审核') {
        this.form.titleUserId = this.$store.state.user.id;
        this.form.titleTime = this.parseTime(new Date(), '{y}-{m}-{d}');
      } else if (this.taskName == '盖章上传') {
        this.form.materialUploadTime = this.parseTime(new Date(), '{y}-{m}-{d}');
      } else if (this.taskName == '确认信息') {
        this.form.confirmer = this.$store.state.user.id;
        this.form.confirmStatus = '1';
        this.form.confirmTime = this.parseTime(new Date(), '{y}-{m}-{d}');
      }
      if (this.isEdit) {
        await updateEval(this.form);
      } else {
        this.form.titleEvalId = this.taskForm.formId;
        await addEval(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 == '评审申请') {
        let allocatedRes = await allocatedUserList({ roleId: 19 });
        let titleUserId = allocatedRes.rows[0].userId;
        this.$set(this.taskForm.variables, "approval", titleUserId);
      } else if (this.taskName == '初步审核') {
        this.$set(this.taskForm.variables, "approval", this.form.userId);
      } else if (this.taskName == '盖章上传') {
        this.$set(this.taskForm.variables, "approval", this.form.titleUserId);
      }
      getNextFlowNode({ taskId: this.taskForm.taskId }).then(() => {
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.$emit('goBack');
        })
      })
    },
    getSheetPath(path) {
      let arr = path.split('/upload')
      this.form.sheet = arr[1]
      if (path == "") {
        this.form.sheet = ""
      }
    },
    getMaterialPath(path) {
      let arr = path.split('/upload')
      this.form.material = arr[1]
      if (path == "") {
        this.form.material = ""
      }
    },
    getSheetStampPath(path) {
      let arr = path.split('/upload')
      this.form.sheetStamp = arr[1]
      if (path == "") {
        this.form.sheetStamp = ""
      }
    },
    getFileName(name) {
      if (name) {
        let arr = name.split('/')
        return arr[arr.length - 1];
      }
    },
    deleteDoc(key) {
      this.$set(this.form, key, undefined)
    },
    isReturn(val) {
      this.showAlter = val;
    },
    commentByRole() {
      if (this.taskName == "初步审核") {
        return this.form.titleComment;
      }
    },
    /**PDF文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.form.secretOpinion = "/职称评审/保密审核意见单/" + this.form.annual + '/' + this.$store.state.user.name + "/" + file.name;
      this.upload.isUploading = true;
      this.uploadLoading = true;
    },
    /* PDF文件改变时 */
    handleFileUploadChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.uploadFormData = new FormData();
      this.uploadFormData.append("file", file);
      this.form.secretOpinion = "/职称评审/保密审核意见单/" + this.form.annual + '/' + this.$store.state.user.name + "/" + file.name;
    },
    /** PDF文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      console.log("成功");
      this.upload.open = false;
      this.upload.isUploading = false;
      this.uploadLoading = false;
      this.fileList = [];
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.$refs["uploadRef"].clearFiles();
    },
    /* 打开上传对话框 */
    openUploadDialog() {
      // 设置文件类型和存储路径
      this.upload.data.fileType = '职称评审/保密审核意见单/' + this.form.annual + '/' + this.$store.state.user.name;
      // 打开上传对话框
      this.upload.open = true;
    },
    /* PDF上传提交按钮 */
    submitUpload() {
      this.$refs['uploadRef'].submit();
    },
    /* 下载模板 */
    importTemplate() {
      const path = '/profile/upload/template/opinion.docx'
      downloadTemplate(path).then(res => {
        const blob = new Blob([res])
        saveAs(blob, 'opinion.docx');
      });
    },
  }
}
</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>