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

import UserBoxBg from '../../images/home/img_bg@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 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 { appLogout } from '../../api/customer';
import { Customer, CustomerSex } 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';
import { updateServiceList } from '@/store/rootReducers/service';
import {
  getShowerController,
  ShowerUseType,
  ControllerResponse,
} from '@/api/shower';
import { updateShowerControlConfig } from '@/store/rootReducers/shower';
import useNotices from './hooks/useNotices';

type PageStateProps = {
  userinfo: Customer;
  serviceList: Service[];
};
type PageDispatchProps = {
  updateUserInfo: (e: UserState) => void;
  updateServiceList: (e: Service[]) => void;
  updateShowerControlConfig: (e: ControllerResponse) => void;
};

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

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

interface Home {
  props: IProps;
  state: PageState;
}
@connect(
  ({ userinfo, serviceList }) => ({
    userinfo,
    serviceList,
  }),
  dispatch => ({
    updateUserInfo(entity: UserState) {
      dispatch(updateUserInfo(entity));
    },
    updateServiceList(entity: Service[]) {
      dispatch(updateServiceList(entity));
    },
    updateShowerControlConfig(e: ControllerResponse) {
      dispatch(updateShowerControlConfig(e));
    },
  }),
)
class Home extends Component {
  config: Config = {
    navigationBarBackgroundColor: '#eee',
  };

  constructor(props) {
    super(props);
    this.state = {
      barMenuVisiable: false,
      beanAccount: [],
      filterBeanList: [],
    };
  }

  onShareAppMessage = shareHandle;

  componentWillMount() {
    this.getInitData();
  }

  componentDidShow() {
    this.getInitData();
  }

  getInitData() {
    this.getServiceList();
  }

  getServiceList() {
    const { userinfo, updateServiceList } = this.props;
    if (userinfo.areaId) {
      fetchAreaService({
        areaId: userinfo.areaId,
        type: ServiceTypeParams.wechatAppV,
      }).then(res => {
        updateServiceList(res.data);
      });
    }
  }

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

  goOrder() {
    Taro.navigateTo({
      url: '/pages/Order/OrderList/OrderList',
    });
  }
  goAccount() {
    Taro.navigateTo({
      url: '/pages/Account/Account',
    });
  }
  goBarCode(serviceId: number) {
    Taro.navigateTo({
      url: `/pages/BarCode/BarCode?serviceId=${serviceId}`,
    });
  }

  goShower = () => {
    const { userinfo, updateShowerControlConfig } = this.props;
    getShowerController({
      campusId: userinfo.areaId,
      customerId: userinfo.customerId,
    })
      .then(res => {
        let data = res.data;
        updateShowerControlConfig(res.data);
        let type =
          data.useType === ShowerUseType.mix ? data.defaultType : data.useType;
        if (type === ShowerUseType.bluetooth) {
          Taro.navigateTo({
            url: '/pages/Shower/Shower',
          });
        } else {
          Taro.navigateTo({
            url: '/pages/Shower/ShowerAppointment',
          });
        }
      })
      .catch(err => {
        console.log('getShowerController err:', err);
        Taro.showToast({
          title: err.msg || '网络错误',
          icon: 'none',
        });
      });
  };

  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(code: string) {
    const { userinfo } = this.props;
    Taro.navigateTo({
      url: `/pages/Content/Content?id=${code}&customerId=${userinfo.customerId}`,
    });
  }

  goUserSetting() {
    this.toggleBarMenu();
    Taro.navigateTo({
      url: '/pages/UserSetting/CustomerSetting',
    });
  }

  render() {
    const { userinfo, serviceList } = this.props;
    const { barMenuVisiable } = this.state;

    const noticeData = useNotices();
    return (
      <View className='Home'>
        {barMenuVisiable ? (
          <View>
            <View className='mask' onClick={this.toggleBarMenu} />
            <View className='Home-BarMenu'>
              <View className='Home-BarMenu-Content'>
                <View onClick={this.goUserSetting}>个人设置</View>
                <View onClick={this.goFeedback}>意见反馈</View>
                <View onClick={this.logoutHandle}>切换账号</View>
              </View>
            </View>
          </View>
        ) : null}
        <View className='Home-UserBox'>
          <View className='Home-UserBox-content'>
            <Image
              className='Home-UserBox-Setting'
              src={SettingIcon}
              onClick={this.toggleBarMenu}
            />
            <Image className='bg' 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'>
                  {userinfo.customerPhone &&
                    this.formatePhone(userinfo.customerPhone)}
                </View>
                <View className='Home-UserBox-addr'>{userinfo.areaName}</View>
              </View>
              {userinfo.customerSex === CustomerSex.girl ? (
                <Image
                  className='Home-UserBox-headimg'
                  src={UserHeaderF}
                  onClick={this.goSetting}
                />
              ) : (
                <Image
                  className='Home-UserBox-headimg'
                  src={UserHeaderM}
                  onClick={this.goSetting}
                />
              )}
            </View>
          </View>

          <View className='Home-UserBox-Order'>
            <Text className='Home-UserBox-Order-text' onClick={this.goOrder}>
              我的订单
            </Text>
            <Text className='Home-UserBox-Order-text' onClick={this.goAccount}>
              账户
            </Text>
          </View>
        </View>
        <View className='Home-Service'>
          {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}
        </View>

        {noticeData.noticeCode ? (
          <View className='Home-Announcement'>
            <Image className='bg' src={AnnouncementBg} />
            <View className='Home-Announcement-title'>
              <Text>最新公告</Text>
              <View
                className='Home-Announcement-more'
                onClick={() => this.goAnn(noticeData.noticeCode)}>
                更多
                <Image className='more-icon' src={MoreIcon} />
              </View>
            </View>
            <View
              className='Home-Announcement-Content'
              onClick={() => this.geAnnDetail(noticeData.noticeCode)}>
              <Text className='Home-Announcement-Content-title'>
                {noticeData.noticeTitle}
              </Text>
              <Text className='ContentDate'>{noticeData.updateAt}</Text>
            </View>
          </View>
        ) : null}
      </View>
    );
  }
}

export default Home as ComponentClass<PageStateProps, PageState>;
