<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue';
import {
  Button,
  Card,
  Col,
  Descriptions,
  Image,
  ImagePreviewGroup,
  InputNumber,
  message,
  Modal,
  notification,
  RadioGroup,
  RadioButton,
  Row,
  Select,
  SelectOption,
  Tag,
  Textarea,
  Timeline,
  TimelineItem
} from 'ant-design-vue';
import { DeleteTwoTone, MinusOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { debounce } from 'lodash-es';

import { getRegisterStatus } from '#/util/tool';
import {
  addWestPrescription,
  checkChineseMedicineConflictApi,
  getDrugUseList,
  getMyStoreListApi,
  getPatientItem,
  getProcessRuleList,
  getProductListDoctorReception,
  switchStoreApi,
} from '#/views/doctor/doctor-reception/api';

// 定义 props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  registerId: {
    type: [Number, String],
    required: true
  }
});

// 定义 emits
const emit = defineEmits(['update:visible', 'prescriptionSent']);

// 患者数据
const patientInfo = ref<null | any>(null);
const userPatientHealthInquiry = ref<null | any>(null);
const prescriptionList = ref([]);

// 药品使用相关数据
const drugUseNum = ref([]);
const drugUseFrequency = ref([]);
const drugUseType = ref([]);
const drugUnit = ref([]);
const drugTime = ref([]);
const drugUseWay = ref([]);
const myStoreList = ref([]);

const myStoreId = ref(0);
const activeCategory = ref(2);
const diagnosis = ref('');
const medicalAdvice = ref('');
const treatmentPrice = ref(0);
const ruleType = ref(1);
const drugList = ref([]);

// 计算商品总价
const totalProductCost = computed(() => {
  if (currentDrugs.value.length === 0) {
    return 0;
  }
  // 如果是中药的时候，计算总价格
  if (activeCategory.value === 1) {
    return currentDrugs.value.reduce(
      (sum, drug) => sum + drug.price * (drug.number || 1) * dosage.value,
      0,
    );
  }
  return currentDrugs.value.reduce(
    (sum, drug) => sum + drug.price * (drug.select_number || 1),
    0,
  );
});

// 计算总价
const totalCost = computed(() => {
  return totalProductCost.value + processingFee.value;
});

const processRulePrice = ref(0);
const calcMethod = ref(0);

// 计算加工费
const processingFee = computed(() => {
  if (ruleType.value === 1) {
    return 0;
  }
  // 已选择药品为空的时候是0
  if (currentDrugs.value.length === 0) {
    return 0;
  }
  // 获取本次选择的加工规则
  childProcessRuleList.value.find((item) => {
    if (item.id === childProcessRuleId.value) {
      calcMethod.value = item.calc_method;
      processRulePrice.value = item.price;
    }
  });
  // 模式1：固定价格模式
  if (calcMethod.value === 1) {
    return processRulePrice.value;
  }
  // 模式2：单价*用量
  if (calcMethod.value === 2) {
    return processRulePrice.value * dosage.value;
  }
  // 模式3：单价*用量*数量
  if (calcMethod.value === 3) {
    const number = currentDrugs.value.reduce(
      (sum, drug) => sum + drug.number,
      0,
    );
    return processRulePrice.value * dosage.value * number;
  }
  return 0;
});

const visible = ref<boolean>(false);
const previewImage = ref([]);

// 说明书预览
const setVisible = (value, instruction = ''): void => {
  previewImage.value = [];
  if (instruction == '') {
    message.error('该产品没有说明书！');
  } else {
    if (typeof instruction === 'string') {
      // 如果有逗号，则进行分割 没有则追加到previewImage
      if (instruction.includes(',')) {
        instruction = instruction.split(',');
        previewImage.value = instruction;
      } else {
        previewImage.value.push(instruction);
      }
    }
    visible.value = value;
  }
};

// 数量增加
const increment = (index: number) => {
  currentDrugs.value[index].select_number++;
  saveToLocalStorage();
};

// 数量减少
const decrement = (index: number) => {
  if (currentDrugs.value[index].select_number > 1) {
    currentDrugs.value[index].select_number--;
    saveToLocalStorage();
  }
};

