// 配送地址 / 配送地址维护
import React from 'react';
import {InputItem, TextareaItem, Button, Toast, Modal, List} from 'antd-mobile';
import { createForm } from 'rc-form';
import AddressSelectionControl from 'pages/common/component/AddressSelectionControl.jsx';
import {Util} from 'tools';
import { $http } from "containers/config/https";
import './style/index.less';

const alert = Modal.alert;

class DeliveryAddressMaintenance extends React.Component {
  constructor({history}) {
    super();
    let weChatParams = sessionStorage.getItem("weChatParams") ? JSON.parse(sessionStorage.getItem("weChatParams")) : {};
    this.state = {
      weChatParams, 
      userInfo: {},
      verificationLocation: false
    };
    this.history = history;
  }

  componentDidMount() {
    let userInfo = this.props.location&&this.props.location.state ? this.props.location.state : {};
    if (userInfo&&userInfo.id) {
      userInfo.location = (userInfo.provinceDesc || "--") + "-" + (userInfo.cityDesc || "") + "-" + (userInfo.areaDesc || "") + "-" + (userInfo.villageDesc || "");
    }
    this.setState({userInfo});
  }

  cityRef = ref => {
    this.cityChild = ref;
  }

  // 打开地址选择弹窗
  showAddressModal = () => {
    let cityData = this.cityChild.exportCitySelectInfo("");
    let {userInfo} = this.state;
    this.cityChild.handleShowModal(cityData&&cityData.provData&&cityData.provData.id ? cityData : userInfo);
  }

  // 保存
  handleSave = () => {
    let {userInfo, verificationLocation} = this.state;
    if (!(userInfo.location)) {
      this.setState({verificationLocation: true})
    } else {
      this.setState({verificationLocation: false})
    }
    this.props.form.validateFields({ force: true }, (error) => {
      if (!error&&!verificationLocation) {
        let values = this.props.form.getFieldsValue();
        let cityData = this.cityChild.exportCitySelectInfo("");
        console.log(cityData)
        values.id = userInfo&&userInfo.id ? userInfo.id : "";
        values.provinceID = cityData.provData&&cityData.provData.value ? cityData.provData.value : (userInfo&&userInfo.provinceID ? userInfo.provinceID : "");
        values.cityID = cityData.cityData&&cityData.cityData.value ? cityData.cityData.value : (userInfo&&userInfo.cityID ? userInfo.cityID : "");
        values.areaID = cityData.countryData&&cityData.countryData.value ? cityData.countryData.value : (userInfo&&userInfo.areaID ? userInfo.areaID : "");
        values.villageID = cityData.regionData&&cityData.regionData.value ? cityData.regionData.value : (userInfo&&userInfo.villageID ? userInfo.villageID : "");
        values.mobile = values.mobile ? Util.removeSpacesFromString(values.mobile) : "";
        let {weChatParams} = this.state;
        let data = {
          params: [{
            ...values,
            pubAccCode: weChatParams.pubAccCode || '',
            openID: weChatParams.openID || '',
          }]
        }
        $http.post("urlS", this, {
          code: "01020005",
          data: data,
          success: function(res) {
            if (+res.errorCode === 0) {
              Toast.info(res.errorMessage);
              let address = res.result&&res.result.address ? res.result.address : {};
              window.sessionStorage.setItem(
                "deliveryAddress",
                JSON.stringify(
                  {...address}
                )
              );
              this.history.goBack();
            } else {
              Toast.info(res.errorMessage);
            }
          },
          error: function(error) {
            Toast.info(error);
          }
        });
      } else {
        Toast.info("请完善相关信息。")
      }
    });
  }

  // 点击显示错误信息
  onErrorClick = (e) => {
    e.stopPropagation();
    Toast.info("请完善所在地区。")
  }

  // 给地址选框赋值
  addressBoxAssignment = () => {
    // 获取城市描述
    let cityTitle = this.cityChild.exportCitySelectInfo("descripts");
    let {userInfo} = this.state;
    userInfo.location = cityTitle
    this.setState({userInfo, verificationLocation: false}, () => {
      this.cityChild.handleClose(); // 关闭城市弹窗
    })
  }

  // 删除地址
  handleDeleteAddress = () => {
    let {userInfo} = this.state;
		let data = {
			params: [{
				id: userInfo.id || ""
			}]
		}
		$http.post("urlS", this, {
			code: "01020007",
			data: data,
			success: function(res) {
				if (+res.errorCode === 0) {
          Toast.info(res.errorMessage);
          this.history.goBack();
				}
			}
		});
  }
  
  // 手机号验证
  handleVerificationMobile = (rule, value, callback) => {
    if (value && (/^1[3456789]\d{9}$/.test(value.replace(/\s*/g,'')))) {
      callback();
    } else {
      callback(new Error("手机号码有误，请重填"));
    }
  }

  handleDateClick = (e) => {
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
  }

  render() {
    let {userInfo, verificationLocation} = this.state;
    const { getFieldProps, getFieldError } = this.props.form;
    return (
      <div className="delivery-address-maintenance">
        {/* <form> */}
          <InputItem
            error={!!getFieldError('name')}
            onErrorClick={() => {
              Toast.info(getFieldError('name').join('、'));
            }}
            {...getFieldProps('name', {
              initialValue: userInfo.name ? userInfo.name : undefined,
              rules: [
                { required: true, message: '姓名不能为空' },
              ],
            })}
          >姓名</InputItem>
          <InputItem
            error={!!getFieldError('mobile')}
            onErrorClick={() => {
              Toast.info(getFieldError('mobile').join('、'));
            }}
            {...getFieldProps('mobile', {
              initialValue: userInfo.mobile ? Util.phoneAddGap(userInfo.mobile) : undefined,
              rules: [{ validator: this.handleVerificationMobile }],
            })}
            type="phone"
          >手机号码</InputItem>
          <List.Item onClick={this.showAddressModal} className={verificationLocation ? "am-input-error" : ""}><span className="am-input-label am-input-label-5" style={{float: "left"}}>
            所在地区</span>{userInfo.location ? userInfo.location : ""}
            <div className="am-input-error-extra" style={{float: "right"}} onClick={(e) => this.onErrorClick(e)}></div>
          </List.Item>
          <TextareaItem
            title="详细地址"
            placeholder="详细地址：如街道、门牌号、小区、楼栋号、单元室等"
            data-seed="logId"
            autoHeight
            error={!!getFieldError('address')}
            onErrorClick={() => {
              Toast.info(getFieldError('address').join('、'));
            }}
            {...getFieldProps('address', {
              initialValue: userInfo.address ? userInfo.address : undefined,
              rules: [
                { required: true, message: '详细地址不能为空' },
              ],
            })}
          />
        {/* </form> */}
        <div className="btn">
          <Button type="primary" onClick={this.handleSave}>{userInfo&&userInfo.id ? "保存并使用" : "新增并使用"}</Button>
          {userInfo&&userInfo.id ? <p onClick={() =>
            alert('删除', '删除后不可恢复确认删除吗???', [
              { text: '取消', onPress: () => console.log('cancel') },
              { text: '确认', onPress: () => this.handleDeleteAddress() },
            ])
          }>删除该地址</p> : ""}
        </div>
        <AddressSelectionControl onRef={this.cityRef} addressBoxAssignment={this.addressBoxAssignment} />
      </div>
    )
  }
};
const DeliveryAddressMaintenanceForm = createForm()(DeliveryAddressMaintenance);
export default DeliveryAddressMaintenanceForm;