<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="itemCode">
              <el-input v-model="queryParams.itemCode" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="queryParams.itemName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="抽取状态" prop="extractionStatus">
              <el-select v-model="queryParams.extractionStatus" clearable>
                <el-option v-for="(label, value) in extractStatusOptions" :key="value" :label="label" :value="value" />
              </el-select>
            </el-form-item>
            <el-form-item label="抽取时间" prop="extractDate" style="width: 330px">
              <el-date-picker
                clearable
                v-model="queryParams.extractDate"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </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>
        <el-card shadow="never" class="mt-[10px]">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Box" @click="handleShow(null, 'extract')">抽取</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="extractList">
            <el-table-column label="序号" width="50px" type="index"></el-table-column>
            <el-table-column
              :label="label"
              :align="align || 'center'"
              prop="expertName"
              :min-width="minWidth"
              :width="width"
              v-for="{ label, prop, align, minWidth, width } in headers"
              :key="prop"
            >
              <template #default="{ row }">
                <router-link
                  class="goto-log"
                  :to="`/project/extractLog?itemId=${row.productSn}&reviewSn=${row.reviewSn}`"
                  v-if="prop == 'extractionCount'"
                >
                  {{ row.extractionCount }}
                </router-link>
                <span v-else-if="prop == 'reviewSn'">
                  {{ stageObj[row.reviewSn] || '-' }}
                </span>
                <span v-else-if="prop == 'extractionStatus'">
                  {{ extractStatusOptions[row.extractionStatus] }}
                </span>
                <span v-else>{{ row[prop] ?? '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150px" fixed="right" class-name="small-padding fixed-width">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleShow(row, 'view')">查看</el-button>
                <el-button link type="primary" :disabled="row.extractionStatus != 1" @click="handleShow(row, 'reExtract')">补抽</el-button>
                <el-button link type="primary" :disabled="row.isSure == 1" @click="confirmExtract(row)">确定</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" :total="page.total" v-model:page="page.pageNum" v-model:limit="page.pageSize" @pagination="getList" />
        </el-card>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { confirmExtractAjax } from '@/api/project/extract';
import { getTableList } from '@/api/project/extract';
import { ExtractVO, ExtractQuery } from '@/api/project/extract/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { item_stage } = toRefs<any>(proxy?.useDict('item_stage'));
const stageObj = computed(() => {
  let obj = {};
  item_stage.value.forEach((e:any) => {
    obj[e.value] = e.label;
  });
  return obj;
});

const extractList = ref<ExtractVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);

const router = useRouter();

const queryFormRef = ref<ElFormInstance>();

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
  width?: string | number;
}
const headers = ref<Header[]>([
  {
    label: '项目编号',
    prop: 'productSn'
  },
  {
    label: '项目名称',
    prop: 'projectName'
  },
  {
    label: '项目阶段',
    prop: 'reviewSn',
    width: 100
  },
  {
    label: '抽取次数',
    prop: 'extractionCount',
    width: 100
  },
  {
    label: '专家人数',
    prop: 'expertSum',
    width:100,
  },
  {
    label: '已抽取人数',
    prop: 'extractedSum',
    width:100
  },
  {
    label: '抽取时间',
    prop: 'extractionTime',
    width: 160
  },
  {
    label: '抽取人',
    prop: 'extractionUser',
    width: 150
  },
  {
    label: '抽取状态',
    prop: 'extractionStatus',
    width: 100
  }
]);

const extractStatusOptions = {
  1: '部分抽取',
  2: '抽取完成'
};
const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryParams = ref<ExtractQuery>({
  itemName: '',
  itemCode: '',
  extractionStatus: '',
  extractDate: []
});

/** 查询expert列表 */
const getList = async () => {
  extractList.value = []
  loading.value = true;
  let startExtractionTime = queryParams.value.extractDate[0] || '';
  let endExtractionTime = queryParams.value.extractDate[1] || '';
  const res = await getTableList({
    ...queryParams.value,
    startExtractionTime,
    endExtractionTime,
    pageNum: page.value.pageNum,
    pageSize: page.value.pageSize,
  });
  if (res.code === 200) {
    extractList.value = res.rows.map(item => {
      return {
        ...item,
        projectName: item.zjkProductVo.productName,
        productSn: item.zjkProductVo.productSn,
        reviewSn: item.zjkReviewPhase?.reviewSn
      }
    })
    page.value.total = res.total;
    loading.value = false;
  }
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
const handleShow = (row: ExtractVO | null, type: string) => {
  let query: any = {
    type
  };
  if (row) {
    query.id = row.id;
  }
  router.push({
    path: '/project/extractExtract',
    query
  });
};
const confirmExtract = async (row:any) => {
  if (!row.reviewId) {
    ElNotification({
      title: '提示',
      message: '抽取结果不存在',
      type: 'error'
    });
    return;
  }
  let params = {
    reviewId: row.reviewId
  };
  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'
      });
      await getList();
    })
    .catch(() => {});
};
onActivated(() => {
  getList();
});
onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.goto-log {
  color: var(--el-color-primary);
  text-decoration: underline;
}
</style>
