import React from 'react';

import { Tabs } from 'antd';
import classNames from 'classnames';
import _ from 'lodash';

import { ChineseDistricts } from '@wisdom-utils/utils';

import styles from './index.less';

const { TabPane } = Tabs;
const PROVINCE = 'province';
const CITY = 'city';
const DISTRICT = 'district';
const PROJECT = 'project';

class CitySelector extends React.Component {
  constructor(props) {
    super(props);
    this.DEFAULTS = {
      simple: false,
      Clickable: {},
      responsive: false,
      placeholder: '请选择省/市/区(包括地级市)',
      level: 'project',
      province: '',
      city: '',
      district: '',
      project: '',
      handEnd() {},
    };

    this.state = {
      currentItem: {},
      cityCurrentItem: {},
      districtCurrentItem: {},
      activeIndex: '1',
    };

    this.$dropdown = null;
    this.options = Object.assign(
      {},
      this.DEFAULTS,
      _.isPlainObject(props.options) ? props.options : {},
    );
    this.active = false;
    this.dems = [];
    this.needBlur = false;
  }

  getProvinceList(data) {
    const { simple } = this.props;
    const pOptions = this.props.Clickable.proviceOption;
    return data.map(item => (
      <dl className="clearfix" key={item.code}>
        <dt>{item.code}</dt>
        <dd>
          {item.address.map(k => {
            let flag = false;
            // eslint-disable-next-line no-plusplus,no-var,vars-on-top
            var j = 0;
            for (j = 0; j < pOptions.length; j++) {
              if (k.address === pOptions[j].proviceName) {
                flag = true;
                break;
              }
            }
            if (flag) {
              return (
                <a
                  title={k.address}
                  key={k.code}
                  className={classNames(
                    styles.clickAble,
                    k.code === this.state.currentItem.code ? styles.active : '',
                  )}
                  onClick={event =>
                    this.selectHandle(
                      event,
                      k,
                      k.code === this.state.currentItem.code,
                    )
                  }
                >
                  {simple ? this.simplize(k.address, PROVINCE) : k.address}
                  {/* eslint-disable-next-line no-undef,block-scoped-var */}
                  <b>{this.symbolNumber(pOptions[j].num)}</b>
                </a>
              );
            }
            return (
              <a title={k.address} key={k.code}>
                {simple ? this.simplize(k.address, PROVINCE) : k.address}
              </a>
            );
          })}
        </dd>
      </dl>
    ));
  }

