import { useEffect, useState } from '@tarojs/taro';
import { fetchBeanCount } from '@/api/bean';
import { CustomerBeanAccountVo } from '@/api/baseClass';
import { Service } from '@/api/home';
import { Customer } from '@/types/Customer/Customer';

export enum BeanType {
  aimi = 'aimi',
  common = 'common',
  shower = 'shower',
  hairDryer = 'hairDryer',
  water = 'water',
}
type BeanAccount = {
  money: number;
  serviceId: string;
};

let initBeanList: BeanAccount[] = [];

const useAllBeanCount = (
  userinfo: Customer,
  serviceList: Service[],
): [
  BeanAccount[],
  (
    customerId: number,
    areaId: number,
    customerPhone: string,
  ) => Promise<CustomerBeanAccountVo[]>
] => {
  const [filterBeanList, setFilterBeanList] = useState(initBeanList);

  const getFilterBeanList = (
    beanAccount: CustomerBeanAccountVo[],
  ): BeanAccount[] => {
    let aimiItem = beanAccount.find(item => item.serviceId === '0');
    let cfItem = beanAccount.find(
      item => item.serviceId === '4' || item.serviceId === '12',
    );
    let xyItem = beanAccount.find(
      item => item.serviceId === '5' || item.serviceId === '10',
    );
    let ysItem = beanAccount.find(
      item =>
        item.serviceId === '3' ||
        item.serviceId === '11' ||
        item.serviceId === '9',
    );
    let commonItem = beanAccount.find(item => item.serviceId === '0');
    let beanMap = {
      [BeanType.aimi]: aimiItem ? aimiItem.money : 0,
      [BeanType.common]: commonItem ? commonItem.money : 0,
    };
    for (let index = 0; index < serviceList.length; index++) {
      const service = serviceList[index];
      if (
        service.serviceId === 3 ||
        service.serviceId === 11 ||
        service.serviceId === 9
      ) {
        beanMap[BeanType.water] = ysItem ? ysItem.money : 0;
      } else if (service.serviceId === 4 || service.serviceId === 12) {
        beanMap[BeanType.hairDryer] = cfItem ? cfItem.money : 0;
      } else if (service.serviceId === 5 || service.serviceId === 10) {
        beanMap[BeanType.shower] = xyItem ? xyItem.money : 0;
      }
    }
    let arr: BeanAccount[] = Object.keys(beanMap).map(k => ({
      serviceId: k,
      money: beanMap[k],
    }));
    return arr;
  };

  const fetchDate = (
    customerId: number,
    areaId: number,
    customerPhone: string,
  ) =>
    fetchBeanCount({
      id: customerId,
      areaId: areaId,
      customerPhone: customerPhone,
      serviceIdList: [],
    })
      .then(res => {
        const data = res.data;
        let list = getFilterBeanList(data);
        setFilterBeanList(list);
        return data;
      })
      .catch(err => {
        console.log(err);
        throw err;
      });

  useEffect(() => {
    fetchDate(userinfo.customerId, userinfo.areaId, userinfo.customerPhone);
  }, [userinfo.customerId, userinfo.areaId, userinfo.customerPhone]);

  return [filterBeanList, fetchDate];
};

export default useAllBeanCount;
