import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'dva';
// import style from "styled-components";
// import {Tabs, Select} from 'antd';
import {Cascader} from 'antd';
import {
  getDistrictData
} from "../../services/api";
import {cascaderCacheData} from '../../common/dataCache';

const {cascaderGetData, cascaderSetData, writeSetData, writeGetData, subscribe} = cascaderCacheData();
/**w
 *
 * @desc    基于 antd Cascader 组件封装
 *          注入单位内部使用的地区级联数据
 * @param   {func} addressChange(data)  组件初始化结束，以及地区 change 事件时候，都会返回详细的 中文地区结果
 * @return
 */



export default class PCascader extends PureComponent {
  state = {
    dataSource: [],
    provinceValue:[]
  };

  static propTypes = {
    addressChange: PropTypes.func,
  }


  /******************************生命周期******************************/

  componentDidMount = () => {
    this.getDistrictData();
  }

  componentWillReceiveProps = (nextProps, newState) => {
    if(nextProps.provinceValue!==this.state.provinceValue){
      this.setState({
        provinceValue:nextProps.provinceValue
      })
      this.numToAddress1(nextProps.provinceValue)
    }
  }
  //数值转地址（可用）传[110000, 110100, 110101] 转 "北京市市辖区东城区",通过changeNumToAddress事件把地址返回回去
  numToAddress1(numValue){
    if (Object.prototype.toString.call(numValue) !== "[object Array]") {
      return '';
    }
    const {dataSource} = this.state;
    if (dataSource.length === 0) {
      return "";
    }
    let provinceLabel=''
    let data=JSON.parse(JSON.stringify(dataSource))
    for(let i =0;i<numValue.length;i++){
        data.map(item=>{
          if(numValue[i]===item.value){
            provinceLabel=provinceLabel+item.label
            data= item.children
          }
        })
    }
    this.props.changeNumToAddress(provinceLabel)
  }

  //数值转 地址详情
  numToAddress = (areaCode = []) => {
    if (Object.prototype.toString.call(areaCode) !== "[object Array]") {
      return;
    }

    const {dataSource} = this.state;

    if (dataSource.length === 0) {
      return "";
    }
    const dataStr = JSON.stringify(dataSource);

    const valueFindLabel = (acc, item) => {
      dataStr.replace(new RegExp(`{"value":${item},"label":"(.*?)"`, 'g'), (match, p1) => {
        acc += p1;
      });
      return acc;
    }

    const addressDetail = areaCode.reduce(valueFindLabel, "");

    const {addressChange} = this.props;

    addressChange && addressChange(addressDetail);
  }

  onChange = (value, selectedOptions) => {
    const {onChange = false} = this.props;
    if (onChange) {
      onChange(value, selectedOptions);
    }
    this.numToAddress(value);
  }
  /******************************ajax请求******************************/
    //获取地区级联
  getDistrictData = () => {

    const cascaderData = cascaderGetData();

    if (cascaderData.length !== 0) {//取出之前存储的结果
      this.setState({dataSource: cascaderData});
      this.changeNumToDetailAddress(this.props);
      return;
    }

    if (writeGetData()) {
      const awitEvent = (dataSource) => this.setState({dataSource});
      subscribe(awitEvent);//订阅事件
      return;
    }

    //迭代自身，判断是否有子元素,转化为antd需要的数据结构
    const changeObj = data => {
      let areas = JSON.parse(JSON.stringify(data));
      areas && areas.map(({regionId, regionName, childs}, key) => {
        areas[key] = {
          value: regionId,
          label: regionName,
          children: childs,
        };
        if (areas[key].children.length !== 0) {
          areas[key].children = changeObj(childs);
        } else {
          delete  areas[key].children;
        }
      });
      return areas;
    }

    writeSetData();

    getDistrictData().then(
      ({data}) => {
        this.setState({dataSource: changeObj(data)});
        cascaderSetData(changeObj(data));//存储结果
        this.changeNumToDetailAddress(this.props);
      },
      (err) => {
        console.log(err);
      }
    );
  }

  //把省市区 转换为详细地址 。例如 [110000, 110100, 110101] 转 "北京市市辖区东城区",暂不支持
  changeNumToDetailAddress = (props) => {
    const {defaultValue = false, value = false} = props;
    if (defaultValue) {
      this.numToAddress(defaultValue);
    } else {
      this.numToAddress(value);
    }
  }

  render() {
    const props = {...this.props};
    if (props.addressChange) {
      delete props.addressChange
    }
    return (
      <Cascader
        {...props}
        {...{options: this.state.dataSource, onChange: this.onChange}}
      />
    );
  }
}
