// 地址选择 -- 省市县街道
import React from 'react';
import {Modal, Steps, List, Radio} from 'antd-mobile';
import './style/index.less';
import { $http } from "containers/config/https";

const RadioItem = Radio.RadioItem;

const Step = Steps.Step;

export default class AddressSelectionControl extends React.Component {
  constructor() {
    super();
    this.state = {
      visible: false,
      provSelectData: [],
      stepListData: [],
      activeSteps: "1",
      provValue: {},
      citySelectData: [],
      cityValue: {},
      countrySelectData: [],
      countryValue: {},
      regionSelectData: [],
      regionValue: {},
      selectType:""
    }
  }

  componentDidMount() {
    this.props.onRef(this);
    this.getProvSelectData();
  }

  // 获取省数据
  getProvSelectData = () => {
    let data = {
			params: [{}]
		}
    $http.post("urlS", this, {
			code: "02010030",
			data: data,
			success: function(res) {
				if (+res.errorCode === 0) {
          let arr = res.result&&res.result.rows.length > 0 ? res.result.rows : [];
          this.setState({provSelectData: arr})
				}
			}
		});
  }

  // 获取市数据
  getCitySelectData = (item) => {
    let data = {
			params: [{
        provinceID: item&&item.value ? item.value : ""
      }]
		}
    $http.post("urlS", this, {
			code: "02010031",
			data: data,
			success: function(res) {
				if (+res.errorCode === 0) {
          let arr = res.result&&res.result.rows.length > 0 ? res.result.rows : [];
          this.setState({citySelectData: arr})
				}
			}
		});
  }

  // 获取县（区）的数据
  getCountrySelectData = (item) => {
    let data = {
			params: [{
        cityID: item&&item.value ? item.value : ""
      }]
		}
    $http.post("urlS", this, {
			code: "02010032",
			data: data,
			success: function(res) {
				if (+res.errorCode === 0) {
          let arr = res.result&&res.result.rows.length > 0 ? res.result.rows : [];
          this.setState({countrySelectData: arr});
				}
			}
		});
  }

  // 获取镇（街道）的数据
  getRegionSelectData = (item) => {
    let data = {
			params: [{
        areaID: item&&item.value ? item.value : ""
      }]
		}
    $http.post("urlS", this, {
			code: "02010033",
			data: data,
			success: function(res) {
				if (+res.errorCode === 0) {
          let arr = res.result&&res.result.rows.length > 0 ? res.result.rows : [];
          this.setState({regionSelectData: arr});
				}
			}
		});
  }

  // 关闭弹窗
  handleClose = () => {
    this.setState({visible: false});
  }

  filterIdAndDescripts = (id, desc) => {
    let arr = [];
    let obj = {}
    obj.value = id ? id : "";
    obj.label = desc ? desc : "";
    arr.push(obj);
    return arr;
  }

  // 打开弹窗
  handleShowModal = (userInfo,type) => {
    if (userInfo && userInfo.provinceID) {
      let stepListData = [];
      let obj = {};
      if ( type && (type==="native" || type==="birth")){
        obj.prov = this.filterIdAndDescripts(userInfo.provinceID, userInfo.provinceDesc);
        obj.city = this.filterIdAndDescripts(userInfo.cityID, userInfo.cityDesc);
        obj.country = this.filterIdAndDescripts(userInfo.areaID, userInfo.areaDesc);
      }else{
        obj.prov = this.filterIdAndDescripts(userInfo.provinceID, userInfo.provinceDesc);
        obj.city = this.filterIdAndDescripts(userInfo.cityID, userInfo.cityDesc);
        obj.country = this.filterIdAndDescripts(userInfo.areaID, userInfo.areaDesc);
        obj.region = this.filterIdAndDescripts(userInfo.villageID, userInfo.villageDesc);
      }
      stepListData.push(obj);
      if ( type && (type==="native" || type==="birth")){
        this.setState({selectType: type,visible: true, stepListData, provValue: obj.prov[0], cityValue: obj.city[0], countryValue: obj.country[0]});
      }else{
        this.setState({selectType: type,visible: true, stepListData, provValue: obj.prov[0], cityValue: obj.city[0], countryValue: obj.country[0], regionValue: obj.region[0]});
      }
      if (type){
        this.setState({
          activeSteps: "1"
        })
      }
    } else {
      let stepListData = [{
        prov: [],
        city: [],
        country: [],
        region: []
      }];
      this.setState({selectType: type,visible: true, activeSteps: "1", stepListData})
    }
    
  }

