<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="职称类型" prop="type">
        <el-select v-model="queryParams.type" clearable placeholder="请选择职称类型" @change="handleQuery">
          <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="queryParams.level" clearable placeholder="请选择职称级别" @change="handleQuery">
          <el-option label="正高级" value="正高级"></el-option>
          <el-option label="副高级" value="副高级"></el-option>
          <el-option label="高级" value="高级"></el-option>
          <el-option label="中级" value="中级"></el-option>
          <el-option label="初级" value="初级"></el-option>
          <el-option label="员级" value="员级"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="申请人" prop="userId">
        <el-select v-model="queryParams.userId" filterable clearable @change="handleQuery">
          <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['oa:title:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['oa:title:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="evalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请人" align="center" prop="userId">
        <template slot-scope="scope">
          {{ getUserName(scope.row.userId) }}
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评审年度" align="center" prop="annual" />
      <el-table-column label="评审单位" align="center" prop="institude" />
      <el-table-column label="职称类型" align="center" prop="type" />
      <el-table-column label="职称级别" align="center" prop="level" />
      <el-table-column label="职称专业名称" align="center" prop="titleProfession" />
      <el-table-column label="审核意见" align="center" prop="titleComment" />
      <el-table-column label="审核时间" align="center" prop="titleTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.titleTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职称管理员" align="center" prop="titleUserId">
        <template slot-scope="scope">
          {{ getUserName(scope.row.titleUserId) }}
        </template>
      </el-table-column>
      <el-table-column label="确认时间" align="center" prop="confirmTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.confirmTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="确认状态" align="center" prop="confirmStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.confirmStatus == '1' ? 'success' : 'danger'">
            {{ scope.row.confirmStatus == "1" ? "已确认" : "未确认" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否通过" align="center" prop="isApproved">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isApproved == '1' ? 'success' : 'danger'">
            {{ scope.row.isApproved == "1" ? "通过" : "未通过" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['oa:title:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改职称评审对话框 -->
    <el-dialog :visible.sync="open" width="760px" append-to-body custom-class="title-eval-dialog"
      :close-on-click-modal="false">
      <template slot="title">
        <div class="title-eval-dialog__header">
          <i class="el-icon-edit-outline" />
          <span>{{ title }}</span>
        </div>
      </template>
      <div class="title-eval-dialog__body">
        <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-user" />
              <span>基本信息</span>
            </div>
            <el-descriptions :column="2" border size="medium" class="info-descriptions">
              <el-descriptions-item label="申请人">
                <span class="info-value">{{ getUserName(form.userId) || '—' }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="评审年度">
                <span class="info-value">{{ form.annual || '—' }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="评审单位">
                <span class="info-value">{{ form.institude || '—' }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="职称类型">
                <el-tag v-if="form.type" size="small" effect="plain">{{ form.type }}</el-tag>
                <span v-else class="info-empty">—</span>
              </el-descriptions-item>
              <el-descriptions-item label="职称级别">
                <el-tag v-if="form.level" size="small" type="warning" effect="plain">{{ form.level }}</el-tag>
                <span v-else class="info-empty">—</span>
              </el-descriptions-item>
              <el-descriptions-item label="职称专业名称" :span="2">
                <span class="info-value">{{ form.titleProfession || '—' }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-folder-opened" />
              <span>申请材料</span>
            </div>
            <el-form-item label-width="140px" v-for="item in applicationFiles" :key="item.key" :label="item.label" :prop="item.key">
              <div v-if="hasFile(item.path)" class="file-row">
                <el-link type="primary" :underline="false" @click="reviewWord(getUploadUrl(item.path))">
                  <i class="el-icon-document" /> {{ getFileName(item.path) }}
                </el-link>
                <el-link class="ml20" type="warning" :href="getUploadUrl(item.path)" :underline="false" target="_blank">
                  <i class="el-icon-download" /> 下载文件
                </el-link>
              </div>
              <span v-else class="info-empty">暂无文件</span>
            </el-form-item>
          </div>

          <div class="form-section form-section--result">
            <div class="section-title">
              <i class="el-icon-circle-check" />
              <span>审核结果</span>
            </div>
            <el-form-item label="是否通过" prop="isApproved" class="approve-switch-item">
              <el-switch v-model="form.isApproved" active-value="1" inactive-value="0" active-text="通过"
                inactive-text="未通过" active-color="#67c23a" inactive-color="#f56c6c" />
            </el-form-item>
            <transition name="el-fade-in">
              <div v-if="form.isApproved == '1'" class="pass-materials">
                <el-alert title="通过评审后，请补充公示文件、证书扫描件及取得时间" type="info" :closable="false" show-icon
                  class="pass-materials__tip" />
                <el-form-item label="公示红头文件" prop="publicityFile">
                  <div v-if="hasFile(form.publicityFile)" class="file-row file-row--readonly">
                    <el-link type="primary" :underline="false" @click="reviewWord(getUploadUrl(form.publicityFile))">
                      <i class="el-icon-document" /> {{ getFileName(form.publicityFile) }}
                    </el-link>
                    <el-link class="ml20" type="warning" :href="getUploadUrl(form.publicityFile)" :underline="false"
                      target="_blank">
                      <i class="el-icon-download" /> 下载文件
                    </el-link>
                  </div>
                  <file-upload v-model="form.publicityFile"
                    :filePathName="'职称评审/公示红头文件/' + form.annual + '/' + getUserName(form.userId)"
                    :fileType="['pdf']" @input="getPublicityFilePath" />
                </el-form-item>
                <el-form-item label="证书扫描件" prop="scanFile">
                  <div v-if="hasFile(form.scanFile)" class="file-row file-row--readonly">
                    <el-link type="primary" :underline="false" @click="reviewWord(getUploadUrl(form.scanFile))">
                      <i class="el-icon-document" /> {{ getFileName(form.scanFile) }}
                    </el-link>
                    <el-link class="ml20" type="warning" :href="getUploadUrl(form.scanFile)" :underline="false"
                      target="_blank">
                      <i class="el-icon-download" /> 下载文件
                    </el-link>
                  </div>
                  <file-upload v-model="form.scanFile"
                    :filePathName="'职称评审/证书扫描件/' + form.annual + '/' + getUserName(form.userId)" :fileType="['pdf']"
                    @input="getScanFilePath" />
                </el-form-item>
                <el-form-item label="证书取得时间" prop="obtainTime">
                  <el-date-picker v-model="form.obtainTime" clearable type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择证书取得时间" style="width: 100%" />
                </el-form-item>
              </div>
            </transition>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="title-eval-dialog__footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" icon="el-icon-check" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEval, getEval, delEval, addEval, updateEval } from "@/api/oa/titles/titles";
import { Snowflake } from "@/utils/snowFlake.js";

export default {
  name: "Eval",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 职称评审表格数据
      evalList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        annual: null,
        institude: null,
        type: null,
        level: null,
        titleProfession: null,
        sheet: null,
        sheetStamp: null,
        material: null,
        isApproved: null,
        publicityFile: null,
        scanFile: null,
        obtainTime: null,
        applyTime: null,
        titleUserId: null,
        titleTime: null,
        titleComment: null,
        materialUploadTime: null,
        confirmer: null,
        confirmTime: null,
        confirmStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  watch: {
    'form.isApproved'(newVal) {
      if (newVal === "0") {
        this.clearFiles();
      }
    }
  },
  computed: {
    applicationFiles() {
      const form = this.form || {};
      return [
        { key: 'sheet', label: '评审表（盖章前）', path: form.sheet },
        // { key: 'secretOpinion', label: '保密审核意见单及承诺书', path: form.secretOpinion },
        { key: 'sheetStamp', label: '评审表（盖章后）', path: form.sheetStamp },
        { key: 'material', label: '其他材料', path: form.material },
      ];
    },
    formRules() {
      return {
        publicityFile: [
          { required: () => this.form.isApproved == '1', message: '请上传公示红头文件', trigger: 'change' }
        ],
        scanFile: [
          { required: () => this.form.isApproved == '1', message: '请上传证书扫描件', trigger: 'change' }
        ],
        obtainTime: [
          { required: () => this.form.isApproved == '1', message: '请选择证书取得时间', trigger: 'change' }
        ]
      }
    },
  },
  methods: {
    hasFile(path) {
      return path != null && String(path).trim() !== '';
    },
    getUploadUrl(path) {
      if (!this.hasFile(path)) return '';
      const p = String(path).trim();
      if (/^https?:\/\//i.test(p)) return p;
      if (p.indexOf('/profile/upload') === 0) {
        return `${this.baseUrl}${p}`;
      }
      return `${this.baseUrl}/profile/upload${p}`;
    },
    /** 查询职称评审列表 */
    getList() {
      this.loading = true;
      listEval(this.queryParams).then((response) => {
        this.evalList = response.rows.filter(
          item => !(item.isApproved === "1" && item.confirmStatus == null));
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getPublicityFilePath(val) {
      let arr = val.split('/upload')
      this.form.publicityFile = arr[1]
      if (val == "") {
        this.form.publicityFile = ""
      }
    },
    getScanFilePath(val) {
      let arr = val.split('/upload')
      this.form.scanFile = arr[1]
      if (val == "") {
        this.form.scanFile = ""
      }
    },
    // 表单重置
    reset() {
      this.form = {
        titleEvalId: null,
        userId: null,
        annual: null,
        institude: null,
        type: null,
        level: null,
        titleProfession: null,
        sheet: null,
        secretOpinion: null,
        sheetStamp: null,
        material: null,
        isApproved: null,
        publicityFile: null,
        scanFile: null,
        obtainTime: null,
        applyTime: null,
        titleUserId: null,
        titleTime: null,
        titleComment: null,
        materialUploadTime: null,
        confirmer: null,
        confirmTime: null,
        confirmStatus: 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.titleEvalId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加职称评审";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let targetRow = row;
      if (!targetRow || !targetRow.titleEvalId) {
        const selected = (this.evalList || []).filter((item) =>
          (this.ids || []).includes(item.titleEvalId)
        );
        targetRow = selected.length === 1 ? selected[0] : null;
      }
      const titleEvalId = targetRow
        ? targetRow.titleEvalId
        : Array.isArray(this.ids)
          ? this.ids[0]
          : this.ids;
      if (!titleEvalId) {
        this.$modal.msgWarning('请选择一条记录');
        return;
      }
      this.reset();
      this.title = '修改职称评审';
      this.open = true;
      if (targetRow) {
        this.form = { ...this.form, ...targetRow };
      }
      getEval(titleEvalId).then((response) => {
        this.form = { ...this.form, ...(response.data || {}) };
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate();
        });
      });
    },
    /**switch切换到未通过时清除上传文件 */
    clearFiles() {
      this.form.publicityFile = "";
      this.form.scanFile = "";
      this.form.obtainTime = "";
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.confirmStatus == "1") {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.titleEvalId != null) {
              updateEval(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addEval(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        })
      }
      else {
        this.$message.error('未在流程中确认信息，无法提交。')
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const titleEvalIds = row.titleEvalId || this.ids;
      this.$modal
        .confirm('是否确认删除职称评审编号为"' + titleEvalIds + '"的数据项？')
        .then(function () {
          return delEval(titleEvalIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "oa/titleEval/export",
        {
          ...this.queryParams,
        },
        `eval_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.form-section {
  margin-bottom: 20px;
  padding: 18px 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafbfc;

  &:last-child {
    margin-bottom: 0;
  }

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

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

    span {
      font-size: 15px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.form-section--result {
  background: #fff;
}

.info-descriptions {
  ::v-deep .el-descriptions__label {
    width: 110px;
    color: #606266;
    font-weight: 500;
  }
}

.info-value {
  color: #303133;
  font-weight: 500;
}

.info-empty {
  color: #c0c4cc;
  font-size: 13px;
}

.file-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  line-height: 32px;

  &--readonly {
    margin-bottom: 8px;
    padding: 8px 12px;
    background: #f5f7fa;
    border-radius: 4px;
    border: 1px solid #ebeef5;
  }
}

.approve-switch-item {
  margin-bottom: 8px;
}

.pass-materials {
  margin-top: 8px;
  padding-top: 16px;
  border-top: 1px dashed #e4e7ed;

  &__tip {
    margin-bottom: 16px;
  }
}
</style>

<style lang="scss">
.title-eval-dialog {
  border-radius: 10px;
  overflow: hidden;

  .el-dialog__header {
    padding: 18px 24px 14px;
    border-bottom: 1px solid #ebeef5;
    background: linear-gradient(135deg, #f5f9ff 0%, #fff 100%);
  }

  .el-dialog__body {
    padding: 20px 24px;
    max-height: 68vh;
    overflow-y: auto;
  }

  .el-dialog__footer {
    padding: 14px 24px 18px;
    border-top: 1px solid #ebeef5;
    background: #fafbfc;
  }

  &__header {
    display: flex;
    align-items: center;
    font-size: 17px;
    font-weight: 600;
    color: #303133;

    i {
      margin-right: 10px;
      font-size: 20px;
      color: #409eff;
    }
  }

  &__footer {
    text-align: right;
  }
}
</style>