// 保存到本地存储
const saveToLocalStorage = () => {
  localStorage.setItem(
    `prescriptionData-chat-${props.registerId}`,
    JSON.stringify(currentDrugs.value),
  );
};

// 删除药品（本地）
const removeDrug = (index: number) => {
  currentDrugs.value.splice(index, 1);
  updateLocalStorage();
};

// 修改缓存的处方信息
const updateLocalStorage = () => {
  localStorage.setItem(
    `prescriptionData-chat-${props.registerId}`,
    JSON.stringify(currentDrugs.value),
  );
  getCurrentDrugs();
};

const currentDrugs = ref([]);
const selectProductId = ref(0);

// 获取缓存的处方信息
const getCurrentDrugs = () => {
  currentDrugs.value = JSON.parse(
    localStorage.getItem(`prescriptionData-chat-${props.registerId}`) || '[]',
  );
};

const doctorSecondSign = ref(0);
const checkData = ref([]);

// 检查中药的相冲
const checkChineseMedicineConflict = () => {
  if (activeCategory.value === 2) {
    sendPrescription();
    return;
  }
  notification.info({
    message: '正在检查药物相冲',
    duration: 1,
    description: '正在检查药物相冲，请稍等...',
  });
  const names = currentDrugs.value.map((item) => item.drug_name);
  checkChineseMedicineConflictApi({names: names}).then((res) => {
    if (res.is_exist === true) {
      checkData.value.message = res.message;
      doctorSecondSignModal.value = true;
    } else {
      notification.success({
        message: '检查成功',
        duration: 3,
        description: '暂无相冲药品',
      });
      sendPrescription();
    }
  });
  return;
};

// 发送处方
const sendPrescription = () => {
  if (currentDrugs.value.length === 0) {
    message.error('请选择药品');
    return;
  }
  if (activeCategory.value === 1) {
    if (ruleType.value === 1) {
      if (packageMethodId.value == null) {
        message.error('请选择包法');
        return;
      }
    } else {
      if (processRuleId.value == null) {
        message.error('请选择制剂');
        return;
      }
      if (processRuleNoteId.value == null) {
        message.error('请选择规格');
        return;
      }
      if (childProcessRuleId.value == null) {
        message.error('请选择备注');
      }
    }
  }
  if (diagnosis.value === '') {
    message.error('诊断结果不能为空');
    return;
  }
  if (medicalAdvice.value === '') {
    message.error('医嘱不能为空');
    return;
  }

  // 发送处方逻辑
  addWestPrescription({
    // 当前活动患者的个人信息
    patient: patientInfo.value,
    // 当前处方中的药品列表
    drugs: currentDrugs.value,
    // 诊断信息
    diagnosis: diagnosis.value,
    // 医嘱信息
    medicalAdvice: medicalAdvice.value,
    // 总费用
    total: totalCost.value,
    // 费用类别
    category: category.value,
    // 药品类型
    drug_type: 2, // 默认为处方类型
    // 从props获取的挂号ID
    register_id: props.registerId,
    // 治疗费用
    treatment_price: treatmentPrice.value,
    // 包装方式ID
    package_method_id: packageMethodId.value,
    // 加工规则ID
    process_rule_id: processRuleId.value,
    // 加工规则备注ID
    process_rule_note_id: processRuleNoteId.value,
    // 子加工规则ID
    child_process_rule_id: childProcessRuleId.value,
    // 加工规则类型
    process_rule_type: ruleType.value,
    // 处方类型
    prescription_type: activeCategory.value,
    // 加工费
    processing_fee: processRulePrice.value,
    // 用药剂量
    dosage: dosage.value,
    // 每日用药次数
    day_dosage: dayDosage.value,
    // 是否二次签名
    doctor_second_sign: doctorSecondSign.value,
  }).then(() => {
    message.success('处方已发送');
    // 清空当前数据
    currentDrugs.value = [];
    diagnosis.value = '';
    medicalAdvice.value = '';
    packageMethodId.value = 2;
    processRulePrice.value = 0;
    dosage.value = 7;
    dayDosage.value = 2;
    newDrugInfo.value = {};
    updateLocalStorage();
    emit('prescriptionSent');
  });
};

// 药品分类
const categories = [
  {label: '中药', value: 1},
  {label: '中成(西)药', value: 2},
];

const category = ref(1);