  handleRadioChange = item => {
    let {activeSteps, stepListData,selectType} = this.state;
    if (!(stepListData&&stepListData.length > 0)) {
      stepListData.push({});
    }
    let arr = [];
    arr.push(item);
    if (activeSteps === "1") {
      let cityData = [
        {
          label: "请选择城市"
        }
      ]
      stepListData[0].prov = arr;
      stepListData[0].city = cityData;
      stepListData[0].country = [];
      stepListData[0].region = [];
      this.setState({stepListData, provValue: item, activeSteps: "2"}, () => {
        this.getCitySelectData(this.state.provValue)
      })
    } else if (activeSteps === "2") {
      let countryData = [
        {
          label: "请选择县（区）"
        }
      ]
      stepListData[0].city = arr;
      stepListData[0].country = countryData;
      stepListData[0].region = [];
      this.setState({stepListData, cityValue: item, activeSteps: "3"}, () => {
        this.getCountrySelectData(this.state.cityValue)
      })
    } else if (activeSteps === "3") {
      let regionData = [
        {
          label: "请选择镇（街道）"
        }
      ]
      stepListData[0].country = arr;
      stepListData[0].region = regionData
      this.setState({stepListData, countryValue: item, activeSteps: "4"}, () => {
        this.getRegionSelectData(this.state.countryValue)
        if (selectType==="native" || selectType==="birth"){
          this.props.addressBoxAssignment(selectType); // 关闭弹窗
        }
      })
    } else if (activeSteps === "4") {
      stepListData[0].region = arr;
      this.setState({stepListData, regionValue: item}, () => {
        this.props.addressBoxAssignment(selectType); // 关闭弹窗
      })
    }
  }

  handleStepsChildClick = (item, index) => {
    let {stepListData} = this.state;
    if (String(index) === "0") {
      let provData = [
        {
          label: "请选择省"
        }
      ]
      stepListData[0].prov = provData;
      stepListData[0].city = [];
      stepListData[0].country = [];
      stepListData[0].region = [];
      this.setState({activeSteps: String(index+1), stepListData, provValue: {}, cityValue: {}, countryValue: {}, regionValue: {}}, () => {
        this.getProvSelectData()
      })
    } else if (String(index) === "1") {
      let cityData = [
          {
            label: "请选择城市"
          }
        ]
      stepListData[0].city = cityData;
      stepListData[0].country = [];
      stepListData[0].region = [];
      this.setState({activeSteps: String(index+1), stepListData, cityValue: {}, countryValue: {}, regionValue: {}}, () => {
        this.getCitySelectData(this.state.provValue)
      })
    } else if (String(index) === "2") {
      let countryData = [
        {
          label: "请选择县（区）"
        }
      ]
      stepListData[0].country = countryData;
      stepListData[0].region = [];
      this.setState({activeSteps: String(index+1), stepListData, countryValue: {}, regionValue: {}}, () => {
        this.getCountrySelectData(this.state.cityValue)
      })
    } else if (String(index) === "3") {
      let regionData = [
        {
          label: "请选择镇（街道）"
        }
      ];
      stepListData[0].region = regionData
      this.setState({activeSteps: String(index+1), stepListData, regionValue: {}}, () => {
        this.getRegionSelectData(this.state.countryValue)
      })
    }
  }

