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

import UserHeaderM from '../../images/home/img_boy_touxiang@2x.png';
import UserHeaderF from '../../images/home/img_girl_touxiang@2x.png';
import InfoIcon from '../../images/user/pc_minel_icon@2x.png';
import SchoolIcon from '../../images/user/pc_school_icon@2x.png';
import radioIcon from '../../images/login/pc_nor_icon@2x.png';
import radioCheckIcon from '../../images/login/pc_sel_icon@2x.png';
import './UserSetting.scss';
import { connect } from '@tarojs/redux';
import { updateUserInfo } from '../../store/rootReducers/userinfo';
import { perfectionUserInfo } from '../../api/customer';
import { Customer } from '../../types/Customer/Customer';
import { shareHandle } from '@/common/shareMethod';

type UpdateParams = {
  customerId: number;
  customerName: string;
  customerSex: string;
  birthDay: string;
  studentNo: string;
  entranceDate: string;
};
type PageStateProps = {
  userinfo: Customer;
};
type PageDispatchProps = {
  updateUserInfo: (e: UpdateParams) => void;
};
type PageOwnProps = {};
type PageState = {
  birthDay: string;
  customerHead: string;
  customerName: string;
  customerSex: string;
  entranceDate: string;
  studentNo: string;
};
type IProps = PageStateProps & PageDispatchProps & PageOwnProps;
interface UserSetting {
  props: IProps;
  state: PageState;
}

@connect(
  ({ userinfo }) => ({
    userinfo,
  }),
  dispatch => ({
    updateUserInfo(entity: UpdateParams) {
      dispatch(updateUserInfo(entity));
    },
  }),
)
class UserSetting extends Component {
  config: Config = {
    navigationBarBackgroundColor: '#6180f4',
    navigationBarTitleText: '',
  };
  constructor(props: IProps) {
    super(props);
    const {
      userinfo: {
        birthDay,
        customerHead,
        customerName,
        customerSex,
        entranceDate,
        studentNo,
      },
    } = props;
    this.state = {
      birthDay: birthDay ? birthDay.split(' ')[0] : '',
      customerHead: customerHead ? customerHead : '',
      customerName: customerName ? customerName : '',
      customerSex: customerSex ? customerSex : '',
      entranceDate: entranceDate ? entranceDate.split(' ')[0] : '',
      studentNo: studentNo ? studentNo : '',
    };
  }
  onShareAppMessage = shareHandle;

  validateSaveForm(): boolean {
    const { customerName } = this.state;
    if (!customerName) {
      Taro.showToast({
        title: '请输入姓名',
      });
      return false;
    }
    return true;
  }
  saveHandle() {
    if (this.validateSaveForm()) {
      Taro.showLoading();
      const {
        userinfo: { customerId },
        updateUserInfo,
      } = this.props;
      const {
        customerName,
        customerSex,
        birthDay,
        studentNo,
        entranceDate,
      } = this.state;
      const entity = {
        customerId: customerId,
        customerName,
        customerSex,
        birthDay,
        studentNo,
        entranceDate,
      };
      perfectionUserInfo(entity)
        .then(() => {
          Taro.hideLoading();
          updateUserInfo(entity);
          this.refs.ToastBox.showToast('已保存');
        })
        .catch(err => {
          console.log(err);
          Taro.showToast({
            title: err.msg || '保存失败',
            icon: 'none',
          });
        });
    }
  }

  render() {
    const { userinfo } = this.props;
    const {
      customerName,
      customerSex,
      birthDay,
      studentNo,
      entranceDate,
    } = this.state;
    return (
      <View className='UserSetting'>
        <ToastBox ref='ToastBox' />
        <View className='UserSetting-Header'>
          <View className='UserSetting-HeaderIconBox'>
            {userinfo.customerSex === '1' ? (
              <Image className='UserSetting-HeaderIcon' src={UserHeaderM} />
            ) : (
              <Image className='UserSetting-HeaderIcon' src={UserHeaderF} />
            )}
          </View>
        </View>
        <View className='UserSetting-name'>{userinfo.customerName}</View>
        <View className='UserSetting-Content'>
          <View className='UserSetting-title'>
            <Image className='UserSetting-titleIcon' src={InfoIcon} />
            <Text>我的信息</Text>
            <View className='UserSetting-titleLine' />
          </View>
          <View className='UserSetting-ContentItem'>
            <Text>姓名：</Text>
            <Input
              className='UserSetting-ContentItem-input'
              maxLength={20}
              value={customerName}
              onInput={({ detail: { value } }) => {
                this.setState({
                  customerName: value.trim(),
                });
                return value.trim();
              }}
            />
          </View>
          <View className='UserSetting-ContentItem'>
            <Text>性别：</Text>
            <View className='loginBox-input sexBox'>
              <View
                className='sexBox-item'
                onClick={() =>
                  this.setState({
                    customerSex: '2',
                  })
                }>
                {customerSex === '2' ? (
                  <Image className='sexBox-icon' src={radioCheckIcon} />
                ) : (
                  <Image className='sexBox-icon' src={radioIcon} />
                )}
                <Text>女</Text>
              </View>
              <View
                className='sexBox-item'
                onClick={() =>
                  this.setState({
                    customerSex: '1',
                  })
                }>
                {customerSex === '1' ? (
                  <Image className='sexBox-icon' src={radioCheckIcon} />
                ) : (
                  <Image className='sexBox-icon' src={radioIcon} />
                )}
                <Text>男</Text>
              </View>
            </View>
          </View>
          <View className='UserSetting-ContentItem'>
            <Text>出生日期：</Text>
            <Picker
              value={birthDay}
              mode='date'
              onChange={({ detail: { value } }) =>
                this.setState({
                  birthDay: value,
                })
              }>
              {birthDay ? (
                <View>{birthDay}</View>
              ) : (
                <View className='UserSetting-placeholder'>
                  {'请选择出生日期'}
                </View>
              )}
            </Picker>
          </View>
          <View className='UserSetting-ContentItem Disabled'>
            <Text>多彩账号：</Text>
            <Text>15961654</Text>
          </View>
          <View className='UserSetting-ContentItem Disabled'>
            <Text>设备账号：</Text>
            <Text>1855</Text>
          </View>
          <View className='UserSetting-title'>
            <Image className='UserSetting-titleIcon' src={SchoolIcon} />
            <Text>学校信息</Text>
            <View className='UserSetting-titleLine' />
          </View>
          <View className='UserSetting-ContentItem Disabled'>
            <Text>学校：</Text>
            <Text>{userinfo.areaName}</Text>
          </View>
          <View className='UserSetting-ContentItem'>
            <Text>学号：</Text>
            <Input
              className='UserSetting-ContentItem-input'
              value={studentNo}
              placeholderClass='UserSetting-placeholder'
              placeholder='请输入学号'
              onInput={({ detail: { value } }) => {
                this.setState({
                  studentNo: value.trim(),
                });
                return value.trim();
              }}
            />
          </View>
          <View className='UserSetting-ContentItem'>
            <Text>入学日期：</Text>
            <Picker
              value={entranceDate}
              mode='date'
              onChange={({ detail: { value } }) =>
                this.setState({
                  entranceDate: value,
                })
              }>
              {entranceDate ? (
                <View>{entranceDate}</View>
              ) : (
                <View className='UserSetting-placeholder'>
                  {'请选择入学日期'}
                </View>
              )}
            </Picker>
          </View>
        </View>
        <Button className='UserSetting-save' onClick={this.saveHandle}>
          保存
        </Button>
      </View>
    );
  }
}

export default UserSetting as ComponentClass<PageOwnProps, PageState>;
