/* eslint-disable array-callback-return,no-undef,prefer-destructuring */
import React, { Component } from 'react';
import { Modal } from 'antd-mobile-v2';
import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import * as commonBusiness from '../../components/Common/commonBusiness';

const alert = Modal.alert;

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {
      };
    }
    componentWillReceiveProps(nextProps) {
      const {
        formData, sModelsId, searchSolution, masterData,
      } = nextProps;
      const { slaveConfig: slaveConfigOld } = nextProps;
      if (commonUtils.isEmptyObject(slaveConfigOld) && formData.length > 0) {
        const sId = sModelsId !== undefined ? sModelsId : '';
        /* 数据Id */
        const slaveConfig = formData[0];
        // console.log('form', formData);
        let filterCondition = [];
        if (commonUtils.isNotEmptyObject(masterData) && !commonUtils.isEmpty(masterData.sSearchSolutionId) && commonUtils.isNotEmptyArr(searchSolution)) {
          const iIndex = searchSolution.findIndex(item => item.sId === masterData.sSearchSolutionId);
          if (iIndex > -1 && !commonUtils.isEmpty(searchSolution[iIndex].sCondition)) {
            filterCondition = JSON.parse(searchSolution[iIndex].sCondition);
          }
        }
        this.handleGetData(slaveConfig, filterCondition, 1);
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnFirst', sControlName: 'BtnFirst',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnPrior', sControlName: 'BtnPrior',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnNext', sControlName: 'BtnNext',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnLast', sControlName: 'BtnLast',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnExamine', sControlName: 'BtnExamine',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnCancelExamine', sControlName: 'BtnCancelExamine',
        });

        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnUpCheck', sControlName: 'BtnUpCheck',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnDownCheck', sControlName: 'BtnDownCheck',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnCopyTo', sControlName: 'BtnCopyTo',
        });
        slaveConfig.gdsconfigformslave.push({
          sId: commonUtils.createSid(), bVisible: false, sName: '', showName: 'BtnCopyFrom', sControlName: 'BtnCopyFrom',
        });
        this.props.onSaveState({
          masterConfig: slaveConfig, slaveConfig, sId, pageLoading: false,
        });
      }
      if (commonUtils.isEmptyStr(this.props.sClomunType) && commonUtils.isNotEmptyObject(this.props.masterConfig)) {
        const { sTbName } = this.props.masterConfig;
        if (sTbName === 'cahsupplyinit' || sTbName === 'cahcustomerinit' || sTbName === 'cahcashierinit') {
          this.handleGetPeriod();
        }
      }
    }

    shouldComponentUpdate(nextProps) {
      const { masterConfig } = nextProps;
      return commonUtils.isNotEmptyArr(masterConfig);
    }
    componentDidUpdate() {
      const { app, slaveData } = this.props;
      const { currentPane } = app;
      if (currentPane.classifyOption === 'add' && slaveData !== undefined) {
        currentPane.classifyOption = '';
        this.handleAdd();
        this.props.onSaveState({ currentPane });
      }
    }

    componentWillUnmount() {
      const { sModelsId } = this.props;
      const { userinfo } = this.props.app;
      this.props.handleSendSocketMessage('release', 'noAction', sModelsId, userinfo.sId, null, null);
    }

    /**   获取表数据   */
    handleGetData = (slaveConfig, slaveFilterCondition, page, slaveOrderBy) => {
      const { app } = this.props;
      const conditonValues = app.currentPane.conditonValues;
      const pageNum = commonUtils.isEmpty(page) ? 1 : page;
      // console.log('slaveConfig', slaveConfig);
      // console.log('pageNum', pageNum);
      // console.log('slaveFilterCondition', slaveFilterCondition);
      this.props.handleGetDataSet({
        name: 'slave',
        configData: slaveConfig,
        condition: {
          pageNum, bFilter: slaveFilterCondition, sFilterOrderBy: slaveOrderBy, sSqlCondition: conditonValues,
        },
      });
    };

    handlePaginationChange = (page) => {
      const { slaveConfig, slaveFilterCondition } = this.props;
      this.props.handleGetDataSet({
        name: 'slave', configData: slaveConfig, condition: { pageNum: page, bFilter: slaveFilterCondition },
      });
    };
    /*   取消操作  */
    handleCancel = () => {
      /*   待用数据声明   */
      const {
        sModelsId, slaveConfig, slaveFilterCondition, slavePagination, slaveOrderBy, app,
      } = this.props;
      const { userinfo } = app;
      const onSendSocketMessage = this.props.handleSendSocketMessage;
      const onGetDataOk = this.handleGetData;
      const onSaveStateOk = this.props.onSaveState;
      alert('Warn', '确定要取消', [
        {
          text: 'Ok',
          onPress: () => {
            onGetDataOk(slaveConfig, slaveFilterCondition, slavePagination.current, slaveOrderBy);
            onSaveStateOk({ enabled: false });
            onSendSocketMessage('release', 'noAction', sModelsId, userinfo.sId, null, null);
          },
        },
        { text: 'Cancel' },
      ]);
    };
    /**   点击修改按钮操作   */
    handleEdit = () => {
      const {
        sModelsId, slaveConfig, slaveFilterCondition, slavePagination, slaveOrderBy, app,
      } = this.props;
      const { userinfo } = app;
      this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, slaveOrderBy);
      this.props.app.webSocket.onmessageTmp = (msg) => {
        const rtmsg = JSON.parse(msg.data);
        if (rtmsg.action === 'showMsg') {
          message.warning(rtmsg.msg);
          this.props.onSaveState({ loading: false });
        }
        this.props.onSaveState({ enabled: true, loading: false });
      };
      this.props.handleSendSocketMessage('update', 'showMsg', sModelsId, userinfo.sId, null, null); // 分类型不能以Id来，涉及到多条修改
    };
    /**   点击新增按钮操作   */
    handleAdd = () => {
      const { sModelsType } = this.props;
      let { slaveSelectedRowKeys } = this.props;
      let { slaveData } = this.props;
      if (slaveData === undefined) {
        slaveData = [];
      }
      const newData = this.props.onDataRowAdd('slave', true);/* 调用父级新增 */
      // const newData = {
      //   handleType: 'add',
      //   sId: commonUtils.createSid(),
      //   iOrder: slaveData.length,
      // };
      if (sModelsType === 'commonClassfiy/sisPosition') {
        newData.maxBillNo = 'sNo';
      }
      if (commonUtils.isEmptyArr(slaveSelectedRowKeys)) { /* 通用分类新增，默认新增行为选中行 */
        slaveSelectedRowKeys = [];
        slaveSelectedRowKeys.push(newData.sId);
      }
      this.props.onSaveState({
        slaveData: [newData, ...slaveData],
        slaveSelectedRowKeys,
        enabled: true,
      });
    };
    /* 删除 */
    handleDel = () => {
      const onOkDel = this.handleOkDel;
      alert('Warn', '确定要删除', [
        {
          text: 'Ok',
          onPress: () => {
            onOkDel();
          },
        },
        { text: 'Cancel' },
      ]);
    };
    handleOkDel = async () => {
      const returnData = await this.handleTableDel('slave');
      if (returnData) {
        this.handleValidateSave();
      }
    };
    handleTableDel = (name, isWait) => {
      const { app } = this.props;
      const { [`${name}Data`]: tableData, [`${name}SelectedRowKeys`]: tableSelectedRowKeys } = this.props;
      let { [`${name}DelData`]: tableDelData } = this.props;
      tableDelData = commonUtils.isEmptyArr(tableDelData) ? [] : tableDelData;
      if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) {
        for (const sId of tableSelectedRowKeys) {
          /*   看看删除集合和从表中是否都存在该条数据   */
          const tableDataIndex = tableData.findIndex(item => item.sId === sId);
          if (tableDataIndex > -1) {
            /*   删除从表中的数据并存入删除集合中   */
            const slaveDataFilter = tableData[tableDataIndex];
            slaveDataFilter.handleType = 'del';
            tableDelData.push(slaveDataFilter);
          }
        }
        if (isWait) {
          return { [`${name}Data`]: tableData, [`${name}DelData`]: tableDelData, [`${name}SelectedRowKeys`]: [] };
        } else {
          this.props.onSaveState({
            [`${name}Data`]: tableData,
            [`${name}DelData`]: tableDelData,
            [`${name}SelectedRowKeys`]: [],
          });
          return true;
        }
      } else {
        message.warn(commonFunc.showMessage(app.commonConst, 'pleaseChooseDelData')); // 请选择删除数据
        return false;
      }
    };
    /**   toolbar校验保存   */
    handleValidateSave = async () => {
      const {
        slaveData, slaveConfig, slaveDelData,
      } = this.props;
      const data = [];
      if (!commonBusiness.validateTable(slaveConfig, slaveData, this.props)) {
        this.props.onSaveState({
          loading: false,
        });
        return;
      }
      data.push(commonBusiness.mergeData('slave', slaveConfig.sTbName, slaveData, slaveDelData));
      // console.log('slaveData', slaveData);
      // console.log('slaveDelData', slaveDelData);
      // console.log('data', data);
      this.handleSaveData({ data, sClientType: '1' });
    };
    /**   toolbar保存   */
    handleSaveData = async (params) => {
      const {
        token, sModelsId, slaveFilterCondition, slaveConfig, slavePagination, slaveOrderBy, app, slaveData,
      } = this.props;
      const { userinfo } = app;
      const onSendSocketMessage = this.props.handleSendSocketMessage;
      const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
      if (commonUtils.isNotEmptyObject(returnData)) {
        commonUtils.clearStoreDropDownData();
        /* 新记录时，关闭后能自动带值  */
        const callBackRecord = this.props.app.currentPane.newRecordMethod;
        if (callBackRecord !== undefined && commonUtils.isNotEmptyArr(slaveData) && slaveData.length > 0) {
          const filterData = slaveData.filter(item => (item.handleType === 'add'));
          const sId = commonUtils.isNotEmptyArr(filterData) && filterData.length > 0 ? filterData[0].sId : null;
          /* 回调 传[新增的数据sId] */
          if (this.props.app.currentPane.newRecordMethod !== undefined) {
            this.props.app.currentPane.newRecordMethod(sId);
          }
        }
        /* END  */
        onSendSocketMessage('release', 'noAction', sModelsId, userinfo.sId, null, null);
        this.props.onSaveState({
          enabled: false, slaveDelData: [], loading: false,
        });
        this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, slaveOrderBy);
        return true;
      } else {
        this.props.onSaveState({
          slaveDelData: [],
          loading: false,
        });
        return false;
      }
    };
    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };
    /* 作废、取消作废的公用函数 */
    handleInvalid = (obj) => {
      const props = { ...this.props, ...this.state, ...obj };
      const onOkInvaild = this.handleOkChangeInvaild;
      alert('Warn', obj.title, [
        {
          text: 'Ok',
          onPress: () => {
            onOkInvaild(props);
          },
        },
        { text: 'Cancel' },
      ]);
    };
    /* 切换作废状态 */
    handleOkChangeInvaild = async (props) => {
      props = this.handleOkInvalid(props);
      this.setState({ ...props });
    };
    /** 作废，取消作废 */
    handleOkInvalid = async (props) => {
      const {
        sModelsId, slaveData, slaveConfig, handleType, slaveSelectedRowKeys, app, slavePagination,
      } = props;
      if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
        const { token } = props.app;
        const { sTbName } = slaveConfig;
        const value = {
          sClientType: '1',
          sId: slaveSelectedRowKeys,
          sTableName: sTbName,
          handleType,
          sBooleanCheck: false,
        };
        const url = `${commonConfig.server_host}checkModel/updatebInvalid?sModelsId=${sModelsId}`;
        const { data } = await commonServices.postValueService(token, value, url);
        if (data.code === 1) {
          message.success(data.msg);
          for (const key of slaveSelectedRowKeys) {
            const selectData = slaveData.filter(item => item.sId === key);
            selectData.bInvalid = handleType === 'toVoid';
          }
          /*  作废(取消作废)后刷新页面 */
          this.handlePaginationChange(slavePagination.current);
        } else {
          this.props.getServiceError(data);
        }
        return props;
      } else {
        message.warn(commonFunc.showMessage(app.commonConst, 'sChoosebInvalid'));/* 请选择作废数据 */
      }
    };
    /** 按钮操作事件 */
    handleButtonClick = (name) => {
      if (name === 'BtnOut') {
        this.handleOut();
      } else if (name === 'BtnRefresh') {
        const { slavePagination } = this.props;
        this.handlePaginationChange(slavePagination.current);
      } else if (name === 'BtnSetPeriod') {
        this.handleBtnSetPeriod();
      } else if (name === 'BtnRelievePeriod') {
        this.handleBtnRelievePeriod();
      }
    };
    /* 导出Excel */
    handleOut = () => {
      const {
        slaveConfig, slaveFilterCondition, sFilterOrderBy, sGroupByList,
      } = this.props;
      let url = `${commonConfig.server_host}excel/export/${slaveConfig.sId}?sModelsId=${slaveConfig.sParentId}&token=${this.props.app.token}`;
      if (commonUtils.isNotEmptyArr(slaveFilterCondition)) {
        url = `${url}&bFilter=${encodeURIComponent(JSON.stringify(slaveFilterCondition))}`;
      }
      if (sFilterOrderBy !== undefined && sFilterOrderBy !== '' && Object.keys(sFilterOrderBy).length > 0) {
        url = `${url}&sFilterOrderBy=${encodeURIComponent(JSON.stringify(sFilterOrderBy))}`;
      }
      if (commonUtils.isNotEmptyArr(sGroupByList)) {
        url = `${url}&sGroupList=${encodeURIComponent(JSON.stringify(sGroupByList))}`;
      }
      window.open(url);
    };
    /* 获取期初 */
    handleGetPeriod = async () => {
      const { sTbName } = this.props.masterConfig;
      let sClomunType = '';
      if (sTbName === 'cahsupplyinit') {
        sClomunType = 'bAP';
      } else if (sTbName === 'cahcustomerinit') {
        sClomunType = 'bAR';
      } else if (sTbName === 'cahcashierinit') {
        sClomunType = 'bCashier';
      }
      const { sModelsId } = this.props;
      const { token } = this.props.app;
      const url = `${commonConfig.server_host}sysAccountPeriod/getSysAccountPeriod?sModelsId=${sModelsId}`;
      const value = { sClientType: '1', sClomunType };
      const { data } = await commonServices.postValueService(token, value, url);
      if (data.code === 1) {
        const [{ isSysAccountPeriod }] = data.dataset.rows;
        this.props.onSaveState({
          adDisabled: isSysAccountPeriod,
          sClomunType,
        });
      } else {
        this.props.getServiceError(data);
      }
    };
    /* 设置期初 */
    handleBtnSetPeriod = async () => {
      const { sTbName } = this.props.masterConfig;
      let sClomunType = '';
      if (sTbName === 'cahsupplyinit') {
        sClomunType = 'bAP';
      } else if (sTbName === 'cahcustomerinit') {
        sClomunType = 'bAR';
      } else if (sTbName === 'cahcashierinit') {
        sClomunType = 'bCashier';
      }
      const { sModelsId } = this.props;
      const { token } = this.props.app;
      const url = `${commonConfig.server_host}sysAccountPeriod/updateSysAccountPeriod?sModelsId=${sModelsId}`;
      const value = { sClientType: '1', handleType: 'add', sClomunType };
      const { data } = await commonServices.postValueService(token, value, url);
      if (data.code === 1) {
        message.success(data.msg);
        this.props.onSaveState({ adDisabled: true, enabled: false });
      } else {
        this.props.getServiceError(data);
      }
    };
    /* 解除锁定 */
    handleBtnRelievePeriod = async () => {
      const { sModelsId } = this.props;
      const { token } = this.props.app;
      const { sTbName } = this.props.masterConfig;
      let sClomunType = '';
      if (sTbName === 'cahsupplyinit') {
        sClomunType = 'bAP';
      } else if (sTbName === 'cahcustomerinit') {
        sClomunType = 'bAR';
      } else if (sTbName === 'cahcashierinit') {
        sClomunType = 'bCashier';
      }
      const url = `${commonConfig.server_host}sysAccountPeriod/updateSysAccountPeriod?sModelsId=${sModelsId}`;
      const value = { sClientType: '1', handleType: 'reset', sClomunType };
      const { data } = await commonServices.postValueService(token, value, url);
      if (data.code === 1) {
        message.success(data.msg);
        this.props.onSaveState({ adDisabled: false });
      } else {
        this.props.getServiceError(data);
      }
    };

    handleTitleChange = (slavePagination, filters, sorter) => {
      const { slaveConfig, slaveFilterCondition } = this.props;
      const sort = sorter.order === 'ascend' ? 'asc' : 'desc';
      const slaveOrderBy = Object.keys(sorter).length > 0 ? { [sorter.columnKey]: sort } : ''; // 后端未支持空对象， 先用空表示
      this.handleGetData(slaveConfig, slaveFilterCondition, slavePagination.current, slaveOrderBy);
    };
    handleTitleChangeEnabled = (slavePagination) => {
      this.props.onSaveState({ slavePagination });
    };
    handleTableSelectRowChange = async (name, selectedRowKeys) => {
      const {
        [`${name}Data`]: tableData, sModelsType, sModelsId, token, masterConfig, enabled,
      } = this.props;
      if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
        if (sModelsType === 'commonClassfiy/salesMan') {
          const addState = this.props.onTableSelectRowChange(name, selectedRowKeys, true);
          const { [`${name}SelectedRowKeys`]: rowKeys } = addState;
          for (const sId of rowKeys) {
            const tableDataIndex = tableData.findIndex(item => item.sId === sId);
            const sNameIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'sName');/* 判断配置中是否有员工编号字段 */
            if (tableDataIndex > -1 && sNameIndex > -1) {
              const tableDataRow = JSON.parse(JSON.stringify(tableData[tableDataIndex]));
              masterConfig.gdsconfigformslave[sNameIndex].iTag = 0; /* 默认是0 */
              if (enabled && tableDataRow.handleType !== 'add') { /* 判断销售人员是否已被占用 */
                const value = {
                  tableName: masterConfig.sTbName,
                  sId: [sId],
                };
                const url = `${commonConfig.server_host}business/addSysLocking?sModelsId=${sModelsId}`;
                /*   接收返回值   */
                const { data } = await commonServices.postValueService(token, value, url);
                if (data.code === 1) {
                  const sNameIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'sName');
                  masterConfig.gdsconfigformslave[sNameIndex].iTag = 1; /* ，已占用销售人员,员工不能修改 即下拉不可选 */
                } else { /*   失败   */
                  this.props.getServiceError(data);
                }
              }
            }
          }
        }
      }
      this.props.onTableSelectRowChange(name, selectedRowKeys);
    }

    render() {
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onCancel={this.handleCancel}
          onAdd={this.handleAdd}
          onEdit={this.handleEdit}
          onDel={this.handleDel}
          onSubmit={this.handleValidateSave}
          onReturnForm={this.handleForm}
          onPaginationChange={this.handlePaginationChange}
          onGetData={this.handleGetData}
          onButtonClick={this.handleButtonClick}
          onChangeInvalid={this.handleInvalid}
          onTitleChange={this.handleTitleChange}
          onTitleChangeEnabled={this.handleTitleChangeEnabled}
          onTableSelectRowChange={this.handleTableSelectRowChange}
        />
      );
    }
  };
};