  // 过滤steps数据
  filterStepsData = (arr) => {
    let filterArr = [];
    if (arr&&arr.length > 0) {
      if (arr[0].prov&&arr[0].prov.length > 0) {
        filterArr.push(arr[0].prov[0]);
      } 
      if (arr[0].city&&arr[0].city.length > 0) {
        filterArr.push(arr[0].city[0]);
      }
      if (arr[0].country&&arr[0].country.length > 0) {
        filterArr.push(arr[0].country[0]);
      }
      if (arr[0].region&&arr[0].region.length > 0) {
        filterArr.push(arr[0].region[0]);
      }
    }
    return filterArr
  }

  // 输入省市县街道数据
  exportCitySelectInfo = (type) => {
    let {provValue, cityValue, countryValue, regionValue} = this.state;
    let provTitle = provValue&&provValue.label ? provValue.label : "";
    let cityTitle = cityValue&&cityValue.label ? cityValue.label : "";
    let countryTitle = countryValue&&countryValue.label ? countryValue.label : "";
    let regionTitle = regionValue&&regionValue.label ? regionValue.label : "";
    let addressDesc =  provTitle+"-"+cityTitle+"-"+countryTitle+"-"+regionTitle
    if (type === "descripts") {
      return addressDesc
    } else if (type === "ID") {
      let {provValue, cityValue, countryValue, regionValue} = this.state;
      let provID = provValue&&provValue.value ? provValue.value : "";
      let cityID = cityValue&&cityValue.value ? cityValue.value : "";
      let countryID = countryValue&&countryValue.value ? countryValue.value : "";
      let regionID = regionValue&&regionValue.value ? regionValue.value : "";
      return {
        provID: provID,
        cityID: cityID,
        countryID: countryID,
        regionID: regionID,
        addressDesc
      }
    } else {
      let obj = {};
      obj.provData = provValue;
      obj.cityData = cityValue;
      obj.countryData = countryValue;
      obj.regionData = regionValue;
      obj.addressDesc = addressDesc
      return obj
    }
  }

  render() {
    let {visible, stepListData, provValue, provSelectData, activeSteps, citySelectData, cityValue, countrySelectData, countryValue, regionSelectData, regionValue,selectType} = this.state;
    // 列表操作数据
    let seasonData =selectType && (selectType==="native" || selectType==="birth") ? (activeSteps === "1" ? provSelectData : (activeSteps === "2" ? citySelectData :  countrySelectData)) : (activeSteps === "1" ? provSelectData : (activeSteps === "2" ? citySelectData : (activeSteps === "3" ? countrySelectData : regionSelectData)));
    // 当前选中的value
    let radilValue =selectType && (selectType==="native" || selectType==="birth") ?  (activeSteps === "1" ? provValue : (activeSteps === "2" ? cityValue :  countryValue )) :(activeSteps === "1" ? provValue : (activeSteps === "2" ? cityValue : (activeSteps === "3" ? countryValue : regionValue)));
    return (
      <div>
        <Modal
          popup
          visible={visible}
          title="地址选择"
          onClose={this.handleClose}
          animationType="slide-up"
          closable
          className="address-modal"
        >
          <div>
            <Steps size="small" className="address-steps" style={{borderBottom: "1px solid #eee"}} current={+activeSteps - 1}>
              {this.filterStepsData(stepListData).map((item, index) => {
                return <Step key={index} title={<span className={item.value === (+activeSteps) ? "steps-active" : ""}>{item.label}</span>} icon={<i className="iconfont icon-dian"></i>} onClick={() => this.handleStepsChildClick(item, index)} />
              })}
            </Steps>
            <div className="address-detail">
              <List>
                <p className="list-head">选择区县</p>
                {seasonData.map(item => (
                  <RadioItem key={item.value} checked={radilValue.value === item.value} onChange={() => this.handleRadioChange(item)}>
                    {item.label}
                  </RadioItem>
                ))}
              </List>
            </div>
          </div>
        </Modal>
      </div>
    )
  }
}