<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 v-loading="loading" shadow="never">
          <el-form
            ref="projectFormRef"
            :class="['logview', 'view'].includes(type) ? '' : 'form-main'"
            :model="projectForm"
            :rules="projectRules"
            label-width="170px"
          >
            <div class="model-title">项目信息</div>
            <el-form-item label="项目名称：" prop="projectId">
              <span v-if="['logview', 'view'].includes(type)">{{ projectForm.productName }}</span>
              <el-select v-else v-model="projectForm.projectId" :disabled="type == 'reExtract'" filterable
                         placeholder="请选择项目">
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.productName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目类型：" prop="productType">
              <span v-if="['logview', 'view'].includes(type)">{{ projectTypeObj[projectForm.productType] }}</span>
              <el-select v-else v-model="projectForm.productType" disabled filterable placeholder="请选择项目">
                <el-option v-for="item in projectTypeOptions" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目规模（万元）：" prop="productScale">
              <span v-if="['logview', 'view'].includes(type)">{{ projectForm.productScale }}</span>
              <el-input v-else v-model="projectForm.productScale" disabled placeholder="请输入项目规模（万元）" />
            </el-form-item>
            <el-form-item label="项目单位名称：" prop="productUnit">
              <span v-if="['logview', 'view'].includes(type)">{{ projectForm.productUnit }}</span>
              <el-input v-else v-model="projectForm.productUnit" disabled placeholder="请输入项目单位名称" />
            </el-form-item>
            <el-form-item label="项目单位联系人：" prop="unitBy">
              <span v-if="['logview', 'view'].includes(type)">{{ projectForm.unitBy }}</span>
              <el-input v-else v-model="projectForm.unitBy" disabled placeholder="请输入项目单位联系人" />
            </el-form-item>
            <el-form-item label="联系人电话：" prop="contact">
              <span v-if="['logview', 'view'].includes(type)">{{ projectForm.contact }}</span>
              <el-input v-else v-model="projectForm.contact" disabled placeholder="请输入联系人电话" />
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-loading="ruleLoading" class="mt-[10px]" shadow="never">
          <template v-if="['logview', 'view'].includes(type)" #header>
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
              <el-tab-pane v-for="tab in tabs" :label="`LSH${tab}`" :name="tab"></el-tab-pane>
            </el-tabs>
          </template>
          <el-form ref="formRef"
                   :class="['logview', 'view'].includes(type) ? '' : 'form-main'" :model="form" :rules="rules"
                   class="look-form" label-width="170px">
            <div class="model-title">抽取条件设置</div>
            <template v-if="['logview', 'view'].includes(type)">
              <div class="form-item-gird">
                <el-form-item label="评审阶段：">
                  <span>{{ stageObj[form.reviewSn] }}</span>
                </el-form-item>
                <el-form-item label="评审地点：">
                  <span>{{ form.reviewPlace }}</span>
                </el-form-item>
                <el-form-item label="评审时间：">
                  <span>{{ form.reviewTime }}</span>
                </el-form-item>
                <el-form-item label="计划抽取人数：">
                  <span>{{ form.count }}人</span>
                </el-form-item>
                <el-form-item label="抽取方式：">
                  <span>{{ extractTypeOptions[form.mode] }}</span>
                </el-form-item>
                <el-form-item v-if="form.areaList.length > 0" label="抽取领域：">
                  <div>
                    <div v-for="(item, index) in form.areaList">{{ index + 1 }}：{{ areaOptionsObj[item.area]
                      }}：{{ item.num }}人
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="抽取限制：">
                  <div style="height: 100%">
                    <div v-for="(id, index) in form.extractioRestrictio">{{ index + 1 }}：{{ extractLimitOptions[id] }}
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="确认时间设置：">
                  <div class="confirm-time">
                    专家在 {{ form.noticeTime || '-' }} 前可接受/拒绝
                  </div>
                </el-form-item>
              </div>
            </template>
            <template v-else>
              <el-form-item label="评审阶段：" prop="reviewSn">
                <el-select v-model="form.reviewSn" :disabled="type == 'reExtract'" placeholder="请选择评价阶段">
                  <el-option v-for="item in stageOptions" :key="item.value" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="评审地点：" prop="reviewPlace">
                <el-input v-model="form.reviewPlace" :disabled="type == 'reExtract'" placeholder="请输入评审地点" />
              </el-form-item>
              <el-form-item label="评审时间：" prop="reviewTime">
                <el-date-picker
                  v-model="form.reviewTime"
                  :disabled="type == 'reExtract'"
                  :disabled-date="disabledDate"
                  placeholder="选择日期时间"
                  popper-class="currentDatePickerClass"
                  style="flex: 1"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="计划抽取人数：" prop="count">
                <el-input-number v-model="form.count" :disabled="type == 'reExtract'" :min="5" :step="2"
                                 class="flex-1" />
              </el-form-item>
              <el-form-item v-if="form.mode != 'appoint'" :rules="{ required: true }" label="抽取领域：">
                <div class="extract-area">
                  <div v-for="(item, index) in form.areaList" class="extract-area-item position-relative">
                    <el-form-item :prop="`areaList[${index}][area]`" :rules="rules.area" label="">
                      <el-select v-model="item.area" filterable>
                        <el-option v-for="item in otherAreaOptions(index)" :key="item.value" :label="item.label"
                                   :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item :prop="`areaList[${index}][num]`" :rules="rules.num" label="">
                      <el-input-number v-model="item.num" :min="1" class="flex-1" />
                    </el-form-item>
                    <div class="icon-main flex gap-2 position-absolute">
                      <el-icon>
                        <CirclePlus v-show="plusShow" @click="PlusArea" />
                      </el-icon>
                      <el-icon>
                        <Remove v-show="removeShow(item)" @click="MinusArea(index)" />
                      </el-icon>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="抽取方式：" prop="mode">
                <el-radio-group v-model="form.mode" @change="changeExtractType">
                  <el-radio v-for="(label, value) in extractTypeOptions" :key="value"
                            :disabled="appointRandomDisabled(value)" :label="value">
                    {{ label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.mode == 'appointRandom'" label="指定数量：" prop="expertsCout">
                <el-input-number v-model="form.expertsCout" :min="1" class="flex-1" />
              </el-form-item>
              <el-form-item v-if="form.mode != 'random'" label="指定专家：" prop="expertsId">
                <el-select
                  v-model="form.expertsId"
                  :loading="expertsLoading"
                  :remote-method="getExperts"
                  filterable
                  multiple
                  placeholder="请选择指定专家"
                  remote
                >
                  <el-option
                    v-for="item in appointExpertOptions"
                    :key="item.expertId"
                    :label="`${item.workUnit} - ${item.expertName}（${item.contact}）-（${item.performWorkName}）`"
                    :value="item.expertId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="form.mode != 'appoint'" label="抽取限制：">
                <el-checkbox-group v-model="form.extractioRestrictio">
                  <el-checkbox v-for="(label, value) in extractLimitOptions" :key="value" :disabled="value == 1"
                               :label="value">
                    {{ label }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="确认时间设置：" prop="noticeTime">
                <div class="confirm-time">
                  <span>专家在</span>
                  <el-date-picker
                    v-model="form.noticeTime"
                    :disabled="!form.reviewTime"
                    :disabled-date="confirmTimeDisabledDate"
                    placeholder="选择日期时间"
                    style="flex: 1"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  >
                  </el-date-picker>
                  <span>前可接受/拒绝</span>
                </div>
              </el-form-item>
            </template>
            <div v-if="!['logview', 'view'].includes(type)">
              <div v-if="form.mode != 'appoint'">
                <div class="model-title">
                  <span class="mr-[10px]">抽取回避设置</span>
                  <el-switch v-model="form.isAvoid" :active-value="true" :inactive-value="false"></el-switch>
                </div>
                <div v-if="form.isAvoid">
                  <el-form-item label="回避专家：" prop="expertIds">
                    <el-select
                      v-model="form.expertIds"
                      :loading="expertsLoading"
                      :remote-method="getExperts"
                      filterable
                      multiple
                      placeholder="请选择回避专家"
                      remote
                    >
                      <el-option
                        v-for="item in avoidExpertOptions"
                        :key="item.expertId"
                        :label="`${item.workUnit} - ${item.expertName}（${item.contact}）-（${item.performWorkName}）`"
                        :value="item.expertId"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="回避单位：">
                    <el-select
                      v-model="form.unit"
                      :loading="unitLoading"
                      :remote-method="getUnits"
                      filterable
                      multiple
                      placeholder="请选择回避单位"
                      remote
                    >
                      <el-option v-for="item in unitOptions" :key="item.label" :label="item.label"
                                 :value="item.label"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </div>
            <div v-else class="mb-[24px]">
              <div class="model-title">抽取结果</div>
              <el-table :data="resultList">
                <el-table-column
                  v-for="({ label, prop, align, minWidth }) in headers"
                  :key="prop"
                  :align="align || 'center'"
                  :label="label"
                  :min-width="minWidth || '100px'"
                  prop="expertName"
                >
                  <template #default="{ row }">
                    <!-- <router-link class="goto-log" :to="`/expert/expert/add?id=${row.expertId}&type=detail`" v-if="prop == 'expertName'">
                      {{ row.expertName || '-' }}
                    </router-link> -->
                    <span v-if="prop == 'acceptStatus'">
                      {{ expertStatusOptions[row.acceptStatus] || '-' }}
                    </span>
                    <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 == 'isSource'">
                      {{ row.isSource == 1 ? '来自补抽' : '原始数据' }}
                    </span>
                    <span v-else-if="prop == 'extractionStatus'">
                      {{ extractionStatusOptions[row.extractionStatus] || '-' }}
                    </span>
                    <span v-else>{{ row[prop] || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column v-if="[1, 2].includes(extractionStatus)" class-name="small-padding fixed-width"
                                 fixed="right"
                                 label="操作">
                  <template #default="{ row }">
                    <el-button :disabled="row.acceptStatus != 1" link type="primary" @click="Leave(row)">请假
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-if="type == 'reExtract'">
              <div class="model-title">
                <span class="mr-[10px]">抽取信息</span>
              </div>
              <div>
                <el-form-item label="补抽人数：" prop="supplementNum">
                  <el-input-number v-model="form.supplementNum" class="flex-1" disabled />
                </el-form-item>
                <el-form-item label="抽取区域：">
                  <el-cascader
                    v-model="form.extractArea"
                    :options="extractAreaOptions"
                    :props="{ label: 'name', value: 'code', children: 'codeName', checkStrictly: true }"
                    placeholder="请选择抽取区域"
                    style="width: 100%"
                  />
                </el-form-item>
              </div>
            </div>
          </el-form>
          <div style="flex: 1; text-align: right">
            <el-button @click="Cancel">返回</el-button>
            <el-button v-show="type == 'extract'" type="primary" @click="Extract">抽取</el-button>
            <el-button v-show="type == 'reExtract'" type="primary" @click="Extract">补抽</el-button>
          </div>
        </el-card>
        <el-dialog v-model="leaveDialog.visible" :before-close="Close" title="请假理由" width="420px">
          <el-form ref="leaveForm" :model="leaveDialog.form" :rules="leaveDialog.rules" label-width="0">
            <el-form-item label="" prop="result">
              <el-input v-model="leaveDialog.form.result" :rows="5" placeholder="请输入请假理由" resize="none"
                        type="textarea"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span>
              <el-button @click="Close">取消</el-button>
              <el-button type="primary" @click="ConfimLeave">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script lang="ts" setup>
import {
  ExtractAjax,
  getArea,
  getExpertList,
  getExpertSelList,
  getProjectSelList,
  getResult,
  getUnitSelList
} from '@/api/project/extract';
import { dictType, ProjectFormType, ProjectRulesType, ResultListType } from '@/api/project/extract/types';
import { setLeave } from '@/api/expert/homePage';
import { onActivated } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { degree_type } = toRefs<any>(proxy?.useDict('degree_type'));
const degreeType = (id: any) => {
  let item = degree_type.value.find((item: any) => item.value == id);
  return item?.label || '';
};
const { item_stage } = toRefs<any>(proxy?.useDict('item_stage'));
const { project_type } = toRefs<any>(proxy?.useDict('project_type'));
const { perform_work_type } = toRefs<any>(proxy?.useDict('perform_work_type'));
const stageOptions = computed<dictType[]>(() => item_stage.value);
const stageObj = computed(() => {
  let obj = {};
  stageOptions.value.forEach((e: any) => {
    obj[e.value] = e.label;
  });
  return obj;
});
const projectTypeOptions = computed<dictType[]>(() => project_type.value);
const projectTypeObj = computed(() => {
  let obj = {};
  project_type.value.forEach((e: any) => {
    obj[e.value] = e.label;
  });
  return obj;
});
const performWorkType = computed(() => perform_work_type.value);
const performWorkObj = computed(() => {
  let obj = {};
  performWorkType.value.forEach((e: any) => {
    obj[e.value] = e.label;
  });
  return obj;
});
const route = useRoute();
const id = computed(() => (route.query.id as string) || '');
const type = computed(() => (route.query.type as string) || '');
const projectForm = ref<ProjectFormType>({
  projectId: '',
  productName: '',
  productType: '',
  productScale: '',
  productUnit: '',
  unitBy: '',
  contact: ''
});

const projectRules = ref<ProjectRulesType>({
  projectId: [{ required: true, message: '项目编号不能为空', trigger: 'change' }],
  productType: [{ required: true, message: '项目类型不能为空', trigger: 'change' }],
  productScale: [{ required: true, message: '项目规模不能为空', trigger: 'change' }],
  productUnit: [{ required: true, message: '项目单位不能为空', trigger: 'change' }],
  unitBy: [{ required: true, message: '联系人不能为空', trigger: 'change' }],
  contact: [{ required: true, message: '联系电话不能为空', trigger: 'change' }]
});

const DEFAULT_SAFE_AREA = ['66'];

const disabledDate = (time) => {
  return time.getTime() < Date.now();
};
const confirmTimeDisabledDate = (time) => {
  let maxTime = new Date(form.value.reviewTime.replace(/-/g, '/')).getTime();
  return time.getTime() < Date.now() || time.getTime() > maxTime;
};
const formRef = ref<ElFormInstance>(null);
const defaultForm = reactive({
  reviewSn: '',
  reviewPlace: '',
  reviewTime: '',
  count: 5,
  mode: 'random',
  expertsCout: 1,
  expertsId: [],
  extractioRestrictio: ['1'],
  noticeTime: '',
  isAvoid: false,
  expertIds: [],
  unit: [],
  supplementNum: 1,
  extractArea: [],
  areaList: [
    {
      area: '',
      num: 0
    }
  ]
});
const form = ref<any>({
  ...defaultForm
});
const appointRandomDisabled = computed(() => {
  return (id: any) => {
    if (type.value == 'reExtract') {
      return form.value.supplementNum <= 1 && id == 'appointRandom';
    }
    return false;
  };
});
const rules: any = {
  reviewSn: [{ required: true, message: '评审阶段不能为空', trigger: 'change' }],
  reviewPlace: [{ required: true, message: '评审地点不能为空', trigger: 'blur' }],
  reviewTime: [{ required: true, message: '评审时间不能为空', trigger: 'change' }],
  count: [
    { required: true, message: '计划抽取人数不能为空', trigger: 'blur' },
    {
      validator: (_: any, value: string, callback: any) => {
        if (+value % 2 == 0) {
          callback(new Error('请输入单数'));
        } else {
          if (form.value.mode == 'appoint') {
            formRef.value?.validateField('expertsId');
          } else {
            formRef.value?.validateField('expertsCout');
          }
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  mode: [{ required: true, message: '抽取方式不能为空', trigger: 'blur' }],
  noticeTime: [{ required: true, message: '确认时间不能为空', trigger: 'change' }],
  expertsCout: [
    {
      required: true,
      validator: (_: any, value: any, callback: any) => {
        let count = type.value == 'extract' ? form.value.count : form.value.supplementNum;
        let label = type.value == 'extract' ? '计划抽取' : '补抽';
        if (areaNumSum.value > count) {
          return callback(new Error(`抽取总人数不能大于${label}人数`));
        }
        formRef.value?.validateField('expertsId');
        callback();
      },
      trigger: 'change'
    }
  ],
  expertsId: [
    { type: 'array', required: true, message: '指定专家不能为空', trigger: 'blur' },
    {
      validator: (_: any, value: any, callback: any) => {
        let count = type.value == 'extract' ? form.value.count : form.value.supplementNum;
        let json = {
          random: () => {
          },
          appoint: () => {
            if (value.length != count) {
              return callback(new Error(`指定专家人数必须等于${count}人`));
            }
            callback();
          },
          appointRandom: () => {
            if (form.value.expertIds.length != 0) {
              let arr = form.value.expertIds.filter((item: any) => {
                return value.includes(item);
              });
              if (arr.length > 0) {
                return callback(new Error(`指定专家不能包含已回避专家`));
              }
            }
            if (value.length != form.value.expertsCout) {
              return callback(new Error(`指定专家人数必须等于${form.value.expertsCout}人`));
            }
            callback();
          }
        };
        json[form.value.mode]();
      }
    }
  ],
  expertIds: [
    {
      validator: (_: any, value: any, callback: any) => {
        if (form.value.expertsId.length != 0) {
          let arr = form.value.expertsId.filter((item: any) => {
            return value.includes(item);
          });
          if (arr.length > 0) {
            return callback(new Error(`回避专家不能包含已指定专家`));
          }
        }
        callback();
      },
      trigger: 'blur'
    }
  ],
  supplementNum: [{ required: true }],
  area: [{ required: true, message: '请选择抽取领域', trigger: 'change' }],
  num: [
    {
      required: true,
      validator: (_: any, value: any, callback: any) => {
        let count = type.value == 'extract' ? form.value.count : form.value.supplementNum;
        let label = type.value == 'extract' ? '计划抽取' : '补抽';
        if (areaNumSum.value > count) {
          return callback(new Error(`领域抽取总人数不能大于${label}人数`));
        }
        callback();
      }
    }
  ]
};
const areaNumSum = computed(() => {
  let sum = form.value.areaList.reduce((acc: any, cur: any) => {
    return acc + cur.num;
  }, 0);
  if (form.value.mode == 'appointRandom') {
    return sum + form.value.expertsCout;
  }
  return sum;
});
const changeExtractType = () => {
  if (form.value.mode == 'random') return;
  formRef.value?.validateField('expertsId');
};
const areaOptions = computed(() => performWorkType.value);
const areaOptionsObj = computed(() => {
  let obj = {};
  areaOptions.value.forEach((e: any) => {
    obj[e.value] = e.label;
  });
  return obj;
});
const otherAreaOptions = computed(() => {
  return (index: number) => {
    let this_id = form.value.areaList[index].area;
    let selected = form.value.areaList.map((e: any) => e.area);
    if (selected.includes(this_id)) {
      selected.splice(selected.indexOf(this_id), 1);
    }
    return areaOptions.value.filter((e: any) => !selected.includes(e.value));
  };
});
const plusShow = computed(() => {
  if (type.value != 'reExtract') {
    return form.value.areaList.length < areaOptions.value.length && areaNumSum.value < form.value.count;
  }
  return form.value.areaList.length < areaOptions.value.length && areaNumSum.value < form.value.supplementNum;
});
const removeShow = computed(() => {
  return (item: any) => {
    if (type.value != 'reExtract') {
      return form.value.areaList.length > 1 && !DEFAULT_SAFE_AREA.includes(item.area);
    }
    return form.value.areaList.length > 1;
  };
});
const PlusArea = () => {
  form.value.areaList.push({
    area: '',
    num: 0
  });
};
const MinusArea = (index: number) => {
  form.value.areaList.splice(index, 1);
};
const projectFormRef = ref<ElFormInstance>(null);
const extractTypeOptions = {
  random: '随机抽取',
  appoint: '指定抽取',
  appointRandom: '随机+指定'
};
const extractLimitOptions = {
  1: '屏蔽同天评审专家',
  2: '同一个单位只能抽取一位专家',
  3: '屏蔽本单位专家'
};
const expertOptions = ref<any[]>([]);
const expertsLoading = ref(false);
// 过滤已选择的专家列表
const filterExpertOptions = (key: any) => {
  if (form.value[key].length == 0) {
    return expertOptions.value;
  }
  return expertOptions.value.filter((e: any) => !form.value[key].includes(e.expertId));
};
const appointExpertOptions = computed(() => {
  return filterExpertOptions('expertIds');
});
const avoidExpertOptions = computed(() => {
  return filterExpertOptions('expertsId');
});
let options = ref([]);
const optionFormat = computed(() => {
  let hash = {};
  return options.value.reduceRight((item, next) => {
    if (!hash[next.expertId]) {
      item.push(next);
      hash[next.expertId] = true;
    }
    return item;
  }, []);
});
const selectOptions = computed(() => {
  let arr = [...form.value.expertsId, ...form.value.expertIds];
  return optionFormat.value.filter((e: any) => arr.includes(e.expertId));
});
const getExperts = async (query: any) => {
  if (!query) return;
  expertsLoading.value = true;
  let res = await getExpertSelList(query);
  expertOptions.value = res.data.map((e: any) => {
    let performWorkId = e.performWorkId?.replace(/\r/, '').split(',') || [];
    return {
      ...e,
      performWorkId,
      performWorkName: performWorkId.map((e: any) => performWorkObj.value[e]).join(',')
    };
  });
  options.value.push(...expertOptions.value);
  expertsLoading.value = false;
};
const unitLoading = ref(false);
const unitOptions = ref<any[]>([]);
const getUnits = async (query: any) => {
  if (!query) return;
  unitLoading.value = true;
  let res = await getUnitSelList(query);
  unitOptions.value =
    res.data?.map((e: any) => {
      return {
        label: e,
        value: e
      };
    }) || [];
  unitLoading.value = false;
};

const extractAreaOptions = ref([]);
const getExtractAreaOptions = async () => {
  let res = await getArea();
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  extractAreaOptions.value = res.data;
};

// 提交抽取
const Extract = async () => {
  // 表单必填项完善校验
  let p_valid = await projectFormRef.value.validate(() => {
  });
  if (!p_valid) {
    ElNotification({
      title: '提示',
      message: '请完善项目信息',
      type: 'error'
    });
    return;
  }
  let f_valid = await formRef.value.validate(() => {
  });
  if (!f_valid) {
    ElNotification({
      title: '提示',
      message: '请完善抽取信息',
      type: 'error'
    });
    return;
  }
  // 复制表单数据
  let value = { ...form.value };
  // 默认二次弹窗提醒内容
  let tip = `是否确定${type.value == 'reExtract' ? '补抽' : '抽取'}`;
  // 根据不同的模式执行不同的数据处理逻辑
  let modeJson = {
    random: () => {
      value.expertsCout = '';
      value.expertsId = [];
      // 检测是否开启了回避开关
      if (!value.isAvoid) {
        delete value.expertIds;
        delete value.unit;
      }
      // 监测是否有安全领域专家
      let areaListIds = value.areaList.map((e: any) => e.area);
      let id = areaListIds.filter((e: any) => DEFAULT_SAFE_AREA.includes(e));
      if (id.length == 0) {
        tip = `原则上至少选择一个安全领域的专家，${tip}`;
      }
    },
    appoint: () => {
      value.expertsCout = '';
      value.areaList = [];
      value.extractioRestrictio = ['1'];
      // 删除回避单位和回避专家数据
      delete value.expertIds;
      delete value.unit;
      // 监测是否有安全领域专家
      let arr = selectOptions.value.filter((e: any) => {
        let arr1 = e.performWorkId.filter((el: any) => DEFAULT_SAFE_AREA.includes(el));
        return arr1.length > 0;
      });
      if (arr.length == 0) {
        tip = `原则上至少选择一个安全领域的专家，${tip}`;
      }
    },
    appointRandom: () => {
      // 检测是否开启了回避开关
      if (!value.isAvoid) {
        delete value.expertIds;
        delete value.unit;
      }
      // 监测是否有安全领域专家
      let arr = selectOptions.value.filter((e: any) => {
        let arr1 = e.performWorkId.filter((el: any) => DEFAULT_SAFE_AREA.includes(el));
        return arr1.length > 0;
      });
      let areaListIds = value.areaList.map((e: any) => e.area);
      let id = areaListIds.filter((e: any) => DEFAULT_SAFE_AREA.includes(e));
      if (arr.length == 0 && id.length == 0) {
        tip = `原则上至少选择一个安全领域的专家，${tip}`;
      }
    }
  };
  modeJson[value.mode]();
  // 如果选择了同一个单位只能抽取一位专家则判断是否有同一个单位的
  const expertsId = value.expertsId || [];
  let arr = selectOptions.value.filter((e: any) => expertsId.includes(e.expertId));
  let units = arr.map((e: any) => e.workUnit);
  if (value.extractioRestrictio.includes('2')) {
    let isRepeat = new Set(units).size !== units.length;
    if (isRepeat) {
      ElNotification({
        title: '提示',
        message: '请勿选择同单位专家',
        type: 'error'
      });
      return;
    }
  }
  if (value.extractioRestrictio.includes('3')) {
    if (value.unit) {
      let isRepeat = value.unit.includes(projectForm.value.productUnit);
      if (isRepeat) {
        ElNotification({
          title: '提示',
          message: `你选择了屏蔽本单位专家，知道专家不能选择单位为：“${projectForm.value.productUnit}”的专家`,
          type: 'error'
        });
        return;
      }
    }
  }

  // 领域数据数组转键值对
  let obj = {};
  value.areaList.forEach((e: any) => {
    obj[e.area] = e.num;
  });
  value.areaList = obj;
  // 判断是否是补抽，不是，补抽数量为空
  if (type.value != 'reExtract') {
    value.supplementNum = '';
  }
  let params = {
    itemid: projectForm.value.projectId,
    redraw: type.value == 'reExtract',
    ...value
  };
  ElMessageBox.confirm(tip, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await ExtractAjax(params);
      if (res.code != 200) {
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: `${type.value == 'reExtract' ? '补抽' : '抽取'}成功`,
        type: 'success'
      });

      proxy?.$tab.closePage(proxy?.$route).then(() => {
        proxy?.$router.replace({
          path: '/project/result',
          query: {
            id: res.data as string,
            type: type.value
          }
        });
      });
    })
    .catch(() => {
    });
};
// 取消抽取
const Cancel = () => {
  proxy?.$tab.closePage(proxy?.$route).then(() => {
    proxy?.$router.replace(type.value == 'logview' ? '/project/extractLog' : '/project/extract');
  });
};
/* 详情抽取结果专家列表 */
const resultList = ref<ResultListType[]>([]);
const expertStatusOptions = {
  0: '待确认',
  1: '已同意',
  2: '已拒绝',
  3: '已请假',
  4: '已取消'
};
const extractionStatusOptions = {
  0: '取消',
  1: '确认',
  2: '重抽'
};

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'
  },
  {
    label: '数据来源',
    prop: 'isSource'
  },
  {
    label: '专家状态',
    prop: 'acceptStatus'
  },
  {
    label: '抽取状态',
    prop: 'extractionStatus'
  }
]);
// 项目列表
const projectOptions = ref<any[]>([]);
// 获取项目列表
const getProjectList = async () => {
  let res = await getProjectSelList();
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  projectOptions.value = res.rows || [];
};
// 根据项目列表id获取项目详情
const getProjectInfoData = async () => {
  let item = projectOptions.value.find((item) => item.id == projectForm.value.projectId);
  if (!item) return;
  projectForm.value = {
    projectId: projectForm.value.projectId,
    ...item,
    contact: item.unitConcat
  };
};
watch(
  () => projectForm.value.projectId,
  (newVal) => {
    if (!newVal || id.value) return;
    getProjectInfoData();
  }
);
const loading = ref(false);
const extractionStatus = ref();
const tabs = ref([]);
const activeName = ref('');
const VoList = ref([]);
const ruleLoading = ref(false);
const handleClick = async () => {
  ruleLoading.value = true;
  await proxy?.$nextTick();
  await getRuleList();
  ruleLoading.value = false;
};
const getResultList = async () => {
  let res = await getExpertList({ reviewId: activeName.value });
  resultList.value = res.data.map((e: any) => {
    let performWorkId = e.performWorkName?.replace(/\r/, '').split(',') || [];
    return {
      ...e,
      performWorkId,
      performWorkName: performWorkId.map((e: any) => performWorkObj.value[e]).join(',')
    };
  });
};
const getRuleList = async () => {
  let res = VoList.value[activeName.value];
  // 抽取配置回显
  let expertIds = res?.avoidanceExpert?.split(',').map((e: any) => e.trim()).filter(Boolean) || [];
  let expertsId = res?.designatedNumber?.split(',').map((e: any) => e.trim()).filter(Boolean) || [];
  let unit = res?.avoidanceUnit?.split(',').map((e: any) => e.trim()).filter(Boolean) || [];
  // 单位回显列表
  unitOptions.value =
    unit?.map((e: any) => {
      return {
        label: e,
        value: e
      };
    }) || [];
  form.value = {
    ...form.value,
    ...(res || {}),
    extractioRestrictio: type.value == 'reExtract' ? ['1'] : JSON.parse(res.extractioRestriction || '[]').map((e: any) => e.toString()),
    count: res.plannedIntake,
    supplementNum: res.expertSum - (res.extractedSum || 0),
    expertIds,
    unit,
    isAvoid: expertIds?.length > 0 || unit?.length > 0,
    mode: res.extractionMode,
    expertsId: type.value == 'reExtract' ? [] : expertsId,
    expertsCout: type.value == 'reExtract' ? 1 : expertsId.length,
    areaList:
      type.value == 'reExtract'
        ? [
          {
            area: DEFAULT_SAFE_AREA[0],
            num: 1
          }
        ]
        : res.area?.split(',').map((e: any) => {
        let [area, num] = e.split('=');
        return {
          area,
          num: +num
        };
      }) || [
        {
          area: DEFAULT_SAFE_AREA[0],
          num: 1
        }
      ]
  };
  options.value.push(...expertOptions.value);
  await getResultList();
};
const getInfo = async () => {
  loading.value = true;
  ruleLoading.value = true;
  let res: any = await getResult(id.value as string).catch(() => {
    loading.value = false;
    ruleLoading.value = false;
  });
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    loading.value = false;
    ruleLoading.value = false;
    return;
  }
  if (!res.data) return;
  // 项目信息回显
  projectForm.value = {
    productName: res.data.zjkProductVo.productName,
    productType: res.data.zjkProductVo.productType,
    productScale: res.data.zjkProductVo.productScale,
    productUnit: res.data.zjkProductVo.productUnit,
    unitBy: res.data.zjkProductVo.unitBy,
    contact: res.data.zjkProductVo.unitConcat,
    projectId: res.data.zjkProductVo.id
  };
  projectOptions.value = [
    {
      id: res.data.zjkProductVo.id,
      productName: res.data.zjkProductVo.productName
    }
  ];
  extractionStatus.value = res.data.extractionStatus;
  // 专家回显列表
  expertOptions.value =
    res.data.designatedNumbers?.map((e: any) => {
      let performWorkId = e.performWorkId?.replace(/\r/, '').split(',') || [];
      return {
        ...e,
        performWorkId,
        performWorkName: performWorkId.map((e: any) => performWorkObj.value[e]).join(',')
      };
    }) || [];
  tabs.value = res.data.zjkReviewPhaseVoList.map((e: any) => e.id);
  res.data.zjkReviewPhaseVoList.forEach((e: any) => {
    VoList.value[e.id] = {
      ...e,
      expertSum: res.data.expertSum,
      extractedSum: res.data.extractedSum
    };
  });
  activeName.value = tabs.value.length > 0 ? tabs.value[0] : '';
  await handleClick();
  loading.value = false;
  ruleLoading.value = false;
};

const leaveForm = ref<ElFormInstance>(null);
const leaveDialog = reactive({
  visible: false,
  activeRow: null,
  form: {
    result: ''
  },
  rules: {
    result: [{ required: true, message: '请输入请假理由', trigger: 'blur' }]
  }
});
/* 请假 */
const Leave = (row: any) => {
  leaveDialog.activeRow = row;
  leaveDialog.visible = true;
};
const Close = () => {
  leaveForm.value.resetFields();
  leaveDialog.visible = false;
};
const ConfimLeave = () => {
  leaveForm.value.validate(async (valid) => {
    if (!valid) return;
    const params = {
      expertId: leaveDialog.activeRow.expertId,
      userId: leaveDialog.activeRow.userId,
      itemId: projectForm.value.projectId,
      itemStage: form.value.reviewSn,
      reviewTime: form.value.reviewTime,
      leaveReason: leaveDialog.form.result
    };
    let res = await setLeave(params);
    if (res.code != 200) {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
      return;
    }

    ElNotification({
      title: '提示',
      message: '请假成功',
      type: 'success'
    });
    await getInfo();
    Close();
  });
};
onActivated(() => {
  if (id.value) {
    getInfo();
    getExtractAreaOptions();
  } else {
    getProjectList();
    projectFormRef.value.resetFields();
    form.value = { ...defaultForm };
    formRef.value.resetFields();
    nextTick(() => {
      form.value.areaList[0].area = DEFAULT_SAFE_AREA[0];
    });
  }
});

onMounted(() => {
  if (id.value) {
    getInfo();
    getExtractAreaOptions();
  } else {
    getProjectList();
    nextTick(() => {
      form.value.areaList[0].area = DEFAULT_SAFE_AREA[0];
    });
  }
});
</script>
<style lang="scss" scoped>
.form-item-gird {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.confirm-time {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
  span{
    color: #a8abb2;
  }
}

.model-title {
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: bold;
}

.goto-log {
  color: var(--el-color-primary);
}

.back-to-list {
  display: flex;
  align-items: center;
  gap: 10px;
  position: absolute;
  top: 10px;
  left: 10px;
  line-height: 20px;

  &:hover * {
    color: var(--el-color-primary);
  }
}

.extract-area {
  flex: 1;

  .extract-area-item {
    display: flex;
    align-items: center;
    gap: 10px;

    &:not(:first-child) {
      margin-top: 14px;
    }

    :deep(.el-form-item) {
      flex: 1;
    }

    .icon-main {
      left: calc(100% + 16px);

      :deep(.el-icon) {
        cursor: pointer;
        font-size: 32px;
      }
    }
  }
}

.form-main {
  width: 800px;
}

.look-form {
  :deep(.el-form-item__content) {
    align-items: flex-start;
  }
}

:deep(.el-tabs) {
  .el-tabs__header {
    margin: 0;

    .el-tabs__nav-wrap::after {
      height: 0 !important;
    }
  }
}
</style>
<style>
.currentDatePickerClass .el-picker-panel__footer .el-button:first-child {
  display: none;
}
</style>
