import React, { Component } from 'react';
import {
  ListView,
  PullToRefresh,
  Modal,
  Toast,
  TextareaItem,
} from 'antd-mobile';
import styles from './style.css';
import PublicCarItem from '../PublicCar/components/PublicCarItem';
import {
  fetchApplyPublicCarList,
  dealPublicCar,
  fetchCarPlateList,
} from '../../api/index';
// import Select from '../../components/Input/Select/Select';
import offCheckIcon from '../../images/Check/radio_off_btn@2x.png';
import onCheckIcon from '../../images/Check/radio_on_btn@2x.png';
import UserInfoContext from '../../context/userinfo-context';
import Select from './Select';

class PublicCarDeal extends Component {
  constructor(props) {
    super(props);
    const list = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    this.state = {
      refreshing: false,
      down: true,
      height: document.documentElement.clientHeight,
      pagination: {
        pageNum: 1,
        pageSize: 10,
      },
      list: list,
      sourceList: [],
      dealDialogVisible: false,
      selected: {
        id: '',
        value: '',
        carPlate: [],
        dealOpinion: '',
      },
      carPlateList: [],
    };
  }
  componentDidMount() {
    this.fetchList();
  }
  updateList = () => {
    const { sourceList } = this.state;
    this.setState(({ list }) => ({
      list: list.cloneWithRows(sourceList),
    }));
  };
  fetchList = fetchMore => {
    this.setState({ refreshing: true });
    const { pagination } = this.state;
    const nowDate = new Date().toISOString();
    const entity = fetchMore
      ? {
          ...pagination,
          pageNum: pagination.pageNum + 1,
        }
      : {
          ...pagination,
          pageNum: 1,
          nowDate,
        };
    fetchApplyPublicCarList(entity)
      .then(res => {
        this.setState(
          ({ sourceList }) =>
            fetchMore
              ? res.data.length
                ? {
                    sourceList: [...sourceList, ...res.data],
                    pagination: entity,
                    refreshing: false,
                  }
                : {
                    refreshing: false,
                  }
              : {
                  sourceList: res.data,
                  pagination: entity,
                  refreshing: false,
                }
        );
        this.updateList();
      })
      .catch(err => {
        Toast.fail(err.msg || '请求失败！');
        this.setState({
          refreshing: false,
        });
      });
  };
  refreshHandle = () => {
    this.fetchList(true);
  };
  dealHandle = id => {
    if (this.state.carPlateList.length === 0) {
      fetchCarPlateList()
        .then(res => {
          this.setState(({ carPlateList }) => ({
            carPlateList: res.data.map(i => ({
              value: i.id,
              lable: i.name,
            })),
          }));
        })
        .catch(err => {
          console.log(err);
        });
    }
    this.setState(({ selected }) => ({
      dealDialogVisible: true,
      selected: {
        ...selected,
        id,
      },
    }));
  };
  resetDialog = () => {
    this.setState(({ selected }) => ({
      dealDialogVisible: false,
      selected: {
        id: '',
        value: '',
        carPlate: [],
        dealOpinion: '',
      },
    }));
  };
  toggleSelectedState = val => {
    this.setState(({ selected }) => ({
      selected: {
        ...selected,
        value: val,
      },
    }));
  };
  validateSelect = () => {
    const {
      selected: { value, carPlate },
    } = this.state;
    if (!value) {
      Toast.fail('请选择处理结果！');
      return false;
    }
    if (value === 2) {
      if (carPlate.length === 0) {
        Toast.fail('请选择派车！');
        return false;
      }
    }
    return true;
  };
  submitHandle = () => {
    if (!this.validateSelect()) {
      return;
    }
    const {
      selected: { id, value, carPlate, dealOpinion },
    } = this.state;
    const { userinfo } = this.props;
    const entity =
      value === 2
        ? {
            id: id,
            dealName: userinfo.name,
            dealResult: value,
            carPlate: carPlate.join(','),
          }
        : {
            id: id,
            dealName: userinfo.name,
            dealResult: value,
            dealOpinion: dealOpinion
              ? `不同意 - ${dealOpinion}`
              : '不同意 - 无车可派送',
          };
    dealPublicCar(entity)
      .then(res => {
        this.resetDialog();
        this.fetchList();
        Toast.success(res.msg || '处理成功！');
      })
      .catch(err => {
        Toast.fail(err.msg || '处理失败！');
      });
  };
  onSelectHandle = val => {
    console.log(val);

    this.setState(({ selected }) => ({
      selected: {
        ...selected,
        carPlate: val,
      },
    }));
  };
  onInputHandle = val => {
    this.setState(({ selected }) => ({
      selected: {
        ...selected,
        dealOpinion: val,
      },
    }));
  };
  MyBody = props => {
    const {
      selected: { value, dealOpinion, carPlate },
      dealDialogVisible,
      carPlateList,
    } = this.state;
    return (
      <div className={styles.repairList}>
        <div className={styles.listInfo}>显示最近半年的约车记录</div>
        {props.children}
        <Modal
          className={styles.dealDialog}
          visible={dealDialogVisible}
          transparent
          maskClosable={false}
          onClose={this.resetDialog}
          title=""
          footer={[
            { text: '放弃', onPress: this.resetDialog },
            {
              text: '提交',
              onPress: this.submitHandle,
            },
          ]}
        >
          <div className={styles.dialogBody}>
            <div key="radio" className={styles.alertInfo}>
              <div
                className={styles.radioBox}
                onClick={() => this.toggleSelectedState(2)}
              >
                <span className={styles.checkLabel}>
                  {value === 2 ? (
                    <img src={onCheckIcon} alt="" />
                  ) : (
                    <img src={offCheckIcon} alt="" />
                  )}
                </span>
                <span>同意</span>
              </div>
              <div
                className={styles.radioBox}
                onClick={() => this.toggleSelectedState(3)}
              >
                <span className={styles.checkLabel}>
                  {value === 3 ? (
                    <img src={onCheckIcon} alt="" />
                  ) : (
                    <img src={offCheckIcon} alt="" />
                  )}
                </span>
                <span>不同意</span>
              </div>
            </div>
            {value === 2 ? (
              <div key="agree" className={styles.agree}>
                <span className={styles.dialogAgreeLabel}>派车车牌</span>
                <div className={styles.selectWrapBox}>
                  <Select
                    className={styles.select}
                    onChange={this.onSelectHandle}
                    value={carPlate}
                  >
                    {carPlateList.map(i => (
                      <div key={i.value} value={i.lable}>
                        {i.lable}
                      </div>
                    ))}
                  </Select>
                </div>
              </div>
            ) : value === 3 ? (
              <div key="notAgree" className={styles.notAgree}>
                <span className={styles.dialogLabel}>处理结果</span>
                <TextareaItem
                  className={styles.textarea}
                  placeholder="输入处理结果"
                  rows={3}
                  count={50}
                  value={dealOpinion}
                  onChange={this.onInputHandle}
                />
              </div>
            ) : null}
          </div>
        </Modal>
      </div>
    );
  };
  render() {
    const { list, pagination } = this.state;
    return (
      <ListView
        style={{
          height: this.state.height,
        }}
        className={styles.scrollWrap}
        dataSource={list}
        pageSize={pagination.pageSize}
        renderBodyComponent={() => <this.MyBody />}
        renderRow={rowData => (
          <PublicCarItem
            key={rowData.id}
            data={rowData}
            dealHandle={this.dealHandle}
          />
        )}
        onEndReached={this.refreshHandle}
        pullToRefresh={
          <PullToRefresh
            refreshing={this.state.refreshing}
            onRefresh={this.fetchList}
          />
        }
        // renderFooter={() => (
        //   <div style={{ textAlign: 'center' }}>
        //     {this.state.refreshing ? 'Loading...' : 'Loaded'}
        //   </div>
        // )}
      />
    );
  }
}

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