<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]">
        <el-card shadow="never">
          <div class="result-icon success-icon mb-[24px] text-center" v-if="isSuccess">
            <el-icon><CircleCheckFilled /></el-icon>
            <div>抽取成功</div>
          </div>
          <div class="result-icon error-icon mb-[24px] text-center" v-else>
            <el-icon><CircleCloseFilled /></el-icon>
            <div>抽取失败</div>
          </div>
          <el-table :data="resultList">
            <el-table-column
              :label="label"
              :align="align || 'center'"
              :min-width="minWidth || '100px'"
              v-for="{ label, prop, align, minWidth } in headers"
              :key="prop"
            >
              <template #default="{ row }">
                <router-link class="goto-log" :to="`/project/extractLog?projectNum=${row.projectNum}`" v-if="prop == 'expertName'">
                  {{ row.expertName }}
                </router-link>
                <div v-else-if="prop == 'major'">
                  <div v-if="row.zjkExpertMajorList?.length > 0">
                    <div v-for="major in row.zjkExpertMajorList">
                      <span v-if="major.major && major.degree">{{ major.major || '-' }}（{{ degreeType(major.degree) || '-' }}）</span>
                      <span v-else>-</span>
                    </div>
                  </div>
                  <div v-else>-</div>
                </div>
                <span v-else-if="prop == 'expertStatus'">
                  {{ expertStatusOptions[row.expertStatus] }}
                </span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
          </el-table>
          <div class="mt-[20px] text-right">
            <el-button @click="reExtract('cancel')">取消</el-button>
            <el-button type="primary" :loading="loading" @click="reExtract('reExtract')">重抽</el-button>
            <el-button type="primary" @click="confirmExtract">确定</el-button>
          </div>
        </el-card>
        <el-dialog :title="title" v-model="dialog.visible" width="500px" :before-close="CloseDialog">
          <el-form :model="dialog.form" ref="reasomFormRef" :rules="dialog.rules" label-width="50px">
            <el-form-item label="原因" prop="content">
              <el-input
                type="textarea"
                :rows="5"
                resize="none"
                v-model="dialog.form.content"
                :placeholder="`每次抽取结果都将会被记录，请输入${title}原因`"
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span>
              <el-button @click="CloseDialog">取消</el-button>
              <el-button type="primary" @click="confirmSubmit">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>
<script lang="ts" setup>
import { getResult, ExtractAjax, confirmExtractAjax, CancelAjax, getExpertList } from '@/api/project/extract';
import { ResultListType } from '@/api/project/extract/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { degree_type } = toRefs<any>(proxy?.useDict('degree_type'));
const degreeType = (id) => {
  let item = degree_type.value.find((item) => item.value == id);
  return item?.label || '';
};
const { perform_work_type } = toRefs<any>(proxy?.useDict('perform_work_type'));
const performWorkType = computed(() => perform_work_type.value);
const performWorkObj = computed(() => {
  let obj = {};
  performWorkType.value.forEach((e) => {
    obj[e.value] = e.label;
  });
  return obj;
});
const route = useRoute();
const id = computed(() => route.query.id);
const type = computed(() => route.query.type);
const resultList = ref<ResultListType[]>([]);
const expertStatusOptions = {
  1: '待确认',
  2: '已同意',
  3: '已拒绝',
  4: '已请假'
};
interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
}
const headers = ref<Header[]>([
  {
    label: '专家姓名',
    prop: 'expertName'
  },
  {
    label: '联系方式',
    prop: 'concat'
  },
  {
    label: '工作单位',
    prop: 'workUnit'
  },
  {
    label: '职务',
    prop: 'duty'
  },
  {
    label: '专业/学历',
    prop: 'major'
  },
  {
    label: '研究领域',
    prop: 'performWorkName'
  }
]);
const isSuccess = ref(true);
const reviewId = ref('');
const getExpert = async (id) => {
  let res = await getExpertList({ reviewId: id });
  resultList.value = res.data.map((e) => {
    let performWorkId = e.performWorkName?.replace(/\r/, '').split(',') || [];
    return {
      ...e,
      performWorkId,
      performWorkName: performWorkId.map((e) => performWorkObj.value[e]).join(',')
    };
  });
};
const getResultList = async (new_id) => {
  let res = await getResult(new_id || (id.value as string));
  let ruleLast = res.data.zjkReviewPhaseVoList[0];
  reviewId.value = ruleLast.id;
  await getExpert(ruleLast.id);
};

