import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { getHlwConfigGroup } from '@/api/hlw'
import { ElMessage } from "element-plus";


/**
 * @description 药品相关配置说明
 * @switch key
 * @case online-medicine-purchase-unit 线上购药-药品用药单位
 * @case online-medicine-purchase-frequency 线上购药-药品用药频次
 * @case online-medicine-purchase-administration 线上购药-药品用药途径
 * @case online-consult-administration 在线咨询-药品用药途径（震元线上咨询在线下门店购药使用）
 * @case online-consult-frequence 在线咨询-药品用药频次（震元线上咨询在线下门店购药使用）
 * @case online-consult-unit 在线咨询-药品 包装单位（震元线上咨询在线下门店购药使用）
 */

export default defineStore("medicineConfigStore", () => {
  const corpId = import.meta.env.VITE_CORP_ID;
  const medicineConfigGroup = ref({});

  //线上购药 单次剂量单位 用药频次 用药途径 包装单位
  const onlineMedicine = computed(() => ({
    dosageUnitList: medicineConfigGroup.value['online-medicine-dosage-unit'] || [],
    frequencyList: medicineConfigGroup.value['online-medicine-frequence'] || [],
    usageList: medicineConfigGroup.value['online-medicine-administration'] || [],
    unitList: medicineConfigGroup.value['medicine-package-unit'] || [],
  }))

  //门店药品 单次剂量单位 用药频次 用药途径 包装单位
  const storeMedicine = computed(() => ({
    dosageUnitList: medicineConfigGroup.value['store-medicine-dosage-unit'] || [],
    frequencyList: medicineConfigGroup.value['store-medicine-frequence'] || [],
    usageList: medicineConfigGroup.value['store-medicine-administration'] || [],
    unitList: medicineConfigGroup.value['medicine-package-unit'] || [],
  }))


  async function getMedicineConfigGroup() {
    const group = `${corpId}-medicine-related`;
    const res = await getHlwConfigGroup(group);
    if (res && res.success && res.data && Array.isArray(res.data.data)) {
      res.data.data.forEach(item => {
        if (item.key && Array.isArray(item.list)) {
          medicineConfigGroup.value[item.key] = item.list;
        }
      })
    }
  }

  async function attachMedicineConfig() {
    try {
      if (Object.keys(medicineConfigGroup.value).length) return;
      for (let i = 1; i <= 5; i++) {
        await getMedicineConfigGroup();
        if (Object.keys(medicineConfigGroup.value).length) return;
        await new Promise(resolve => setTimeout(resolve, 500 + i * 200));
      }
    } catch (e) {
      console.log(e)
    }
    ElMessage.info('药品相关配置获取失败，请稍后再试！')
  }



  return {
    onlineMedicine,
    storeMedicine,
    attachMedicineConfig,
  }
});