import { ComponentClass } from 'react';
import Taro, { Component } from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components';

import UserBoxBg from '../../images/home/img_bg@2x.png';
import ArrowIcon from '../../images/home/icon_dingdan@2x.png';
import AnnouncementBg from '../../images/home/img_gonggao_bg@2x.png';
import MoreIcon from '../../images/home/icon_more_right@2x.png';
import SettingIcon from '../../images/home/icon_shezhi@2x.png';
import AimiIcon from '../../images/home/ic_aimi@2x.png';
import HBeanIcon from '../../images/home/icon_chuifengdou@2x.png';
import WBeanIcon from '../../images/home/ic_yinshui@2x.png';
import SBeanIcon from '../../images/home/ic_xiyu@2x.png';
import UserHeaderM from '../../images/home/img_boy_touxiang@2x.png';
import UserHeaderF from '../../images/home/img_girl_touxiang@2x.png';
import WaterIconNormal from '../../images/menu/ic_zizhu@2x.png';
import WaterIconBlock from '../../images/menu/ic_zizhu-2@2x.png';
import WaterIconBig from '../../images/menu/ic_zizhu-3@2x.png';
import ShowerIconNormal from '../../images/menu/ic_linyu@2x.png';
import ShowerIconBlock from '../../images/menu/ic_zizhu-1@2x.png';
import ShowerIconBig from '../../images/menu/ic_linyu-2@2x.png';
import DryerIconNormal from '../../images/menu/ic_chuifeng@2x.png';
import DryerIconBlock from '../../images/menu/ic_chuifeng-1@2x.png';
import DryerIconBig from '../../images/menu/ic_chuifeng-2@2x.png';
import DispenserIconNormal from '../../images/menu/ic_bigua@2x.png';
import DispenserIconBlock from '../../images/menu/ic_bigua-1@2x.png';
import DispenserIconBig from '../../images/menu/ic_bigua-2@2x.png';

import './Home.scss';
import { connect } from '@tarojs/redux';
import {
  UserState,
  updateUserInfo,
  INITIAL_STATE as userINitState,
} from '../../store/rootReducers/userinfo';
import { fetchBeanCount } from '../../api/bean';
import { fetchAnn, SectionItem } from '../../api/announcement';
import { appLogout } from '../../api/customer';
import { Customer } from '@/types/Customer/Customer';
import { shareHandle } from '@/common/shareMethod';
import { fetchAreaService, ServiceTypeParams, Service } from '@/api/home';
import MenuIconNormal from '@/components/MenuIcon/normal/MenuIconNormal';
import MenuIconBlock from '@/components/MenuIcon/block/MenuIconBlock';
import MenuIconBig from '@/components/MenuIcon/big/MenuIconBig';

enum BeanType {
  aimi = 'aimi',
  shower = 'shower',
  hairDryer = 'hairDryer',
  water = 'water',
}

type PageStateProps = {
  userinfo: Customer;
};
type PageDispatchProps = {
  updateUserInfo: (e: UserState) => void;
};

type BeanAccount = {
  money: number;
  serviceId: string;
};

type PageState = {
  barMenuVisiable: boolean;
  beanAccount: BeanAccount[];
  annItem: SectionItem;
  serviceList: Service[];
  filterBeanList: BeanAccount[];
};
type IProps = PageStateProps & PageDispatchProps;

