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 { 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';
import { updateServiceList } from '@/store/rootReducers/service';
import {
  getShowerController,
  ShowerUseType,
  ControllerResponse,
} from '@/api/shower';
import { updateShowerControlConfig } from '@/store/rootReducers/shower';

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[];
  annItem: SectionItem;
  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: [],
      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.getServiceList();
    this.getAnn();
  }

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

  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);
      });
  }

  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',
    });
  }
  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(id: number) {
    console.log(id);
    Taro.navigateTo({
      url: `/pages/Content/Content?id=${id}`,
    });
  }

  render() {
    const { userinfo, serviceList } = this.props;
    const { annItem, barMenuVisiable } = 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'>
          <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'>
                  {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>

          <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>

        {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>;