  getList(data, type, flag) {
    const { simple } = this.props;
    const { cityOption } = this.props.Clickable;
    const { siteOption } = this.props.Clickable;
    const children = [];
    if (type === PROJECT && flag === 'project') {
      const { address } = this.state.districtCurrentItem;
      const arr = siteOption.filter(item => item.city.indexOf(address) > 0);
      return (
        <dl className="clearfix">
          <dd>
            {arr.map(item => (
              <a
                title={item.city}
                className={classNames(
                  styles.clickAble,
                  !item.isDeployed ? styles.noData : '',
                )}
                onClick={event => this.siteHandle(event, item)}
              >
                {item.groupName}
              </a>
            ))}
          </dd>
        </dl>
      );
    }
    return (
      <dl className="clearfix">
        <dd>
          {/* eslint-disable-next-line array-callback-return */}
          {data.map((item, index) => {
            // eslint-disable-next-line no-shadow
            const flag = data.filter(
              // eslint-disable-next-line no-shadow
              item => item.code === this.state.cityCurrentItem.code,
            );
            if (type === DISTRICT && index === 0 && !flag.length) {
              let flag2 = false;
              // eslint-disable-next-line no-plusplus
              for (let h = 0; h < siteOption.length; h++) {
                const arr = siteOption[h].city.split('/');
                const lastValue = arr[arr.length - 1];
                if (
                  lastValue.indexOf(this.state.cityCurrentItem.address) > -1
                ) {
                  flag2 = true;
                  break;
                }
              }

              if (!flag2) {
                children.push(
                  <a
                    title={this.state.cityCurrentItem.address}
                    datacode={this.state.cityCurrentItem.code}
                  >
                    {simple
                      ? this.simplize(this.state.cityCurrentItem.address, type)
                      : this.state.cityCurrentItem.address}
                  </a>,
                );
              } else {
                children.push(
                  <a
                    title={this.state.cityCurrentItem.address}
                    className={classNames(
                      styles.clickAble,
                      item.code === this.state.districtCurrentItem.code
                        ? styles.active
                        : '',
                    )}
                    onClick={event =>
                      this.districtHandle(event, this.state.cityCurrentItem)
                    }
                  >
                    {simple
                      ? this.simplize(this.state.cityCurrentItem.address, type)
                      : this.state.cityCurrentItem.address}
                  </a>,
                );
              }
            }
            if (type === CITY) {
              // eslint-disable-next-line no-shadow
              let flag = false;
              // eslint-disable-next-line no-var,no-plusplus
              for (var j = 0; j < cityOption.length; j++) {
                if (item.address === cityOption[j].proviceName) {
                  flag = true;
                  break;
                }
              }
              if (flag) {
                children.push(
                  <a
                    title={item.address}
                    className={classNames(
                      styles.clickAble,
                      item.code === this.state.cityCurrentItem.code
                        ? styles.active
                        : '',
                    )}
                    onClick={event => this.selectCityHandle(event, item)}
                  >
                    {simple ? this.simplize(item.address, CITY) : item.address}
                    {/* eslint-disable-next-line no-undef */}
                    <b>{this.symbolNumber(cityOption[j].num)}</b>
                  </a>,
                );
              } else {
                children.push(
                  <a>
                    {simple ? this.simplize(item.address, CITY) : item.address}
                  </a>,
                );
              }
            } else {
              let flg1 = false;
              // eslint-disable-next-line no-plusplus
              for (let k = 0; k < siteOption.length; k++) {
                if (siteOption[k].city.indexOf(item.address) > -1) {
                  flg1 = true;
                  break;
                }
              }
              if (flg1) {
                children.push(
                  <a
                    title={item.address}
                    className={classNames(
                      styles.clickAble,
                      item.code === this.state.districtCurrentItem.code
                        ? styles.active
                        : '',
                    )}
                    onClick={event =>
                      type === DISTRICT
                        ? this.districtHandle(event, item, '123')
                        : null
                    }
                  >
                    {simple ? this.simplize(item.address, type) : item.address}
                  </a>,
                );
              } else {
                children.push(
                  <a>
                    {simple ? this.simplize(item.address, type) : item.address}
                  </a>,
                );
              }
            }
          })}
          {children}
        </dd>
      </dl>
    );
  }

  nextTab() {
    // eslint-disable-next-line radix
    let key = parseInt(this.state.activeIndex);
    // eslint-disable-next-line no-plusplus
    key = ++key;
    return key.toString();
  }

  selectHandle = (event, item, status) => {
    event.persist();
    this.setState({
      currentItem: item,
    });
    this.handleChangeTab(this.nextTab());
  };

  handleChangeTab = activeKey => {
    this.setState({
      activeIndex: activeKey,
    });
  };

  selectCityHandle = (event, item, status) => {
    event.persist();

    this.setState({
      cityCurrentItem: item,
    });
    this.handleChangeTab(this.nextTab());
  };

  districtHandle = (event, item, status) => {
    event.persist();
    this.setState({
      districtCurrentItem: item,
    });
    this.handleChangeTab(this.nextTab());
  };

  siteHandle = (event, item) => {
    // eslint-disable-next-line no-unused-expressions
    this.props.handEnd && this.props.handEnd(event, item);
  };

