import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import Header from 'components/Header/Header';
import commonTool from 'utils/commonTool.js';
import { Storage } from 'storage';
import { Toast } from 'antd-mobile';
import SortableList from './SortableVerticalList';
import './view.scss';
import { rateCodeKey } from './config';

const EditInterestCode = class extends Component {
  constructor(props) {
    super(props);
    const rateCode = this.initRateCode();
    let interestCode = rateCode.interestCode;
    if (!interestCode) {
      interestCode = [];
    } else {
      interestCode = interestCode.split(',');
    }
    this.state = {
      interestCode,
      allCode: rateCode.allCode.split(','),
    };
  }

  // 排序结束渲染
  onSortEnd(items) {
    commonTool.gtjaBurialPoint('293027');
    const interTemp = this.state.interestCode.join(',').split(',');
    const interSortRate = [];
    for (let i = 0; i < items.length; i++) {
      for (let j = 0; j < interTemp.length; j++) {
        if (interTemp[j] === items[i]) {
          interSortRate.push(interTemp[j]);
        }
      }
    }
    this.setState({ allCode: items, interestCode: interSortRate });
  }

  /**
   * 更改货币对Storage
   */
  setCodeStorage() {
    if (this.state.interestCode.join(',') === '') {
      Toast.info('温馨提示：请选择您关注的货币对！', 1);
      return false;
    }
    Storage.setItem(rateCodeKey, {
      allCode: this.state.allCode.join(','),
      interestCode: this.state.interestCode.join(','),
    });
    console.error(Storage.getItem('eraytRateCode'));
    window.history.back();
  }

  /**
   * 保存编辑
   */
  saveEdit() {
    commonTool.gtjaBurialPoint('293028');
    this.setCodeStorage();
  }

  /**
   * 跳转到 添加交易货币页
   */
  goAddCode() {
    const path = {
      pathname: '/AddTradeCode',
    };
    this.props.history.push(path);
  }

  /**
   * 改变单列选中
   */
  changeItemDisplay(val) {
    const index = this.state.interestCode.indexOf(val);
    const allIndex = this.state.allCode.indexOf(val);
    this.state.allCode.splice(allIndex, 1);
    if (index !== -1) {
      this.state.interestCode.splice(index, 1);
      this.state.allCode.push(val);
    } else {
      this.state.interestCode.push(val);
      this.state.allCode.splice(this.state.interestCode.length - 1, 0, val);
    }
    this.setState({
      interestCode: this.state.interestCode,
      allCode: this.state.allCode,
    });
  }

  initRateCode() {
    let rateCode = Storage.getItem(rateCodeKey, true);
    if (!rateCode) {
      rateCode = {
        allCode: this.props.allCode,
        interestCode: '',
        // allCode:
        // 'AUD/USD,EUR/USD,GBP/USD,USD/CAD,USD/CHF,USD/JPY,GBP/JPY,GBP/AUD,GBP/CNY',
      };
    }
    rateCode.allCode = this.props.allCode;
    if (rateCode.interestCode) {
      const interestCodeArr = rateCode.interestCode.split(',');
      const allCodeArr = rateCode.allCode.split(',');
      interestCodeArr.map((value, index) => {
        if (allCodeArr.includes(value)) {
          const allCodeArrIndex = allCodeArr.indexOf(value);
          allCodeArr.splice(allCodeArrIndex, 1);
        }
        allCodeArr.splice(index, 0, value);
        return '';
      });
      rateCode.allCode = allCodeArr.join(',');
    } else {
      rateCode.interestCode = rateCode.allCode;
    }
    Storage.setItem(rateCodeKey, rateCode);

    return rateCode;
  }

  /**
   * 全选操作
   */
  handleAllSel() {
    if (this.state.interestCode.length === this.state.allCode.length) {
      this.state.interestCode = [];
    } else {
      this.state.interestCode = this.state.allCode.join(',').split(',');
    }
    this.setState({ interestCode: this.state.interestCode });
  }

  render() {
    return (
      <div id="editInterestCode">
        <Header>
          编辑
          <span
            className="del"
            onClick={() => {
              this.saveEdit();
            }}
          >保存
          </span>
        </Header>
        <div className="explain-text">
          <div
            className="banner"
            onClick={() => {
              this.handleAllSel();
            }}
          >
            <span
              className={(this.state.interestCode.length === this.state.allCode.length)
                ? 'waitSelIcon selIcon'
                : 'waitSelIcon'}
            />
            <span>全展示</span>
          </div>
          <span
            style={{
              width: '45%',
              textAlign: 'left',
            }}
          >货币对
          </span>
          <span style={{ width: '15%', textAlign: 'center' }}>置顶</span>
          <span style={{ width: '15%', textAlign: 'center' }}>拖动</span>
        </div>
        <SortableList
          items={this.state.interestCode}
          allCode={this.state.allCode}
          changeItemDisplay={(index) => {
            this.changeItemDisplay(index);
          }}
          onSortEnd={(item) => {
            this.onSortEnd(item);
          }}
        />
      </div>
    );
  }
};

const mapStateToProps = (state) => {
  const { firmQuotation } = state;
  const { priceObject } = firmQuotation.firm || {
    priceObject: {},
  };
  return {
    allCode: Object.keys(priceObject).join(','),
  };
};

export default withRouter(connect(mapStateToProps)(EditInterestCode));
