import React, { Component } from 'react';
import styles from './style.css';
import { Toast, Button, TextareaItem, Modal } from 'antd-mobile';
import peopleIcon from './images/repair_people_icon@2x.png';
import phoneIcon from './images/phone_tel_icon@2x.png';
import roleIcon from './images/user_role_icon@2x.png';
import areaIcon from './images/repair_area_icon@2x.png';
import typeIcon from './images/repair_item_icon@2x.png';
import addrIcon from './images/repair_addr_icon@2x.png';
import imgIcon from './images/upload_pic_icon@2x.png';
import ImagePicker from '../../components/Input/ImagePicker/ImagePicker';
import Select from '../../components/Input/Select/Select';
import { fetchRepairArea, fetchRepairTerm } from '../../api/index';
import { reportRepair } from '../../api/repairAdd';
import Perview from '../../components/Perview/Perview';
import store from '../../store/index';
import UserInfoContext from '../../context/userinfo-context';
import offCheckIcon from '../../images/Check/radio_off_btn@2x.png';
import onCheckIcon from '../../images/Check/radio_on_btn@2x.png';
import { emojiFilter } from '../../utils/index';

class ReprtRepair extends Component {
  constructor(props) {
    super(props);
    this.state = {
      areaList: [],
      termList: [],
      applyForm: {
        name: props.userinfo.name,
        repairCellphone: props.userinfo.cellphone,
        applyIdentity: '学生',
        area: '',
        areaId: [],
        term: '',
        termId: [],
        address: '',
        uploadImg: [null, null, null],
      },
      perviewVisibility: false,
      perviewIndex: 0,
    };
  }
  componentDidMount() {
    fetchRepairArea()
      .then(res => {
        let list = res.data.length
          ? res.data.map(i => ({
              value: i.id,
              label: i.name,
            }))
          : [];
        this.setState(() => ({
          areaList: list,
        }));
      })
      .catch(err => {
        console.log(err);
      });
    fetchRepairTerm()
      .then(res => {
        let list = res.data.length
          ? res.data.map(i => ({
              value: i.id,
              label: i.name,
            }))
          : [];
        this.setState(() => ({
          termList: list,
        }));
      })
      .catch(err => {
        console.log(err);
      });
  }
  resetApplyForm = () => {
    const { userinfo } = this.props;
    this.setState({
      applyForm: {
        name: userinfo.name,
        repairCellphone: userinfo.cellphone,
        applyIdentity: '学生',
        area: '',
        areaId: [],
        term: '',
        termId: [],
        address: '',
        uploadImg: [null, null, null],
      },
    });
  };
  onChangeHandle = e => {
    const { name, value } = e.target;
    this.setState(({ applyForm }) => ({
      applyForm: {
        ...applyForm,
        [name]: emojiFilter(value),
      },
    }));
  };
  onSelectHandle = (key, val) => {
    console.log(key, val);
    this.setState(({ applyForm }) => ({
      applyForm: {
        ...applyForm,
        [key]: val,
      },
    }));
  };
  onImagePicker = (index, val) => {
    console.log(index, val);
    const { uploadImg } = this.state.applyForm;
    uploadImg[index] = val;
    this.setState(({ applyForm }) => ({
      applyForm: {
        ...applyForm,
        uploadImg: uploadImg,
      },
    }));
  };
  showViewHandle = index => {
    console.log(index);
    this.setState({
      perviewVisibility: true,
      perviewIndex: index,
    });
  };
  validateForm = () => {
    const { applyForm } = this.state;
    if (!applyForm.name) {
      Toast.fail('请输入报修人！');
      return;
    }
    if (!applyForm.repairCellphone) {
      Toast.fail('请输入报修人电话！');
      return;
    }
    if (applyForm.repairCellphone.length !== 11) {
      Toast.fail('请输入正确电话！');
      return;
    }
    if (!applyForm.applyIdentity) {
      Toast.fail('请选择报修人身份！');
      return;
    }
    if (!applyForm.areaId.length) {
      Toast.fail('请选择报修区域！');
      return;
    }
    if (!applyForm.termId.length) {
      Toast.fail('请选择报修项目！');
      return;
    }
    if (!applyForm.address) {
      Toast.fail('请输入报修地址！');
      return;
    }
    let imgList = applyForm.uploadImg.filter(i => i !== null);
    if (imgList.length) {
      let size = imgList.reduce((totle, item) => {
        let fileSize = item.filesList[0].size;
        return totle + fileSize;
      }, 0);
      if (size > 10485760) {
        Toast.fail('上传图片过大！');
        return;
      }
    }
    return true;
  };
  startApply = () => {
    if (!this.validateForm()) {
      return;
    }
    Toast.loading('', 99);
    let formData = new FormData();
    this.state.applyForm.uploadImg.map(i => {
      if (i) {
        console.log(i);
        formData.append('file', i.filesList[0]);
      }
      return i;
    });
    let area = this.state.areaList.find(
      i => i.value === this.state.applyForm.areaId[0]
    ).label;
    let term = this.state.termList.find(
      i => i.value === this.state.applyForm.termId[0]
    ).label;
    formData.append('userId', store.getUserId());
    // product 需要登陆后的用户ID
    formData.append('applyIdentity', this.state.applyForm.applyIdentity);
    formData.append('area', area);
    formData.append('term', term);
    formData.append('address', this.state.applyForm.address);
    formData.append('repairCellphone', this.state.applyForm.repairCellphone);
    formData.append('termId', this.state.applyForm.termId);
    formData.append('areaId', this.state.applyForm.areaId);
    formData.append('name', this.state.applyForm.name);

    reportRepair(formData)
      .then(res => {
        console.log(res);
        const { data } = res;
        if (data.code && data.code === 1000) {
          const { data } = res;
          const { history } = this.props;
          console.log('resetForm');
          this.resetApplyForm();
          // Toast.hide();
          Toast.success(data.msg);
          history.replace('/repair/RepairList');
        } else {
          throw data.msg;
        }
      })
      .catch(err => {
        console.log(err);
        // Toast.hide();
        Toast.fail(err.msg || err.message || '提交失败！');
      });
  };
  resetDialog = () => {
    this.setState({
      perviewVisibility: false,
    });
  };
  render() {
    const {
      applyForm,
      areaList,
      termList,
      perviewVisibility,
      perviewIndex,
    } = this.state;

    return (
      <div className={styles.wrap}>
        <div className={styles.listItem}>
          <i className={styles.itemIcon}>
            <img src={peopleIcon} alt="" />
          </i>
          <span className={styles.itemLabel}>报修人</span>
          <div className={styles.inputBox}>
            <input
              className={styles.input}
              type="text"
              maxLength="20"
              name="name"
              value={applyForm.name}
              onChange={this.onChangeHandle}
            />
          </div>
        </div>
        <div className={styles.listItem}>
          <i className={styles.itemIcon}>
            <img src={phoneIcon} alt="" />
          </i>
          <span className={styles.itemLabel}>报修人tel</span>
          <div className={styles.inputBox}>
            <input
              className={styles.input}
              type="tel"
              maxLength="11"
              name="repairCellphone"
              value={applyForm.repairCellphone}
              onChange={this.onChangeHandle}
            />
          </div>
        </div>
        <div className={styles.listItem}>
          <i className={styles.itemIcon}>
            <img src={roleIcon} alt="" />
          </i>
          <span className={styles.itemLabel}>报修身份</span>
          <div className={styles.inputBoxNoBB}>
            {/* <input className={styles.input} type="text" /> */}

            <div
              className={styles.checkBox}
              onClick={() =>
                this.onChangeHandle({
                  target: { name: 'applyIdentity', value: '老师' },
                })
              }
            >
              <div className={styles.checkLabel}>
                {applyForm.applyIdentity === '老师' ? (
                  <img src={onCheckIcon} alt="" />
                ) : (
                  <img src={offCheckIcon} alt="" />
                )}
              </div>
              <div>老师</div>
            </div>
            <div
              className={styles.checkBox}
              onClick={() =>
                this.onChangeHandle({
                  target: { name: 'applyIdentity', value: '学生' },
                })
              }
            >
              <div className={styles.checkLabel}>
                {applyForm.applyIdentity === '学生' ? (
                  <img src={onCheckIcon} alt="" />
                ) : (
                  <img src={offCheckIcon} alt="" />
                )}
              </div>
              <div>学生</div>
            </div>
            {/* <Radio
              className="my-radio"
              name="applyIdentity"
              value="老师"
              checked={applyForm.applyIdentity === '老师'}
              onChange={this.onChangeHandle}
            />
            <Radio
              className="my-radio"
              name="applyIdentity"
              value="学生"
              checked={applyForm.applyIdentity === '学生'}
              onChange={this.onChangeHandle}
            >
              学生
            </Radio> */}
          </div>
        </div>
        <div className={styles.listItem}>
          <i className={styles.itemIcon}>
            <img src={areaIcon} alt="" />
          </i>
          <span className={styles.itemLabel}>报修区域</span>
          <div className={styles.inputBox}>
            <Select
              placeholder="请选择"
              data={areaList}
              cols={1}
              value={applyForm.areaId}
              onChange={val => this.onSelectHandle('areaId', val)}
            />
          </div>
        </div>
        <div className={styles.listItem}>
          <i className={styles.itemIcon}>
            <img src={typeIcon} alt="" />
          </i>
          <span className={styles.itemLabel}>报修项目</span>
          <div className={styles.inputBox}>
            {/* <input className={styles.input} type="text" /> */}
            <Select
              placeholder="请选择"
              data={termList}
              cols={1}
              value={applyForm.termId}
              onChange={val => this.onSelectHandle('termId', val)}
            />
          </div>
        </div>
        <div className={styles.listItem}>
          <i className={styles.itemIcon}>
            <img src={addrIcon} alt="" />
          </i>
          <span className={styles.itemLabel}>报修地址</span>
        </div>
        <TextareaItem
          className="textarea"
          placeholder="输入报修地址"
          rows={3}
          count={50}
          value={this.state.applyForm.address}
          onChange={val =>
            this.setState(({ applyForm }) => ({
              applyForm: {
                ...applyForm,
                address: emojiFilter(val.replace(/\n/, '')),
              },
            }))
          }
        />
        <div className={styles.listItem}>
          <i className={styles.itemIcon}>
            <img src={imgIcon} alt="" />
          </i>
          <span className={styles.itemLabel}>上传图片</span>
        </div>
        <div className={styles.imageArea}>
          <ImagePicker
            value={applyForm.uploadImg[0]}
            showView={() => this.showViewHandle(0)}
            onChange={fileList => this.onImagePicker(0, fileList)}
          />
          <ImagePicker
            value={applyForm.uploadImg[1]}
            showView={() => this.showViewHandle(1)}
            onChange={fileList => this.onImagePicker(1, fileList)}
          />
          <ImagePicker
            value={applyForm.uploadImg[2]}
            showView={() => this.showViewHandle(2)}
            onChange={fileList => this.onImagePicker(2, fileList)}
          />
        </div>
        <Button className={styles.applyBtn} onClick={this.startApply}>
          提交
        </Button>
        <Modal
          className={styles.perViewDialog}
          visible={perviewVisibility}
          transparent
          maskClosable={true}
          onClose={this.resetDialog}
          title=""
        >
          <Perview data={applyForm.uploadImg} index={perviewIndex} />
        </Modal>
      </div>
    );
  }
}

export default props => (
  <UserInfoContext.Consumer>
    {({ userinfo }) => <ReprtRepair userinfo={userinfo} {...props} />}
  </UserInfoContext.Consumer>
);
