/* eslint-disable */
import React, { Component } from 'react';
import { Affix, Table, Checkbox, Input, Select, message, Tabs, Alert } from 'antd-v4';
import styles from '@/index.less';
import lodash from 'lodash';
import * as commonUtils from '@/utils/utils';
import config from '@/utils/config';
import * as commonFunc from '@/components/Common/commonFunc';
import AntdDraggableModal from '@/components/Common/AntdDraggableModal';
import SvgIcon from '../SvgIcon';

const { Option } = Select;
const { TabPane } = Tabs;

class AffixMenuComponent extends Component {
  constructor(props) {
    super(props);
    const UserPersonalization = commonFunc.showMessage(props.app.commonConst, 'UserPersonalization');/* 用户个性化配置 */
    this.state = {
      top: 10,
      modalPanel: { title: UserPersonalization },
      modalVisible: false,
      modalData: [],
      modalContent: [], /* 面板展示内容 */
      modalContentData1: [],
      modalContentData2: [],
      modalContentData3: [],
      modalContentData4: [],
      modalContentData5: [],
      modalContentData6: [],
      modalContentData7: [],
      modalContentData8: [],
      modalContentData9: [],
      modalContentData10: [],
      roleShow: '', /* 角色 */
      roleSelectData: '', /* 选择的角色 */
    };
  }

  onInit() {
    const sActiveId = this.props.app.currentPane.formId;
    const { formSrcRoute } = this.props;
    const url = `${config.server_host}configform/getConfigformData/${sActiveId}?sModelsId=${sActiveId}&sName=${formSrcRoute}`;
    const { token } = this.props.app;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };

