<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="专家姓名" prop="expertName">
              <el-input v-model="queryParams.expertName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="queryParams.contact" placeholder="请输入联系方式" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工作单位" prop="workUnit" label-width="120">
              <el-input v-model="queryParams.workUnit" placeholder="请输入工作单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="职务" prop="duty">
              <el-input v-model="queryParams.duty" placeholder="请输入职务" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="政治面貌" prop="politics">
              <el-input v-model="queryParams.politics" placeholder="请输入政治面貌" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="状态" clearable>
                <el-option v-for="(item, index) of approval_status" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <p class="title">专家审批</p>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="expertList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" minWidth="55" align="center" />
        <el-table-column type="index" label="序号" minWidth="50" align="center">
          <template #default="scope">
            <span>{{
              (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="expertName" minWidth="160" />
        <el-table-column label="性别" align="center" prop="sex" minWidth="100">
          <template #default="scope">
            <span>{{ scope.row.sex == 0 ? '男' : scope.row.sex == 1 ? '女' : '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" align="center" prop="contact" minWidth="140" />
        <el-table-column label="工作单位" align="center" prop="workUnit" minWidth="270" />
        <el-table-column label="职务" align="center" prop="duty" minWidth="180" />
        <el-table-column label="审批类型" align="center" prop="approvalType" minWidth="180">
          <template #default="scope">
            <el-tag v-if="scope.row.approvalType == '0'" type="primary">专家申请</el-tag>
            <el-tag v-if="scope.row.approvalType == '1'" type="info">信息变更</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" minWidth="120">
          <template #default="scope">
            <el-tag v-if="scope.row.status == '0'" type="primary">暂存</el-tag>
            <el-tag v-if="scope.row.status == '1'" type="warning">待审批</el-tag>
            <el-tag v-if="scope.row.status == '2'" type="success">通过</el-tag>
            <el-tag v-if="scope.row.status == '3'" type="danger">拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" minWidth="200">
          <template #default="scope">
            <span v-if="scope.row.status == '1'" style="color: #36d;cursor: pointer;"
              @click="jumpToDetail('approval', scope.row)">审批</span>
            <span v-else style="color: #36d;cursor: pointer;"
              @click="jumpToDetail('detail', scope.row)">详情</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 专家库导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <!-- <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div> -->
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Expert" lang="ts">
import { listExpert, getExpert, delExpert, addExpert, updateExpert } from '@/api/expert/approval/index';
import { ApprovalVO, ApprovalQuery, ApprovalForm } from '@/api/expert/approval/types';
import $bus from '@/utils/mitt'
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// const { approval_status } = toRefs<any>(proxy?.useDict('approval_status'));
const approval_status = [
  {
    label: '待审批', value: '1'
  },
  {
    label: '通过', value: '2'
  },
  {
    label: '拒绝', value: '3'
  }
]


const expertList = ref<ApprovalVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const router = useRouter();

const queryFormRef = ref<ElFormInstance>();
const expertFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/zjk-api/expert/imports'
});
const initFormData: ApprovalForm = {
  id: undefined,
  expertName: undefined,
  sex: undefined,
  birthDate: undefined,
  contact: undefined,
  workUnit: undefined,
  duty: undefined,
  politics: undefined,
  graduateSchool: undefined,
  major: undefined,
  email: undefined,
  professional: undefined,
  professionalAcquisitionDate: undefined,
  workProfessial: undefined,
  workProfessialYear: undefined,
  photograph: undefined,
  performWorkId: undefined,
  otherDescribe: undefined,
  workExperience: undefined,
  workPluralistic: undefined,
  achievement: undefined,
  remark: undefined,
  createdBy: undefined,
  createdTime: undefined,
  updatedBy: undefined,
  updatedTime: undefined,
  deleteFlag: undefined,
  // approver: undefined,
  paperpath: undefined,
  patentpath: undefined,
  approvalValue: undefined,
  approver: undefined,
  approvalType: undefined,
  approvalOpinion: undefined,
  positionTitleLevel: undefined,
  expertSources: undefined,
}
const data = reactive<PageData<ApprovalForm, ApprovalQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    expertId: undefined,
    expertName: undefined,
    sex: undefined,
    birthDate: undefined,
    contact: undefined,
    workUnit: undefined,
    duty: undefined,
    politics: undefined,
    graduateSchool: undefined,
    major: undefined,
    email: undefined,
    professional: undefined,
    professionalAcquisitionDate: undefined,
    workProfessial: undefined,
    workProfessialYear: undefined,
    photograph: undefined,
    performWorkId: undefined,
    otherDescribe: undefined,
    workExperience: undefined,
    workPluralistic: undefined,
    achievement: undefined,
    createdBy: undefined,
    createdTime: undefined,
    updatedBy: undefined,
    updatedTime: undefined,
    deleteFlag: undefined,
    params: {
    },
    status: ''
  },
  rules: {
    id: [
      { required: true, message: "id不能为空", trigger: "blur" }
    ],
    expertName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    sex: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ],
    birthDate: [
      { required: true, message: "生日不能为空", trigger: "blur" }
    ],
    contact: [
      { required: true, message: "联系方式不能为空", trigger: "blur" }
    ],
    workUnit: [
      { required: true, message: "工作单位不能为空", trigger: "blur" }
    ],
    duty: [
      { required: true, message: "职务不能为空", trigger: "blur" }
    ],
    politics: [
      { required: true, message: "政治面貌不能为空", trigger: "blur" }
    ],
    graduateSchool: [
      { required: true, message: "毕业学校不能为空", trigger: "blur" }
    ],
    major: [
      { required: true, message: "专业不能为空", trigger: "blur" }
    ],
    email: [
      { required: true, message: "邮箱不能为空", trigger: "blur" }
    ],
    professional: [
      { required: true, message: "专业技术资格不能为空", trigger: "blur" }
    ],
    professionalAcquisitionDate: [
      { required: true, message: "专业技术资格取得时间不能为空", trigger: "blur" }
    ],
    workProfessial: [
      { required: true, message: "从事专业不能为空", trigger: "blur" }
    ],
    workProfessialYear: [
      { required: true, message: "从事专业年限不能为空", trigger: "blur" }
    ],
    photograph: [
      { required: true, message: "照片不能为空", trigger: "blur" }
    ],
    performWorkId: [
      { required: true, message: "从事工作或研究领域不能为空", trigger: "blur" }
    ],
    otherDescribe: [
      { required: true, message: "其他领域描述不能为空", trigger: "blur" }
    ],
    workExperience: [
      { required: true, message: "专业相关经历不能为空", trigger: "blur" }
    ],
    workPluralistic: [
      { required: true, message: "参与政务信息化项目评审情况不能为空", trigger: "blur" }
    ],
    achievement: [
      { required: true, message: "主要论著、业绩成果及获奖情况不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
    createdBy: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
    createdTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    updatedBy: [
      { required: true, message: "修改人不能为空", trigger: "blur" }
    ],
    updatedTime: [
      { required: true, message: "修改时间不能为空", trigger: "blur" }
    ],
    deleteFlag: [
      { required: true, message: "是否删除不能为空", trigger: "blur" }
    ]
  }
});

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '专家库导入';
  upload.open = true;
};
const uploadRef = ref<ElUploadInstance>();
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

