<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">
              <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>
              <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">
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['expert:expert:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['expert:expert:remove']">删除</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="info" plain icon="FolderAdd" @click="handleExport(0)"
              v-hasPermi="['expert:expert:download']">下载模板</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleImport"
              v-hasPermi="['expert:expert:import']">导入</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button color="#626aef" plain icon="Download" @click="handleExport(1)"
              v-hasPermi="['expert:expert:export']">导出</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button color="#529b2e" plain icon="Promotion" @click="toBeiAn">备案</el-button>
          </el-col>

          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="expertList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <!-- <el-table-column label="id" align="center" prop="id" /> -->
        <el-table-column type="index" label="序号" width="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">
          <template #default="scope">
            <span @click="jumpToDetail(scope.row)" class="expertName">{{ scope.row.expertName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" prop="sex">
          <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">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" align="center" prop="contact" />
        <el-table-column label="工作单位" align="center" prop="workUnit" />
        <el-table-column label="职务" align="center" prop="duty" />
        <el-table-column label="来源" align="center" prop="expertSources">
          <template #default="scope">
            <dict-tag :options="expert_sources" :value="scope.row.expertSources"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template #default="scope">
            <span @click="handleUpdate(scope.row)" style="color:#36d;cursor: pointer;">修改</span>
            <el-divider direction="vertical"> </el-divider>
              <span @click="handleMoveToBlack(scope.row)"
                :style="scope.row.rewardType == '4' || scope.row.rewardType == '5' || scope.row.rewardType == '6' ? 'color:#529b2e;cursor: pointer;' : 'color:#36d;cursor: pointer;'">{{
                  scope.row.rewardType == '4' || scope.row.rewardType == '5' || scope.row.rewardType ==
                    '6' ? '移出黑名单' : '加入黑名单' }}</span>
              <el-divider direction="vertical"> </el-divider>
                <span @click="handleDelete(scope.row)" style="color:#36d;cursor: pointer;">删除</span>
            <el-divider direction="vertical" />
            <span
              @click="handleVerify(scope.row)"
              style="color: #67c23a; 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>
      <el-form ref="expertFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="id" prop="id">
          <el-input v-model="form.expertId" placeholder="请输入id" />
        </el-form-item>
        <el-form-item label="姓名" prop="expertName">
          <el-input v-model="form.expertName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="生日" prop="birthDate">
          <el-date-picker clearable v-model="form.birthDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择生日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="工作单位" prop="workUnit">
          <el-input v-model="form.workUnit" placeholder="请输入工作单位" />
        </el-form-item>
        <el-form-item label="职务" prop="duty">
          <el-input v-model="form.duty" placeholder="请输入职务" />
        </el-form-item>
        <el-form-item label="政治面貌" prop="politics">
          <el-input v-model="form.politics" placeholder="请输入政治面貌" />
        </el-form-item>
        <el-form-item label="毕业学校" prop="graduateSchool">
          <el-input v-model="form.graduateSchool" placeholder="请输入毕业学校" />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="form.major" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="专业技术资格" prop="professional">
          <el-input v-model="form.professional" placeholder="请输入专业技术资格" />
        </el-form-item>
        <el-form-item label="专业技术资格取得时间" prop="professionalAcquisitionDate">
          <el-date-picker clearable v-model="form.professionalAcquisitionDate" type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择专业技术资格取得时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="从事专业" prop="workProfessial">
          <el-input v-model="form.workProfessial" placeholder="请输入从事专业" />
        </el-form-item>
        <el-form-item label="从事专业年限" prop="workProfessialYear">
          <el-input v-model="form.workProfessialYear" placeholder="请输入从事专业年限" />
        </el-form-item>
        <el-form-item label="照片" prop="photograph">
          <el-input v-model="form.photograph" placeholder="请输入照片" />
        </el-form-item>
        <el-form-item label="从事工作或研究领域" prop="performWorkId">
          <!-- <el-input v-model="form.performWorkId" placeholder="请输入从事工作或研究领域" /> -->
        </el-form-item>
        <el-form-item label="其他领域描述" prop="otherDescribe">
          <el-input v-model="form.otherDescribe" placeholder="请输入其他领域描述" />
        </el-form-item>
        <el-form-item label="专业相关经历" prop="workExperience">
          <el-input v-model="form.workExperience" placeholder="请输入专业相关经历" />
        </el-form-item>
        <el-form-item label="参与政务信息化项目评审情况" prop="workPluralistic">
          <el-input v-model="form.workPluralistic" placeholder="请输入参与政务信息化项目评审情况" />
        </el-form-item>
        <el-form-item label="主要论著、业绩成果及获奖情况" prop="achievement">
          <el-input v-model="form.achievement" placeholder="请输入主要论著、业绩成果及获奖情况" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker clearable v-model="form.createdTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改人" prop="updatedBy">
          <el-input v-model="form.updatedBy" placeholder="请输入修改人" />
        </el-form-item>
        <el-form-item label="修改时间" prop="updatedTime">
          <el-date-picker clearable v-model="form.updatedTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择修改时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否删除" prop="deleteFlag">
          <el-input v-model="form.deleteFlag" placeholder="请输入是否删除" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 专家库导入对话框 -->
    <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, moveToBlack, moveBackBlack } from '@/api/expert/expert/index';
import { ExpertVO, ExpertQuery, ExpertForm } from '@/api/expert/expert/types';
import $bus from '@/utils/mitt'
import { globalHeaders } from '@/utils/request';
import { verifyHmac } from '@/api/project/maintain';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { approval_status } = toRefs<any>(proxy?.useDict('approval_status'));
const { expert_sources } = toRefs<any>(proxy?.useDict('expert_sources'));


const expertList = ref<ExpertVO[]>([]);
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: ExpertForm = {
  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,
  paperpath: undefined,
  patentpath: undefined,
}
const data = reactive<PageData<ExpertForm, ExpertQuery>>({
  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: 0
  },
  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 toBeiAn = (row) => {

};
/** 导入按钮操作 */
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 reset = () => {
  form.value = { ...initFormData };
  expertFormRef.value?.resetFields();
}

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

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

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


/** 查看专家详情 */
const jumpToDetail = (row) => {
  const _id = row?.expertId;
  router.push({ path: '/expert/expertDetail', query: { id: _id, type: 'detail' } })
  // router.push({ path: '/expert/expert/add', query: { id: _id, type: 'detail' } })
};

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

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

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

}

/** 提交按钮 */
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("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 移入黑名单操作 */
const handleMoveToBlack = async (row?: ExpertVO) => {
  // if (row.rewardType == '4' || row.rewardType == '5' || row.rewardType == '6') {
  //   return
  // }
  loading.value = true;
  const _id = row?.expertId;
  const _name = row.expertName;
  const _userId = row.userId;
  if (row.rewardType == '4' || row.rewardType == '5' || row.rewardType == '6') {
    await proxy?.$modal.confirm('是否确认将专家"' + _name + '"从黑名单中移出？').finally(() => loading.value = false);
    await moveBackBlack({ userId: _userId, expertId: _id });
    proxy?.$modal.msgSuccess("操作成功");
  } else {
    await proxy?.$modal.confirm('是否确认将专家"' + _name + '"移入黑名单？').finally(() => loading.value = false);
    await moveToBlack({ userId: _userId, expertId: _id });
    proxy?.$modal.msgSuccess("操作成功");
  }

  // await proxy?.$modal.confirm('是否确认将"' + _name + '"专家移入黑名单？').finally(() => loading.value = false);
  // await moveToBlack({userId:_userId,expertId:_id});
  // proxy?.$modal.msgSuccess("操作成功");
  await getList();
}

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

/**hmac校验*/
function handleVerify(row: any) {
  verifyHmac({
    bizType: 'expert',
    id: row.expertId,
    fields: []
  })
    .then(result => {
      if (result.match) {
        ElMessage.success('校验通过');
      } else {
        ElMessage.error(`校验失败，该信息被篡改`);
      }
    })
    .catch(err => {
      ElMessage.error('接口请求失败: ' + (err.response?.data?.msg || err.message));
    });
}

/** 下载模板/导出按钮操作 */
const handleExport = (type) => {
  proxy?.download('/zjk-api/expert/export', {
    ...queryParams.value,
    'isTemplate': type,
    expertIds: ids.value.join(',')
  }, `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">
.expertName {
  color: #36d;
  cursor: pointer;
}
</style>