    const originData = {};
     fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const data = json.dataset.rows[0];
        this.setState({ modalData: data });
        Object.keys(data).forEach((child) => {
          const spitArr = commonUtils.isNotEmptyObject(child) ? child.split('_') : [];
          /* 数据增加key属性用于table展示 */
          for (const item of data[child]) {
            item.key = item.sId;
          }
          originData[`modalContentData_${spitArr[1]}`] = data[child];
        });
        this.setState({ ...originData }, () => { this.handleClick(); });
      } else {
        // console.log(json.msg);
      }
    });
    if (this.props.app.userinfo.sType === 'sysadmin') {
      const chooseRole = commonFunc.showMessage(this.props.app.commonConst, 'chooseRole');/* 选择角色 */
      const chooseOneRole = commonFunc.showMessage(this.props.app.commonConst, 'chooseOneRole');/* 请选择一个角色 */
      const roleUrl = `${config.server_host}configform/getLogininfosupplygroup?sModelsId=${sActiveId}&sName=${formSrcRoute}`;
      /* 获取角色下拉 */
      fetch(roleUrl, options).then(response => response.json()).then((json) => {
        if (json.code === 1) {
          const data = json.dataset.rows;
          const oPtinon = [];
          for (const child of data) {
            oPtinon.push(<Option key={child.sId} value={child.sId}>{child.sName}</Option>);
          }
          const roleShow = (
            <Alert
              message={(
                <div className={styles.affixMenuShow}>
                  <span>{chooseRole}</span>
                  <Select
                    style={{ width: 'calc(100% - 58px)' }}
                    filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    onChange={e => this.handleSelectChange(e)}
                    placeholder={chooseOneRole}
                  >
                    {oPtinon}
                  </Select>
                </div>

              )}
              type="info"
              showIcon
            />
          );
          this.setState({ roleShow });
        } else {
          // console.log(json.msg);
        }
      });
    }
  }

  onCheckChange = (e) => {
    this.setState({
      indeterminate: false,
      checkValue: e.target.checked ? true : '',
    });
  };

  onCheckAll = (e, name, count, configId) => {
    const data = JSON.parse(JSON.stringify(this.state.modalData[name] || []));
    const temp = JSON.parse(JSON.stringify(this.state[`modalContentData${count}`] || []));
    const config = JSON.parse(JSON.stringify(this.state[`modalContentData_${configId}`] || []));
    data.forEach((item, idx) => {
      data[idx].bVisible = e.target.checked;
    });
    temp.forEach((item, idx) => {
      temp[idx].bVisible = e.target.checked;
    });
    config.forEach((item, idx) => {
      config[idx].bVisible = e.target.checked;
    });
    this.setState({
      modalData: { ...this.state.modalData, [name]: data },
      [`modalContentData${count}`]: temp,
      [`modalContentData_${configId}`]: config,
    });
  }

  handleClick=() => {
    const { sModelsId } = this.props;
    const addStateData = {};
    const sessionKeys = Object.keys(sessionStorage); /* 找到配置 */
    for (const key of sessionKeys) { /* 通过缓存中key的name匹配config配置，通过config配置获取配置sId,通过配置sId在state中找到对应的数据集 */
      const keyArr = commonUtils.isNotEmptyObject(key) ? key.split('_') : [];
      if (commonUtils.isNotEmptyArr(keyArr) && sModelsId === keyArr[0]) { /* 防止多页签name名重复导致缓存匹配错误 */
        const tableSid = keyArr[1]; /* 取表名称 */
        if (tableSid) {
          let { [`modalContentData_${tableSid}`]: tableData } = this.state;
          if (addStateData[`modalContentData_${tableSid}`]) {
            tableData = addStateData[`modalContentData_${tableSid}`];
          } else {
            tableData = JSON.parse(JSON.stringify(tableData));
          }

          /* 取缓存中的数据 */
          if (commonUtils.isJSON(sessionStorage[key]) && JSON.parse(sessionStorage[key]).length > 0) {
            const sessionData = JSON.parse(sessionStorage[key]);
            if (commonUtils.isNotEmptyArr(sessionData) && commonUtils.isNotEmptyArr(tableData) && key.indexOf('headerColumns') === -1) {
              tableData.forEach((item, index) => {
                const iIndex = sessionData.findIndex(session => session.dataIndex === item.sName);
                if (iIndex > -1) {
                  const addState = {};
                  if (addState.iFitWidth !== sessionData[iIndex].width) {
                    addState.iFitWidth = sessionData[iIndex].width;
                    tableData[index] = { ...tableData[index], ...addState };
                  }
                }
              });
            }
            if (key === `${sModelsId}_${tableSid}_headerColumns` || key === `${sModelsId}_${tableSid}_info_headerColumns`) {
              const sessionData = JSON.parse(sessionStorage[key]);
              const iOrderSort = tableData.map(item => item.iOrder).sort((a, b) => a - b);
              const obj = {};
              sessionData.forEach((item, idx) => {
                obj[item] = iOrderSort[idx];
              });
              tableData.forEach((item, idx) => {
                tableData[idx].iOrder = obj[item.sName];
              });
              tableData.sort((a, b) => a.iOrder - b.iOrder)
              tableData.forEach((item, idx) => {
                tableData[idx].iOrder = idx + 1;
              })
            }
            addStateData[`modalContentData_${tableSid}`] = tableData;
          }
        }
      }
    }
    this.setState({ ...addStateData });
  };

  handlePpopUpPaneCancel=() => {
    this.setState({ modalVisible: false });
  };

  handleChange=(value, count, record, name) => {
    const data = JSON.parse(JSON.stringify(this.state[`modalContentData_${count}`]));
    const dataMap = data.filter(item => (item.key === record.key))[0];
    if (dataMap !== undefined) {
      dataMap[`${name}`] = value;
    }
    this.setState({ [`modalContentData_${count}`]: data });
  };

  handleSelectChange=(value) => {
    /* 调用接口 */
    const { formSrcRoute } = this.props;
    this.setState({ roleSelectData: value });
    const sActiveId = this.props.app.currentPane.formId;
    const url = `${config.server_host}configform/getConfigformData/${sActiveId}?roleSelectId=${value}&&sModelsId=${sActiveId}&sName=${formSrcRoute}`;
    const { token } = this.props.app;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const data = json.dataset.rows[0];
        this.setState({ modalData: data });
        Object.keys(data).forEach((child) => {
          const spitArr = commonUtils.isNotEmptyObject(child) ? child.split('_') : []; /* 取菜单ID */
          /* 数据增加key属性用于table展示 */
          for (const item of data[child]) {
            item.key = item.sId;
          }
          this.setState({ [`modalContentData_${spitArr[1]}`]: data[child] });
        });
      } else {
        // console.log(json.msg);
      }
    });
  };

  handleOk=() => {
    const { formSrcRoute } = this.props;
    const sActiveId = this.props.app.currentPane.formId;
    const url = `${config.server_host}configform/sHandleConfigform?sModelsId=${sActiveId}&sName=${formSrcRoute}`;
    const { token } = this.props.app;
    const { roleShow, roleSelectData, modalData } = this.state;
    // const pleaseChooseRole = commonFunc.showMessage(this.props.app.commonConst, 'pleaseChooseRole');/* 请选择角色 */
    // if (roleShow !== '' && roleSelectData === '') {
    //   message.warning(pleaseChooseRole);
    //   return;
    // }
    const submitData = {};
    // let count = 1;
    let num = 0;

    Object.keys(modalData).forEach((item) => {
      const splitArr = commonUtils.isNotEmptyObject(item) && commonUtils.isNotEmptyArr(item.split('_')) ? item.split('_') : [];
      const configId = commonUtils.isNotEmptyArr(splitArr) ? splitArr[1] : '';
      const { [`modalContentData_${configId}`]: tableData } = this.state;
      if (commonUtils.isNotEmptyArr(tableData) && tableData.length > 0) {
        num = 0;
        for (const child of tableData) {
          if (num === 0) {
            submitData[`${child.sParentId}`] = [];
          }
          // if (child.bVisible) {
          //   submitData[`${child.sParentId}`].push(child);
          // }
          submitData[`${child.sParentId}`].push(child);
          num += 1;
        }
      }
    });

    let value = '';
    if (roleShow !== '') {
      value = {
        handleType: 'group',
        sJurisdictionClassifyId: roleSelectData,
        handleData: submitData,
        bDefault: commonUtils.isEmpty(roleSelectData) ? true : this.state.checkValue, /* bDefault为true代表更新到后台配置库里 */
      };
    } else {
      value = {
        handleType: 'user',
        handleData: submitData,
      };
    }
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    const { dispatch } = this.props;
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        message.success(json.msg);

        // 清除缓存
        if(sessionStorage !== undefined) {
          const sessionKeys = Object.keys(sessionStorage); /* 找到配置 */
          for (const key of sessionKeys) {
            if(key !== 'feedbackBtnRecord') {
              sessionStorage.removeItem(key);
            }
          }
        }

          this.handlePpopUpPaneCancel();
      } else if (json.code === -2) {
        dispatch({ type: 'app/throwError', payload: json });
      }
    });
  };

  renderColumns=(text, name, count, record) => {
    if (name === 'bVisible' || name === 'bReadonly') {
      return <Checkbox defaultChecked={text} checked={text} onChange={e => this.handleChange(e.target.checked, count, record, name)} />;
    } else {
      let flag = false;
      if (name === 'showName' || name === 'sName') {
        flag = true;
      }
      return <Input value={text} disabled={flag} onChange={e => this.handleChange(e.target.value, count, record, name)} />;
    }
  };

  openModal = () => {
    this.setState({
      modalVisible: true,
    })
    this.onInit();
  }

  render() {
    const { modalData, roleShow } = this.state;
    const { app, sTabId, sModelsType } = this.props;
    // const { userinfo } = app;
    const pane = app.panes.filter(paneTmp => paneTmp.key === sTabId)[0];
    const modalContent = [];
    let count = 1;
    let checkBoxShow = '';
    let checkAll = '';
    const columniOrder = commonFunc.showMessage(app.commonConst, 'columniOrder');/* 排序 */
    const columnShowName = commonFunc.showMessage(app.commonConst, 'columnShowName');/* 显示名 */
    // const columnChinese = commonFunc.showMessage(app.commonConst, 'columnChinese');/* 显示名 */
    // const columnEnglish = commonFunc.showMessage(app.commonConst, 'columnEnglish');/* 显示名 */
    // const columnBig5 = commonFunc.showMessage(app.commonConst, 'columnBig5');/* 显示名 */
    const columniFitWidth = commonFunc.showMessage(app.commonConst, 'columniFitWidth');/* 宽度 */
    const columnbVisible = commonFunc.showMessage(app.commonConst, 'columnbVisible');/* 是否显示 */
    const columnsName = commonFunc.showMessage(app.commonConst, 'columnsName');/* 字段名 */
    const columnsReadOnly = commonFunc.showMessage(app.commonConst, 'columnsReadOnly') || '是否只读';/* 是否自读 */
    const columnsFontColor = commonFunc.showMessage(app.commonConst, 'columnsFontColor') || '字体颜色';/* 字体颜色 */
    const isDefault = commonFunc.showMessage(app.commonConst, 'isDefault');/* 是否设置默认 */
    const BtnSure = commonFunc.showMessage(app.commonConst, 'BtnSure') || '确认';/* 按钮确认 */
    const BtnCancel = commonFunc.showMessage(app.commonConst, 'BtnCancel') || '取消';/* 按钮取消 */
    const selectAll = commonFunc.showMessage(app.commonConst, 'selectAll') || '全选';/* 全选 */
    // eslint-disable-next-line no-unused-vars
    Object.keys(modalData).forEach((child, i) => {
      const splitArr = commonUtils.isNotEmptyObject(child) && commonUtils.isNotEmptyArr(child.split('_')) ? child.split('_') : [];
      const configName = commonUtils.isNotEmptyArr(splitArr) ? splitArr[0] : '';
      const configId = commonUtils.isNotEmptyArr(splitArr) ? splitArr[1] : '';
      let childTable = '';
      let dataSource = [];
      if (commonUtils.isNotEmptyObject(configId)) { /*  从缓存中取宽度 */
        dataSource = this.state[`modalContentData_${configId}`];
      } else {
        dataSource = this.state[`modalContentData${count}`];
      }
      const columns = [{
        title: columniOrder,
        dataIndex: 'iOrder',
        render: (text, record) => this.renderColumns(text, 'iOrder', configId, record),
        width: 40,
      }, {
        title: columniFitWidth,
        dataIndex: 'iFitWidth',
        render: (text, record) => this.renderColumns(text, 'iFitWidth', configId, record),
        width: 40,
      }, {
        title: columnShowName,
        dataIndex: 'showName',
        render: (text, record) => this.renderColumns(text, 'showName', configId, record),
        width: 100,
      }];
      if (this.props.app.userinfo.sType === 'sysadmin' || true) { /* 管理员显示字段名 */
        columns.push({
          title: columnsName,
          dataIndex: 'sName',
          render: (text, record) => this.renderColumns(text, 'sName', configId, record),
          width: 80,
        });
      }
      if (this.props.app.userinfo.sType === 'sysadmin' || true) { /* 管理员设置列是否显示 */
        columns.push({
          title: columnbVisible,
          dataIndex: 'bVisible',
          render: (text, record) => this.renderColumns(text, 'bVisible', configId, record),
          width: 80,
        });
      }
      if (this.props.app.userinfo.sType === 'sysadmin') { /* 配置选择框 */
        // checkBoxShow = <span>{isDefault}&nbsp;&nbsp;<Checkbox defaultChecked={false} onChange={this.onCheckChange} /></span>;
        checkBoxShow = '';
        let visible = 0;
        const len = dataSource ? dataSource.length : 0;
        for (let i = 0; i < len; i += 1) {
          if (dataSource[i].bVisible) {
            visible += 1;
          }
        }
        checkAll = <span>{selectAll}&nbsp;&nbsp;<Checkbox indeterminate={visible !== len && visible} defaultChecked={visible === len} onChange={e => this.onCheckAll(e, child, count, configId)} /></span>;
      }
      if (this.props.app.userinfo.sType === 'sysadmin' || true) { /* 管理员设置列是否可修改 */
        columns.push({
          title: columnsReadOnly,
          dataIndex: 'bReadonly',
          render: (text, record) => this.renderColumns(text, 'bReadonly', configId, record),
          width: 80,
        });
      }
      if (this.props.app.userinfo.sType === 'sysadmin' || true) { /* 管理员设置列颜色 */
        columns.push({
          title: columnsFontColor,
          dataIndex: 'sFontColor',
          render: (text, record) => this.renderColumns(text, 'sFontColor', configId, record),
          width: 80,
        });
      }

      /* 动态列解析 将字段表头换成 动态列返的 */
      // if (!(commonUtils.isNotEmptyObject(sModelsType) && !sModelsType.includes('dynamicList'))) {
      //   const { slaveConfig } = this.props;
      //   const columnConfig = commonUtils.isNotEmptyObject(slaveConfig) ? slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '' && item.showName !== '' && !(item.sControlName !== '' && item.sControlName.indexOf('Btn') > -1)) : [];
      //   /* 动态列 需要将中文名称替换掉 */
      //   if (commonUtils.isNotEmptyArr(columnConfig) && dataSource && dataSource.length === columnConfig.length) {
      //     columnConfig.forEach((item, iIndex) => {
      //       // dataSource[iIndex].sName = item.sName;
      //       dataSource[iIndex].showName = item.showName;
      //       dataSource[iIndex].sChinese = item.sChinese;
      //     });
      //   }
      // }

      const dataSource_dep = lodash.cloneDeep(dataSource);
      if (dataSource_dep && dataSource_dep.length) {
        let min = 0;
        for (let i = 0; i < dataSource_dep.length - 1; i += 1) {
          min = i;
          for (let j = i + 1; j < dataSource_dep.length; j += 1) {
            if (Number(dataSource_dep[min].iOrder) > Number(dataSource_dep[j].iOrder)) {
              const temp = dataSource_dep[min];
              dataSource_dep[min] = dataSource_dep[j];
              dataSource_dep[j] = temp;
            }
          }
        }
      }

      childTable = (
        <TabPane tab={configName} key={count}>
          <div key={count} className={styles.affixMenuTableAll}>
            {checkBoxShow}
            &nbsp;&nbsp;&nbsp;
            {checkAll}
            <Table
              bordered
              columns={columns}
              dataSource={dataSource_dep}
              pagination={false}
              scroll={{ y: 310 }}
              className={styles.affixMenuTable}
            />
          </div>
        </TabPane>
      );
      modalContent.push(childTable);
      count += 1;
    });
    return (
      <div>
        <Affix offsetTop={this.state.top} style={{ position: 'absolute', top: 50, left: 1000 }}>
          <div className={styles.affixMenu}>
            <SvgIcon iconClass="setting" fill="#fff" size="16" onClick={this.openModal.bind(this)} />
            {(pane?.notCurrentPane ? false : this.state.modalVisible) ?
              <AntdDraggableModal
                title={Object.keys(this.state.modalPanel).length > 0 ? this.state.modalPanel.title : ''}
                visible={pane?.notCurrentPane ? false : this.state.modalVisible}
                onCancel={this.handlePpopUpPaneCancel.bind(this)}
                onOk={this.handleOk.bind(this)}
                width={1000}
                okText={BtnSure}
                cancelText={BtnCancel}
              >
                <div className={styles.modalsContent}>
                  {
                    roleShow !== '' ? roleShow : ''
                  }
                  <div id="slaveTabs">
                    <Tabs className={styles.slaveTabs}>
                      {modalContent}
                    </Tabs>
                  </div>
                </div>
              </AntdDraggableModal>
              : ''}
          </div>
        </Affix>
      </div>
    );
  }
}

export default AffixMenuComponent;