// 基础配置
const processRuleList = ref([]);
// 子配置
const childProcessRuleList = ref([]);
// 规格
const processRuleNoteList = ref([]);
const processRuleId = ref();
const processRuleNoteId = ref();
const childProcessRuleId = ref();

function getProcessRuleListByDoctor(pid = 0, ruleId = 0) {
  let data = {};
  data =
    ruleId === 0
      ? {
        pid,
      }
      : {
        rule_id: ruleId,
      };
  getProcessRuleList(data).then((value) => {
    if (ruleId !== 0) {
      processRuleNoteList.value = value;
    } else if (pid === 0) {
      processRuleList.value = value;
    } else {
      childProcessRuleList.value = value;
    }
  });
}

// 选择煎法
function selectProcessRule(id) {
  processRuleId.value = id;
  getProcessRuleListByDoctor(id);
}

// 选择规格
function selectProcessRuleNot(id) {
  childProcessRuleId.value = id;
  getProcessRuleListByDoctor(0, id);
}

// 选择备注
function selectProcessRuleNotCommit(id) {
  processRuleNoteId.value = id;
}

const packageMethodId = ref(2);
const packageMethod = [
  {label: '味包', value: 1},
  {label: '剂包', value: 2},
];

function selectPackageMethod(id) {
  packageMethodId.value = id;
}

// 剂量
const dosage = ref(7);
const dayDosage = ref(2);

function updateChineseNumber() {
  updateLocalStorage();
}

// 新药品确认弹窗
const showNewDrugModal = ref(false);
// 二次签名确认弹窗
const doctorSecondSignModal = ref(false);

// 在新的药品数量框失去焦点后弹出新药品弹窗
function newDrugBlur() {
  if (newDrugInfo.value.id > 0 && newDrugInfo.value.number > 0) {
    showNewDrugModal.value = true;
  }
}

function newDrugModalOk() {
  addDrugByChinese();
  showNewDrugModal.value = false;
}

function doctorSecondSignModalOk() {
  doctorSecondSign.value = 1;
  doctorSecondSignModal.value = false;
  sendPrescription();
}

function updateChineseNumberGoNewDrug(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    updateLocalStorage();
    setTimeout(() => {
      // 获取新药品卡片中的克数输入框并聚焦
      const newDrugNumberInput = document.querySelector(
        '.new-select-drug-name input',
      );
      if (newDrugNumberInput) {
        (newDrugNumberInput as HTMLElement).focus();
      }
    }, 100);
  }
}

// 获取药品列表
const getDrugListByWesternModal = debounce(async (searchText = '') => {
  if (searchText === '' && activeCategory.value === 1) {
    drugList.value = [];
    return;
  }

  getCurrentDrugs();

  try {
    const res = await getProductListDoctorReception({
      store_id: myStoreId.value,
      type: activeCategory.value,
      name: searchText,
    });

    drugList.value = res.map((item) => {
      const matched = currentDrugs.value.find((v) => v.index_id === item.id);
      return {
        ...item,
        select_number: matched?.select_number || 0,
        drug: {
          ...item.drug,
          number: matched?.number || 1,
        },
      };
    });
  } catch (error) {
    console.error('获取药品列表失败:', error);
    message.error('获取药品列表失败');
  }
}, 300);

// 选择药品
function selectNewDrugInfo() {
  // 如果是新药品输入框，调用添加新药品方法
  const check = currentDrugs.value.find((v) => v.id === newDrugInfo.value.id);
  if (check) {
    newDrugInfo.value.id = '';
    message.error('该药品已经在处方中了！');
    return;
  }

  const data = drugList.value.find((v) => v.drug_id === newDrugInfo.value.id);
  newDrugInfo.value.price = data.price;
  newDrugInfo.value.name = data.drug.drug_name;
  setTimeout(() => {
    // 获取新药品卡片中的克数输入框并聚焦
    const newDrugNumberInput = document.querySelector(
      '.new-number-input input',
    );
    if (newDrugNumberInput) {
      (newDrugNumberInput as HTMLElement).focus();
    }
  }, 100);
}

const selectChineseIndex = ref(-1);
const selectChineseId = ref(0);