  render() {
    return (
      <Tabs activeKey={this.state.activeIndex} onChange={this.handleChangeTab}>
        <TabPane tab="省份" key="1">
          <div className={styles['city-select-content']}>
            <div className={classNames(styles['city-select'], styles.province)}>
              {this.output(PROVINCE)}
            </div>
          </div>
        </TabPane>
        <TabPane tab="城市" key="2">
          <div className={styles['city-select-content']}>
            <div className={classNames(styles['city-select'], styles.city)}>
              {this.output(CITY)}
            </div>
          </div>
        </TabPane>
        <TabPane tab="区县" key="3">
          <div className={styles['city-select-content']}>
            <div className={classNames(styles['city-select'], styles.city)}>
              {this.output(DISTRICT)}
            </div>
          </div>
        </TabPane>
        <TabPane tab="站点" key="4">
          <div className={styles['city-select-content']}>
            <div className={classNames(styles['city-select'], styles.city)}>
              {this.output(PROJECT, 'project')}
            </div>
          </div>
        </TabPane>
      </Tabs>
    );
  }

  refresh() {}

  defineDems() {
    let stop = false;
    // eslint-disable-next-line array-callback-return
    [PROVINCE, CITY, DISTRICT, PROJECT].map(item => {
      if (stop) {
        this.dems.push(item);
      }
      // eslint-disable-next-line no-undef
      if (type === this.options.level) {
        stop = true;
      }
    });
  }

  includeDem(type) {
    return this.dems.findIndex(item => item === type) !== -1;
  }

  componentDidMount() {
    this.output();
  }

  /* eslint-disable */
  output(type = PROVINCE, flag) {
    const data = [];

    const code =
      // eslint-disable-next-line no-nested-ternary
      type === PROVINCE
        ? 86
        : type === CITY
        ? this.state.currentItem.code
        : type === DISTRICT
        ? this.state.cityCurrentItem.code
        : type === PROJECT
        ? this.state.currentItem.code
        : null;
    const districts = ChineseDistricts[code];

    if (_.isPlainObject(districts)) {
      Object.keys(districts).forEach((item, index) => {
        const ret = districts[item];
        data.push({
          code: item,
          address: ret,
        });
      });
    }
    return type === PROVINCE
      ? this.getProvinceList(data)
      : this.getList(data, type, flag);
  }

  // eslint-disable-next-line consistent-return
  simplize(address, type) {
    // eslint-disable-next-line no-param-reassign
    address = address || '';
    if (type === PROVINCE) {
      return address.replace(/[省,市,自治区,壮族,回族,维吾尔]/g, '');
    }
    if (type === CITY) {
      return address
        .replace(
          /[市,地区,回族,蒙古,苗族,白族,傣族,景颇族,藏族,彝族,壮族,傈僳族,布依族,侗族]/g,
          '',
        )
        .replace('哈萨克', '')
        .replace('自治州', '')
        .replace(/自治县/, '');
    }
    if (type === DISTRICT) {
      return address;
    }
  }

  symbolNumber(num) {
    const symbolArr = [
      '①',
      '②',
      '③',
      '④',
      '⑤',
      '⑥',
      '⑦',
      '⑧',
      '⑨',
      '⑩',
      '⑪',
      '⑫',
      '⑬',
      '⑭',
      '⑮',
      '⑯',
      '⑰',
      '⑱',
      '⑲',
      '⑳',
      '㉑',
      '㉒',
      '㉓',
      '㉔',
      '㉕',
      '㉖',
      '㉗',
      '㉘',
      '㉙',
      '㉚',
      '㉛',
      '㉜',
      '㉝',
      '㉞',
      '㉟',
      '㊱',
      '㊲',
      '㊳',
      '㊴',
      '㊵',
      '㊶',
      '㊷',
      '㊸',
      '㊹',
      '㊺',
      '㊻',
      '㊼',
      '㊽',
      '㊾',
      '㊿',
    ];
    return symbolArr[num - 1];
  }
}

export default CitySelector;
