import http from "@/plugins/http";
import config from "@/app.config";

import { useCounterMixin } from "@/stores/mixin";
import { useEvaluateStore } from "@/modules/06_evaluate/store";

const store = useEvaluateStore();
const mixin = useCounterMixin();

const { showLoader, hideLoader } = mixin;

/** function เช็คการยื่นข้อประเมิน*/
async function fetchCheckStatus() {
  store.showLoadStatus = false;
  //  = 1;
  showLoader();
  await http
    .get(config.API.evaluationCheckStatus())
    .then((res) => {
      const data = res.data.result;
      store.tabMenu === "1"
        ? (store.evaluateId = data.expertId)
        : (store.evaluateId = data.specialExpertId);
      fetchCheckStep(store?.evaluateId);
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function fetchCheckStep(id: string) {
  if (id) {
    await http
      .get(config.API.evaluationCheckStep(id))
      .then((res) => {
        const data = res.data.result;

        let step =
          data.step === "CHECK_SPEC"
            ? 1
            : data.step === "PREPARE_DOC_V1"
            ? 2
            : data.step === "CHECK_DOC_V1"
            ? 3
            : data.step === "WAIT_CHECK_DOC_V1"
            ? 4
            : data.step === "ANNOUNCE_WEB"
            ? 5
            : data.step === "PREPARE_DOC_V2"
            ? 6
            : data.step === "WAIT_CHECK_DOC_V2"
            ? 7
            : data.step === "CHECK_DOC_V2"
            ? 8
            : data.step === "DONE"
            ? 9
            : 1;

        store.currentStep = step;
        store.step = step;
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        store.showLoadStatus = true;
      });
  } else
    ((store.step = 1), (store.currentStep = 1)), (store.showLoadStatus = true);
}

async function saveEvaluation(formSpec: any, detail: any) {
  const salaries = detail.salaries.map((e: any) => ({
    amount: e.amount,
    date: e.date,
    mouthSalaryAmount: e.mouthSalaryAmount ? e.mouthSalaryAmount : 0,
    posNo: e.posNo,
    position: e.position,
    positionSalaryAmount: e.positionSalaryAmount ? e.positionSalaryAmount : 0,
    refCommandDate: e.refCommandDate,
    refCommandNo: e.refCommandNo ? e.refCommandNo : "",
    salaryClass: e.salaryClass ? e.salaryClass : "",
    salaryRef: e.salaryRef ? e.salaryRef : "",
    salaryStatus: e.salaryStatus ? e.salariesStatus : "",
  }));

  const educations = detail.educations.map((e: any) => ({
    country: e.country,
    degree: e.degree,
    duration: e.duration,
    durationYear: e.durationYear.toString(),
    educationLevel: e.educationLevel,
    endDate: e.endDate,
    field: e.field,
    finishDate: e.finishDate,
    fundName: e.fundName,
    gpa: e.gpa,
    institute: e.institute,
    isDate: e.isDate,
    isEducation: e.isEducation,
    other: e.other,
    startDate: e.startDate,
  }));

  const form = {
    userId: detail.id,
    citizenId: detail.citizenId,
    prefix: detail.prefix,
    fullName: `${detail.firstName}   ${detail.lastName}.`,
    position: detail.position,
    oc: detail.oc,
    salary: detail.salary.toString(),
    positionLevel: detail.positionLevel,
    posNo: detail.posNo,
    birthDate: detail.birthDate,
    govAge: detail.govAge,
    type: store.tabMenu === "1" ? "EXPERT" : "SPECIAL_EXPERT",
    step: "PREPARE_DOC_V1",
    isEducationalQft: formSpec.isEducationalQft,
    isGovermantServiceHtr: formSpec.isGovermantServiceHtr,
    isOperatingExp: formSpec.isOperatingExp,
    isMinPeriodOfTenure: formSpec.isMinPeriodOfTenure,
    isHaveSpecificQft: formSpec.isHaveSpecificQft,
    isHaveProLicense: formSpec.isHaveProLicense,
    isHaveMinPeriodOrHoldPos: formSpec.isHaveMinPeriodOrHoldPos,
    reason: "",
    educations: [...educations],
    certificates: [...detail.certificates],
    salaries: [...salaries],
    trainings: [...detail.trainings],
    assessments: [...detail.assessments],
  };

  showLoader();
  await http
    .post(config.API.evaluationCheckspec(), form)
    .then((res) => {
      fetchCheckStatus();
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      fetchCheckStep(store?.evaluateId);
      hideLoader();
    });
}

async function nextPrapare(type: string, body: any) {
  showLoader();
  await http
    .put(config.API.evaluationPreparedoc(store.evaluateId, type), body)
    .then((res) => {})
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      hideLoader();
      fetchCheckStatus();
    });
}

async function nextCheckDoc(type: string) {
  showLoader();
  await http
    .put(config.API.evaluationCheckdoc(store.evaluateId, type))
    .then((res) => {})
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      hideLoader();
      fetchCheckStep(store?.evaluateId);
    });
}

// async function nextCheckDoc2(data: any) {
//   const body = {
//     commanderAboveFullnameDoc2: data.commanderAboveFullname,
//     commanderAbovePositionDoc2: data.commanderAbovePosition,
//     commanderFullnameDoc2: data.commanderFullname,
//     commanderPositionDoc2: data.commanderPosition,
//   };
//   showLoader();
//   await http
//     .put(config.API.evaluationCheckdocV1(store.evaluateId), body)
//     .then((res) => {})
//     .catch((err) => {})
//     .finally(() => {
//       hideLoader();
//       fetchCheckStatus();
//     });
// }

async function nextPrepareDoc2() {
  showLoader();
  await http
    .put(config.API.evaluationPreparedocV2(store.evaluateId))
    .then((res) => {})
    .catch((err) => {})
    .finally(() => {
      hideLoader();
      fetchCheckStatus();
    });
}

export default {
  fetchCheckStatus,
  saveEvaluation,
  nextPrapare,
  nextCheckDoc,
  // nextCheckDoc2,
  nextPrepareDoc2,
};