// 选择药品
function selectOldDrugInfo(id) {
  const check = JSON.parse(
    localStorage.getItem(`prescriptionData-chat-${props.registerId}`) || '[]',
  ).find((v) => v.id === id);
  if (check) {
    currentDrugs.value[selectChineseIndex.value].id = selectChineseId.value;
    drugList.value = [];
    message.error('该药品已经在处方中了！');
    return;
  }
  const oldDrugInfo = currentDrugs.value[selectChineseIndex.value];
  // 如果是新药品输入框，调用添加新药品方法
  const data = drugList.value.find((v) => v.drug_id === id);

  // 创建新的商品对象（避免直接修改原始数据）
  const newProduct = {
    // 索引ID（用于在列表中查找）
    index_id: data.id,
    // 药品ID
    id: data.drug.id,
    // 药品名称
    drug_name: data.drug.drug_name,
    // 药品数量
    number: data.drug.number,
    // 药品使用数量信息
    use_num: drugTime.value.find((item) => item.id === data.drug.time_id),
    // 药品使用类型信息
    use_type: drugUseType.value.find((item) => item.id === data.drug.type_id),
    // 药品使用频率信息
    use_frequency: drugUseFrequency.value.find(
      (item) => item.id === data.drug.frequency_id,
    ),
    // 药品单位信息
    unit: drugUnit.value.find((item) => item.id === data.drug.unit_id),
    // 药品价格
    price: data.price,
    // 药品使用方式ID
    way_id: data.drug?.way_id,
    // 药品使用方式信息
    use_ways: drugUseWay.value.find((item) => item.id === data.drug.way_id),
    // 药品使用时间ID
    time_id: data.drug.time_id,
    // 药品类型ID
    type_id: data.drug.type_id,
    // 药品使用频率ID
    frequency_id: data.drug.frequency_id,
    // 药品单位ID
    unit_id: data.drug.unit_id,
    // 药品图片
    image: data.drug.image,
    // 药品说明书
    instruction: data.drug.instruction,
    // 药品类型
    type: data.drug.type,
  };
  currentDrugs.value[selectChineseIndex.value] = newProduct;
  updateLocalStorage();
  setTimeout(() => {
    // 获取新药品卡片中的克数输入框并聚焦
    const newDrugNumberInput = document.querySelector(
      `.old-number-input-${selectChineseIndex.value} input`,
    );
    if (newDrugNumberInput) {
      (newDrugNumberInput as HTMLElement).focus();
    }
  }, 100);
}

// 写入当前修改的下标
function setSelectChineseIndex(index, id) {
  selectChineseIndex.value = index;
  selectChineseId.value = id;
}

// 查询中药列表
function searchOption(inputValue) {
  getDrugListByWesternModal(inputValue);
}

// 添加中药
function addDrugByChinese() {
  // 如果是新药品输入框，调用添加新药品方法
  const check = currentDrugs.value.find(
    (v) => v.id === newDrugInfo.value.id,
  );
  if (check) {
    message.error('该药品已经在处方中了！');
    return;
  }
  const data = drugList.value.find(
    (v) => v.drug_id === newDrugInfo.value.id,
  );
  if (data === null || data === undefined) {
    message.error('请选择药品');
    return;
  }
  data.drug.number = newDrugInfo.value.number;
  data.drug.way_id = newDrugInfo.value.way_id;
  addProducts(data);
  newDrugInfo.value = {};
}

// 添加操作
function selectDrugByNewDrugInfo(event: KeyboardEvent, isNewDrug: boolean) {
  // 如果按下的是回车键
  if (event.key === 'Enter') {
    // 阻止默认行为（防止表单提交）
    event.preventDefault();

    if (isNewDrug) {
      // 如果是新药品输入框，调用添加新药品方法
      addDrugByChinese();
    } else {
      // 如果是已有药品输入框，调用更新数量方法
      updateChineseNumber();
    }
    setTimeout(() => {
      // 获取新药品卡片中的克数输入框并聚焦
      const newDrugNumberInput = document.querySelector(
        '.new-select-drug-name input',
      );
      if (newDrugNumberInput) {
        (newDrugNumberInput as HTMLElement).focus();
      }
    }, 100);
  }
}

