<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="name">
              <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="生日" prop="birthDate">
              <el-date-picker clearable
                v-model="queryParams.birthDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择生日"
              />
            </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="organization">
              <el-input v-model="queryParams.organization" 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="entryResult">
              <el-select v-model="queryParams.entryResult" placeholder="请选择入库结果" clearable>
                <el-option v-for="dict in approval_status" :key="dict.value" :label="dict.label" :value="dict.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>
    <div class="mb-[10px]">
      <el-card shadow="hover">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button color="#626aef" plain icon="Download" @click="handleExport(1)">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </el-card>
    </div>
    <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 label="id" align="center" prop="id" /> -->
        <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="name" minWidth="180" />

        <!-- <el-table-column label="性别" align="center" prop="sex" minWidth="110">
          <template #default="scope">
            <span>{{ scope.row.sex == 0 ? '男' : scope.row.sex == 1 ? '女' : '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="生日" align="center" prop="birthDate" minWidth="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="联系方式" align="center" prop="contactInfo" minWidth="160" />
        <el-table-column label="工作单位" align="center" prop="organization" minWidth="250" />
        <el-table-column label="职务" align="center" prop="position" minWidth="150" />
        <el-table-column label="入库结果" align="center" prop="entryResult" minWidth="220">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.entryResult)">
              {{ getTagLabel(scope.row.entryResult) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="applicationTime" minWidth="250" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" minWidth="160">
          <template #default="scope">
            <span v-if="scope.row.entryResult == '1'" @click="viewReject(scope.row, '通过意见')"
              style="color: #67c23a;cursor: pointer;">通过意见</span>
            <span v-if="scope.row.entryResult == '2'" @click="viewReject(scope.row, '驳回理由')"
              style="color: #f56c6c;cursor: pointer;">驳回理由</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>
    <!-- 添加或修改expert对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <span>{{ dialogContent }}</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="confirm">确 认</el-button>
          <!-- <el-button @click="cancel">取 消</el-button> -->
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Expert" lang="ts">
import { listExpert, getExpert, delExpert, addExpert, updateExpert } from '@/api/expert/enterRecord/index';
import { EnterVO, EnterQuery, EnterForm } from '@/api/expert/enterRecord/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 expertList = ref<EnterVO[]>([]);
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 getTagType = (entryResult) => {
  const typeMap = {
    '1': 'success',
    '2': 'danger',
  };
  return typeMap[entryResult] || 'info'; // 默认类型为 info
};

// 根据结果值获取标签文本
const getTagLabel = (entryResult) => {
  const labelMap = {
    '1': '通过',
    '2': '拒绝',
  };
  return labelMap[entryResult] || '未知';
};
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: EnterForm = {
  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,
  remark: undefined,
  createdBy: undefined,
  createdTime: undefined,
  updatedBy: undefined,
  updatedTime: undefined,
  deleteFlag: undefined,
  approver: undefined,
  approvalType: undefined,
  approvalOpinion: undefined,
}
const data = reactive<PageData<EnterForm, EnterQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    expertId: undefined,
    name: undefined,
    organization: undefined,
    entryResult: undefined,
    applyStartTime: undefined,
    applyEndTime: undefined,

    createdBy: undefined,
    createdTime: undefined,
    updatedBy: undefined,
    updatedTime: undefined,
    deleteFlag: undefined,
    params: {
    },
  },
  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 dialogContent = ref('');
/** 查看驳回理由操作 */
const viewReject = (data, title) => {
  dialogContent.value = data.rejectionReason;
  dialog.title = title;
  dialog.visible = true;

};
/** 导入按钮操作 */
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 confirm = () => {
  dialog.visible = false;
}
/** 表单重置 */
const reset = () => {
  // form.value = { ...initFormData };
  expertFormRef.value?.resetFields();
}

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: EnterVO[]) => {
  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?: EnterVO) => {

//   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.expertId) {
        await updateExpert(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addExpert(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");

      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: EnterVO) => {
  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>
