import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { getMedicalWineList } from '@/api/hlw';

export default function useWine() {
  const wines = ref([]);

  function changeWine({ quantity, index }) {
    wines.value[index].quantity = quantity;
  }

  function checkWines() {
    if (wines.value.length === 0) {
      return '请添加中药饮片';
    }
    const unAvailableWines = wines.value.find(item => !(item._id && typeof item.quantity === 'number' && item.quantity >= 1 && Number.isInteger(item.quantity)));
    if (unAvailableWines) {
      return `中药饮片【${unAvailableWines.name}】中药数量无效`
    }
    return ''
  }

  async function initWines(d) {
    const data = Array.isArray(d) ? d : [];
    wines.value = await getWines(data);
  }

  async function getWines(data) {
    const ids = Array.isArray(data) ? data.map(i => i.id) : [];
    if (ids.length === 0) {
      return []
    }
    const res = await getMedicalWineList({ ids })
    const wineData = res && res.data && Array.isArray(res.data.data) ? res.data.data : [];
    const wrongDatas = [];
    const list = []
    data.forEach(i => {
      const wine = wineData.find(w => i && i.id && w._id === i.id);
      if (wine) {
        const quantity = Number(i.quantity) && Number(i.quantity) >= 1 && Number.isInteger(Number(i.quantity)) ? Number(i.quantity) : 1;
        list.push({ ...wine, quantity })
      } else if (i && i.name) {
        wrongDatas.push(`【${i.name}】`);
      }
    })
    if (wrongDatas.length > 0) {
      ElMessage.error(`未查询到浸酒${wrongDatas.join('、')}信息`);
    }
    return list
  }

  return { checkWines, changeWine, initWines, wines }
}