// 添加商品到处方
function addProducts(data) {
  // 查找是否已存在于选择列表中
  const existItem = currentDrugs.value.find(
    (item) => item.index_id === data.id,
  );

  if (existItem) {
    message.warn('已经存在了');
    return;
  }
  // 创建新的商品对象（避免直接修改原始数据）
  const newProduct = {
    // 索引ID（用于在列表中查找）
    index_id: data.id,
    // 药品ID
    id: data.drug.id,
    // 药品名称
    drug_name: data.drug.drug_name,
    // 药品数量
    number: data.drug.number,
    // 药品使用数量信息
    use_num: drugTime.value.find((item) => item.id === data.drug.time_id),
    // 药品使用类型信息
    use_type: drugUseType.value.find((item) => item.id === data.drug.type_id),
    // 药品使用频率信息
    use_frequency: drugUseFrequency.value.find(
      (item) => item.id === data.drug.frequency_id,
    ),
    // 药品单位信息
    unit: drugUnit.value.find((item) => item.id === data.drug.unit_id),
    // 药品价格
    price: data.price,
    // 药品使用方式ID
    way_id: data.drug?.way_id,
    // 药品使用方式信息
    use_ways: drugUseWay.value.find((item) => item.id === data.drug.way_id),
    // 药品使用时间ID
    time_id: data.drug.time_id,
    // 药品类型ID
    type_id: data.drug.type_id,
    // 药品使用频率ID
    frequency_id: data.drug.frequency_id,
    // 药品单位ID
    unit_id: data.drug.unit_id,
    // 药品图片
    image: data.drug.image,
    // 药品说明书
    instruction: data.drug.instruction,
    // 药品类型
    type: data.drug.type,
  };

  // 首次添加，初始化数量为1
  newProduct.select_number = 1;

  // 添加到选中列表
  currentDrugs.value.push(newProduct);

  // 更新本地存储
  updateLocalStorage();

  // 提示成功
  message.success(`已将${newProduct.drug_name}添加到清单中！`);
}

const newDrugInfo = ref({});

function selectProductChange(id) {
  selectProductId.value = id;
}

// 选择中药用法
function selectDrugUseWayChange(id) {
  currentDrugs.value = currentDrugs.value.map((item) =>
    // 修改item下面drug的 frequency_id = id
    item.index_id === selectProductId.value
      ? {
        ...item,
        way_id: id,
        use_ways: drugUseWay.value.find((value) => value.id === id),
      }
      : item,
  );
  updateLocalStorage();
}

// 切换tab
function tabChange(id) {
  localStorage.setItem(`activeCategory-chat-${props.registerId}`, id);
  currentDrugs.value = [];
  updateLocalStorage();
  activeCategory.value = id;
}

// 根据创制string来把字符串的逗号分开变成数组
function splitString(str: string) {
  if (!str) {
    return [];
  }
  return str.split(',');
}

// 获取我的诊所列表
function getMyStoreList() {
  getMyStoreListApi().then((res) => {
    myStoreList.value = res;
    if (res.length > 0) {
      myStoreId.value = res[0].id;
    }
  });
}

// 获取药品使用方式列表
function getDrugUseListByWesternModal() {
  getDrugUseList().then((res) => {
    // 更新各种药品使用相关数据
    drugUseNum.value = res.drug_use_num;
    drugUseFrequency.value = res.drug_use_frequency;
    drugUseType.value = res.drug_use_type;
    drugUnit.value = res.drug_unit;
    drugTime.value = res.drug_time;
    drugUseWay.value = res.drug_use_way;
  });
}

// 获取患者信息
async function getPatientInfo() {
  try {
    const res = await getPatientItem(props.registerId);
    patientInfo.value = res;
    userPatientHealthInquiry.value = res.user_patient_health_inquiry;
    prescriptionList.value = res.prescription;
  } catch (error) {
    console.error('获取患者信息失败:', error);
  }
}

// 监听 visible prop 变化
watch(() => props.visible, (newVal) => {
  visible.value = newVal;
});

onMounted(() => {
  getMyStoreList();
  getDrugUseListByWesternModal();
  getProcessRuleListByDoctor();
  getPatientInfo();
  getCurrentDrugs();
});
</script>

<template>
  <Modal
    :open="visible"
    :width="1200"
    title="开方模块"
    @cancel="emit('update:visible', false)"
    @ok="sendPrescription"
  >
  </Modal>
</template>

<style scoped>
</style>