interface Home {
  props: IProps;
  state: PageState;
}
@connect(
  ({ userinfo }) => ({
    userinfo,
  }),
  dispatch => ({
    updateUserInfo(entity: UserState) {
      dispatch(updateUserInfo(entity));
    },
  }),
)
class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      barMenuVisiable: false,
      beanAccount: [],
      serviceList: [],
      filterBeanList: [],
      annItem: {
        id: 0,
        styleType: '',
        name: '',
        titleTypeRemark: '',
        titleType: '',
        titleContent: '',
        sort: 0,
        updateTime: 0,
        itemsCount: 0,
        items: [],
      },
    };
  }

  onShareAppMessage = shareHandle;

  componentWillMount() {
    this.getInitData();
  }

  componentDidShow() {
    this.getInitData();
  }
  getInitData() {
    this.getBeanCountData();
    this.getServiceList();
    this.getAnn();
  }

  getServiceList() {
    const { userinfo } = this.props;
    if (userinfo.areaId) {
      fetchAreaService({
        areaId: userinfo.areaId,
        type: ServiceTypeParams.wechatAppV,
      }).then(res => {
        console.log(res);
        this.setState(
          {
            serviceList: res.data,
          },
          () => {
            const { beanAccount } = this.state;
            if (beanAccount && beanAccount.length) {
              this.getFilterBeanList();
            }
          },
        );
      });
    }
  }

  getBeanCountData() {
    const { userinfo } = this.props;
    fetchBeanCount({
      id: userinfo.customerId,
      areaId: userinfo.areaId,
      customerPhone: userinfo.customerPhone,
      serviceIdList: [],
    })
      .then(res => {
        const data = res.data;
        this.setState(
          {
            beanAccount: data,
          },
          () => {
            const { serviceList } = this.state;
            if (serviceList && serviceList.length) {
              this.getFilterBeanList();
            }
          },
        );
      })
      .catch(console.error);
  }

  getAnn() {
    const { userinfo } = this.props;
    fetchAnn({
      campusId: userinfo.areaId,
      customerId: userinfo.customerId,
    })
      .then(res => {
        if (res) {
          this.setState({
            annItem: res,
          });
        }
      })
      .catch(err => {
        console.error(err);
      });
  }

  getFilterBeanList() {
    const { beanAccount, serviceList } = this.state;
    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 beanMap = {
      [BeanType.aimi]: aimiItem ? aimiItem.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],
    }));
    this.setState({
      filterBeanList: arr,
    });
  }

  goSetting() {
    Taro.navigateTo({
      url: '/pages/UserSetting/UserSetting',
    });
  }
  goFeedback() {
    this.toggleBarMenu();
    Taro.navigateTo({
      url: '/pages/Feedback/Feedback',
    });
  }
  goAnn(id: number) {
    Taro.navigateTo({
      url: '/pages/Announcement/Announcement?sectionId=' + id,
    });
  }

  goOrder() {
    Taro.navigateTo({
      url: '/pages/Order/OrderList/OrderList',
    });
  }

  goBarCode(serviceId: number) {
    Taro.navigateTo({
      url: `/pages/BarCode/BarCode?serviceId=${serviceId}`,
    });
  }

  goShower() {
    Taro.navigateTo({
      url: '/pages/Shower/Shower',
    });
  }

  goDispenser() {
    Taro.navigateTo({
      url: '/pages/WaterDispenser/WaterDispenser',
    });
  }

  toggleBarMenu() {
    this.setState(({ barMenuVisiable }: PageState) => ({
      barMenuVisiable: !barMenuVisiable,
    }));
  }
  logoutHandle() {
    const { updateUserInfo } = this.props;
    appLogout()
      .then(() => {
        updateUserInfo(userINitState);
        Taro.redirectTo({
          url: '/pages/index/index',
        });
      })
      .catch(console.log);
  }
  formatePhone = (phone: string) => {
    let newPhone = phone.replace(/([0-9]{3})([0-9]{4})([0-9]{4})/, '$1****$3');
    return newPhone;
  };
  geAnnDetail(id: number) {
    console.log(id);
    Taro.navigateTo({
      url: `/pages/Content/Content?id=${id}`,
    });
  }

  render() {
    const { userinfo } = this.props;
    const {
      annItem,
      barMenuVisiable,
      serviceList,
      filterBeanList,
    } = this.state;
    return (
      <View className='Home'>
        {barMenuVisiable ? (
          <View>
            <View className='mask' onClick={this.toggleBarMenu} />
            <View className='Home-BarMenu'>
              <View className='Home-BarMenu-Content'>
                <View onClick={this.goFeedback}>意见反馈</View>
                <View onClick={this.logoutHandle}>切换账号</View>
              </View>
            </View>
          </View>
        ) : null}
        <View className='Home-UserBox'>
          <Image
            className='Home-UserBox-Setting'
            src={SettingIcon}
            onClick={this.toggleBarMenu}
          />
          <Image
            className={`bg ${serviceList.length >= 2 ? 'big' : ''}`}
            src={UserBoxBg}
          />
          <View className='Home-UserBox-info'>
            <View className='Home-UserBox-other'>
              <View className='Home-UserBox-name'>{userinfo.customerName}</View>
              <View className='Home-UserBox-tel'>
                {this.formatePhone(userinfo.customerPhone)}
              </View>
              <View className='Home-UserBox-addr'>{userinfo.areaName}</View>
            </View>
            {userinfo.customerSex === '2' ? (
              <Image
                className='Home-UserBox-headimg'
                src={UserHeaderF}
                onClick={this.goSetting}
              />
            ) : (
              <Image
                className='Home-UserBox-headimg'
                src={UserHeaderM}
                onClick={this.goSetting}
              />
            )}
          </View>
          <View className='Home-UserBox-line' />
          <View className='Home-UserBox-Bean'>
            {filterBeanList &&
              filterBeanList.length &&
              filterBeanList.map(beanItem =>
                beanItem.serviceId === BeanType.aimi ? (
                  <View className='Home-UserBox-BeanItem'>
                    <Image className='Home-UserBox-BeanIcon' src={AimiIcon} />
                    <Text>艾米豆：</Text>
                    <Text className='Home-UserBox-BeanCount'>
                      {beanItem.money ? beanItem.money.toFixed(2) : '0.00'}
                    </Text>
                  </View>
                ) : beanItem.serviceId === BeanType.water ? (
                  <View
                    key={beanItem.serviceId}
                    className='Home-UserBox-BeanItem'>
                    <Image className='Home-UserBox-BeanIcon' src={WBeanIcon} />
                    <Text>饮水豆：</Text>
                    <Text className='Home-UserBox-BeanCount'>
                      {beanItem.money ? beanItem.money.toFixed(2) : '0.00'}
                    </Text>
                  </View>
                ) : beanItem.serviceId === BeanType.hairDryer ? (
                  <View
                    key={beanItem.serviceId}
                    className='Home-UserBox-BeanItem'>
                    <Image className='Home-UserBox-BeanIcon' src={HBeanIcon} />
                    <Text>吹风豆：</Text>
                    <Text className='Home-UserBox-BeanCount'>
                      {beanItem.money ? beanItem.money.toFixed(2) : '0.00'}
                    </Text>
                  </View>
                ) : beanItem.serviceId === BeanType.shower ? (
                  <View
                    key={beanItem.serviceId}
                    className='Home-UserBox-BeanItem'>
                    <Image className='Home-UserBox-BeanIcon' src={SBeanIcon} />
                    <Text>洗浴豆：</Text>
                    <Text className='Home-UserBox-BeanCount'>
                      {beanItem.money ? beanItem.money.toFixed(2) : '0.00'}
                    </Text>
                  </View>
                ) : null,
              )}
          </View>

          <View className='Home-UserBox-Order'>
            <Text className='Home-UserBox-Order-text'>我的订单</Text>
            <View className='Home-UserBox-Order-right' onClick={this.goOrder}>
              <Image className='Home-UserBox-Order-icon' src={ArrowIcon} />
            </View>
          </View>
        </View>

        {serviceList.length && serviceList.length <= 2 ? (
          <View className='Home-Service-List big'>
            {serviceList.map(service =>
              service.serviceId === 3 || service.serviceId === 11 ? (
                <MenuIconBig
                  key={service.serviceId}
                  icon={WaterIconBig}
                  text={''}
                  side='right'
                  onClick={() => this.goBarCode(service.serviceId)}
                />
              ) : service.serviceId === 4 || service.serviceId === 12 ? (
                <MenuIconBig
                  ex-class='hairDryer'
                  key={service.serviceId}
                  icon={DryerIconBig}
                  text={service.serviceName}
                  side='right'
                  onClick={() => this.goBarCode(service.serviceId)}
                />
              ) : service.serviceId === 5 || service.serviceId === 10 ? (
                <MenuIconBig
                  key={service.serviceId}
                  icon={ShowerIconBig}
                  text={service.serviceName}
                  side='left'
                  onClick={this.goShower}
                />
              ) : service.serviceId === 9 ? (
                <MenuIconBig
                  key={service.serviceId}
                  icon={DispenserIconBig}
                  text={''}
                  side='left'
                  onClick={this.goDispenser}
                />
              ) : null,
            )}
          </View>
        ) : serviceList.length && serviceList.length == 3 ? (
          <View className='Home-Service-List block'>
            {serviceList.map(service =>
              service.serviceId === 3 || service.serviceId === 11 ? (
                <MenuIconBlock
                  key={service.serviceId}
                  icon={WaterIconBlock}
                  text={service.serviceName}
                  onClick={() => this.goBarCode(service.serviceId)}
                />
              ) : service.serviceId === 4 || service.serviceId === 12 ? (
                <MenuIconBlock
                  key={service.serviceId}
                  icon={DryerIconBlock}
                  text={service.serviceName}
                  onClick={() => this.goBarCode(service.serviceId)}
                />
              ) : service.serviceId === 5 || service.serviceId === 10 ? (
                <MenuIconBlock
                  key={service.serviceId}
                  icon={ShowerIconBlock}
                  text={service.serviceName}
                  onClick={this.goShower}
                />
              ) : service.serviceId === 9 ? (
                <MenuIconBlock
                  key={service.serviceId}
                  icon={DispenserIconBlock}
                  text={service.serviceName}
                  onClick={this.goDispenser}
                />
              ) : null,
            )}
          </View>
        ) : serviceList.length && serviceList.length >= 4 ? (
          <View className='Home-Service-List normal'>
            {serviceList.map(service =>
              service.serviceId === 3 || service.serviceId === 11 ? (
                <MenuIconNormal
                  key={service.serviceId}
                  icon={WaterIconNormal}
                  text={service.serviceName}
                  onClick={() => this.goBarCode(service.serviceId)}
                />
              ) : service.serviceId === 4 || service.serviceId === 12 ? (
                <MenuIconNormal
                  key={service.serviceId}
                  icon={DryerIconNormal}
                  text={service.serviceName}
                  onClick={() => this.goBarCode(service.serviceId)}
                />
              ) : service.serviceId === 5 || service.serviceId === 10 ? (
                <MenuIconNormal
                  key={service.serviceId}
                  icon={ShowerIconNormal}
                  text={service.serviceName}
                  onClick={this.goShower}
                />
              ) : service.serviceId === 9 ? (
                <MenuIconNormal
                  key={service.serviceId}
                  icon={DispenserIconNormal}
                  text={service.serviceName}
                  onClick={this.goDispenser}
                />
              ) : null,
            )}
          </View>
        ) : null}

        {annItem.id ? (
          <View className='Home-Announcement'>
            <Image className='bg' src={AnnouncementBg} />
            <View className='Home-Announcement-title'>
              <Text>最新公告</Text>
              <View
                className='Home-Announcement-more'
                onClick={() => this.goAnn(annItem.id)}>
                更多
                <Image className='more-icon' src={MoreIcon} />
              </View>
            </View>
            {annItem.items.length && (
              <View
                className='Home-Announcement-Content'
                onClick={() => this.geAnnDetail(annItem.items[0].id)}>
                <Text className='Home-Announcement-Content-title'>
                  {annItem.items[0].title}
                </Text>
                <Text className='ContentDate'>
                  {annItem.items[0].updateTime}
                </Text>
              </View>
            )}
          </View>
        ) : null}
      </View>
    );
  }
}

export default Home as ComponentClass<PageStateProps, PageState>;