const { queryParams, form, rules } = toRefs(data);

/** 查询expert列表 */
const getList = async () => {
  loading.value = true;
  const res = await listExpert(queryParams.value);
  expertList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

//跳转审批/查看详情
const jumpToDetail = (type: string, row?: ApprovalVO) => {

  const _id = row?.expertId || ids.value[0];

  router.push({ path: '/expert/approval/detail', query: { id: _id, type } });
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  expertFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ApprovalVO[]) => {
  ids.value = selection.map(item => item.expertId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
// const handleAdd = () => {
//   router.push('/expert/expert/add');

//   // reset();
//   // dialog.visible = true;
//   // dialog.title = "添加expert";
// }

/** 修改按钮操作 */
// const handleUpdate = async (row?: ApprovalVO) => {

//   const _id = row?.expertId || ids.value[0];

//  router.push({ path: '/expert/expert/add', query: { id: _id } });

  // const res = await getExpert(_id);



  // reset();
  // const _id = row?.expertId || ids.value[0]
  // const res = await getExpert(_id);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = "修改expert";
// }

/** 提交按钮 */
const submitForm = () => {
  expertFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateExpert(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addExpert(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ApprovalVO) => {
  const _ids = row?.expertId || ids.value;
  await proxy?.$modal.confirm('是否确认删除expert编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delExpert(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 下载模板/导出按钮操作 */
const handleExport = (type) => {
  proxy?.download('/zjk-api/expert/export', {
    ...queryParams.value,
    isTemplate: type
  }, `expert_${new Date().getTime()}.xlsx`)


  // proxy?.download('zjk-api/expert/export', {
  // // proxy?.download('expert/expert/export', {
  //   ...queryParams.value
  // }, `expert_${new Date().getTime()}.xlsx`)
}
onActivated(() => {
  getList();
})
onMounted(() => {
  getList();
});
</script>


<style scoped lang="scss">
.title {
position: relative;
padding-left: 1vw;
font-size: 1.2rem;
margin: 0
}
.title::before {
content: "";
width: 5px;
height: 20px;
display: block;
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
border-radius: 3px;
background-color: #36d;
}
</style>