const reasomFormRef = ref(null);
const dialog = ref({
  visible: false,
  type: 'cancel',
  form: {
    content: ''
  },
  rules: {
    content: [
      {
        required: true,
        validator: (rule: any, value: string, callback: any) => {
          if (!value) {
            callback(new Error(`请输入${title.value}原因`));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  }
});
const title = computed(() => {
  return dialog.value.type == 'cancel' ? '取消' : '重抽';
});

const CloseDialog = () => {
  reasomFormRef.value.resetFields();
  dialog.value.visible = false;
};
const loading = ref(false);
const confirmSubmit = () => {
  let params: any = {
    id: id.value,
    reviewId: reviewId.value
  };
  ElMessageBox.confirm(`每次抽取结果都将会被记录，是否确定${title.value}抽取`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const json = {
        cancel: async () => {
          params.causeRepum = dialog.value.form.content;
          let res = await CancelAjax(params);
          if (res.code != 200) {
            ElNotification({
              title: '提示',
              message: res.msg,
              type: 'error'
            });
            return;
          }
          ElNotification({
            title: '提示',
            message: `取消成功，跳转到${type.value == 'extract' ? '抽取' : '补抽'}条件页面`,
            type: 'success'
          });
          proxy?.$tab.closePage(proxy?.$route).then(() => {
            proxy?.$router.replace({
              path: '/project/extractExtract',
              query: {
                type: type.value,
                id: id.value
              }
            });
          });
        },
        reExtract: async () => {
          loading.value = true;
          params.causeRepum = dialog.value.form.content;
          let res = await ExtractAjax(params);
          if (res.code != 200) {
            ElNotification({
              title: '提示',
              message: res.msg,
              type: 'error'
            });
            return;
          }
          ElNotification({
            title: '提示',
            message: '重抽成功',
            type: 'success'
          });
          loading.value = false;
          proxy.$router.replace({
            query: {
              type: type.value,
              id: res.data as string
            }
          });
          CloseDialog();
          await getResultList(res.data);
        }
      };
      reasomFormRef.value.validate((valid) => {
        if (!valid) return;
        json[dialog.value.type]();
      });
    })
    .catch(() => {});
};

const reExtract = async (type) => {
  dialog.value.type = type;
  dialog.value.form.content = '';
  dialog.value.visible = true;
};
const confirmExtract = async () => {
  if (!reviewId.value) {
    ElNotification({
      title: '提示',
      message: '抽取结果不存在',
      type: 'error'
    });
    return;
  }
  let params = {
    reviewId: reviewId.value
  };
  ElMessageBox.confirm(`是否确定本次抽取结果`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await confirmExtractAjax(params);
      if (res.code != 200) {
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: '确认抽取成功',
        type: 'success'
      });
      proxy?.$tab.closePage(proxy?.$route).then(() => {
        proxy?.$router.replace(type.value == 'logview' ? '/project/extractLog' : '/project/extract');
      });
    })
    .catch(() => {});
};
onActivated(() => {
  getResultList(null);
});
onMounted(() => {
  getResultList(null);
});
</script>
<style lang="scss" scoped>
.result-icon {
  &.success-icon {
    color: var(--el-color-success);
  }
  &.error-icon {
    color: var(--el-color-danger);
  }
  font-size: 20px;
  :deep(.el-icon) {
    font-size: 80px;
  }
}
.back-to-list {
  // display: flex;
  // align-items: center;
  gap: 10px;
  &:hover * {
    color: var(--el-color-primary);
  }
}
</style>
