/* eslint-disable */
import React, { Component } from 'react';
import { Button, Toast } from 'antd-mobile-v2';
import * as commonUtils from '../../utils/utils';
import commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import FileManageMobile from '../components/FileManageMobile';
import FileShowMobile from '../components/FileShowMobile';
import FileManageMobileWx from '../components/FileManageMobileWx';
import {Modal} from "antd";


class CommobileToolBar extends Component {
  /**   构造函数   */
  constructor(props) {
    super(props);
    this.state = {
      buttonConfig: [], /* 导航工具栏 */
      btnStyle: {},
      divStyle: {},
    };
  }

  componentWillMount() {
    this.componentWillReceiveProps(this.props);
  }
  /**   props改变的时候触发   */
  componentWillReceiveProps(nextProps) {
    const {
      masterConfig, btnStyle, divStyle,
    } = nextProps;
    const { buttonConfig: buttonConfigOld } = this.state;
    if (commonUtils.isNotEmptyObject(masterConfig) && commonUtils.isEmptyArr(buttonConfigOld)) {
      let buttonConfig = masterConfig.gdsconfigformslave.filter(item => item.sName === '' && item.showName !== '' && item.bVisible && item.sControlName.substring(0, 3) === 'Btn');
      if(location.pathname.toLowerCase().includes('padbill')) {
        buttonConfig = buttonConfig.filter(item  => item.sControlName?.toLowerCase().includes('btnupdpic'))
      }
      this.setState({ buttonConfig, btnStyle, divStyle });
    }
  }

  /**   获取父级菜单属性   */
  getMenuStatus = (menu) => {
    if (menu?.sControlName === 'BtnCancel') {
      return false;
    }
    let { masterData } = this.props;
    const { enabled, adDisabled, sModelsType } = this.props;
    if (commonUtils.isEmptyObject(masterData)) {
      masterData = {};
    }
    const { bCheck, bInvalid } = masterData;
    let disabledData = []; /* 置灰按钮集合 */
    if (adDisabled) {
      disabledData = ['BtnAdd', 'BtnUpd', 'BtnDel', 'BtnSave', 'BtnCancel', 'BtnSetPeriod'];
    } else if (!adDisabled) {
      if (!enabled) {
        if (bInvalid) { // 已作废
          disabledData = ['BtnUpd', 'BtnDel', 'BtnSave', 'BtnCancel', 'BtnExamine', 'BtnCancelExamine', 'BtnCopyTo', 'BtnCopyFrom', 'BtnBsOperation.BtnInvalid'];
        } else if (bCheck) { // 已审核
          if (!commonUtils.isEmpty(sModelsType) && sModelsType.includes('element/')) {
            if (sModelsType === 'element/customerInfo') {
              disabledData = ['BtnUpd', 'BtnDel', 'BtnSave', 'BtnCancel', 'BtnExamine', 'BtnCopyFrom', 'BtnCancelInvalid', 'BtnImport'];
            } else {
              disabledData = ['BtnSave', 'BtnCancel', 'BtnCancelExamine', 'BtnCopyFrom', 'BtnCancelInvalid'];
            }
          } else {
            /* 已审核查看状态 修改 删除 保存 取消 审核 复制从 取消作废置灰 */
            disabledData = ['BtnUpd', 'BtnDel', 'BtnSave', 'BtnCancel', 'BtnExamine', 'BtnCopyFrom', 'BtnCancelInvalid', 'BtnImport'];
          }
        } else {
          /** 查看状态 修改 删除 保存 取消 审核 复制从置灰 */
          disabledData = ['BtnSave', 'BtnCancel', 'BtnCancelExamine', 'BtnCopyTo', 'BtnCopyFrom', 'BtnCancelInvalid'];
          if (!commonUtils.isEmpty(sModelsType) && sModelsType.includes('element/') && sModelsType !== 'element/customerInfo') {
            /* 除了客户信息，其他基础信息在查看状态状态下 复制到常亮 */
            disabledData = ['BtnSave', 'BtnCancel', 'BtnCancelExamine', 'BtnCopyFrom', 'BtnCancelInvalid'];
          }
        }
      } else if (sModelsType === 'production/productionPlanInfo') {
        disabledData = ['BtnRefresh', 'BtnAdd', 'BtnUpd', 'BtnDel', 'BtnFirst', 'BtnPrior', 'BtnNext', 'BtnLast', 'BtnUpCheck', 'BtnDownCheck', 'BtnExamine', 'BtnCancelExamine', 'BtnCopyTo', 'BtnBsOperation.BtnInvalid', 'BtnBsOperation.BtnCancelInvalid'];
      } else {
        disabledData = ['BtnRefresh', 'BtnAdd', 'BtnUpd', 'BtnDel', 'BtnFirst', 'BtnPrior', 'BtnNext', 'BtnLast', 'BtnUpCheck', 'BtnDownCheck', 'BtnExamine', 'BtnCancelExamine', 'BtnCopyTo', 'BtnBsOperation.BtnInvalid', 'BtnBsOperation.BtnCancelInvalid', 'BtnPrint'];
      }
    }
    /* 通用上传按钮 除了新增,其他状态下都是亮的 */
    if (menu.sControlName === 'BtnUpload') {
      const { handleType } = masterData;
      if (handleType === 'add') {
        disabledData.push('BtnUpload');
      }
    }
    // 其它自定义按钮不在以上 不能操作数据里
    if (menu.disabled) {
      disabledData.push(menu.sControlName);
    }
    // else {
    //   const iIndex = disabledData.findIndex(item => item === menu.sControlName);
    //   disabledData.splice(iIndex, 1);
    // }
    // console.log('disabledData:', menu.sControlName, menu.disabled); // disabledData
    let bReturn = true;
    if (menu.sControlName !== undefined && menu.sControlName.indexOf('.') > -1) {
      bReturn = disabledData.findIndex(item => item === menu.sControlName.substring(0, menu.sControlName.indexOf('.'))) > -1;
      if (!bReturn) {
        bReturn = disabledData.findIndex(item => item === menu.sControlName) > -1;
      }
    } else {
      bReturn = disabledData.findIndex(item => item === menu.sControlName) > -1;
    }
    bReturn = bReturn || (this.props.getMenuStatus !== undefined && this.props.getMenuStatus(menu));
    return bReturn;
  };
  // 进行存储过程按钮存储过程参数解析拼接 根据存储过程按钮参数配置进行解析，配置是json格式 {"sproName":"cal_sss","inMap":"master.sSlaveId,slave.sId"}
  handleBtnEent = async (btnConfig, name, sValue) => {
    const { masterData } = this.props;
    let iResult = 0 ;
    // if (commonUtils.isNotEmptyObject(name) && name.indexOf('BtnRepair') > -1 && commonUtils.isNotEmptyObject(sCurrMemoProps)) {
    //   sCurrMemoProps.bVisibleMemo = false;
    //   this.props.onSaveState({ sCurrMemoProps });
    // }
    // eslint-disable-next-line prefer-destructuring
    const sButtonParam = btnConfig.sButtonParam;
    const btn = JSON.parse(sButtonParam);
    const sProName = btn.sproName;
    const inParams = [];
    // eslint-disable-next-line prefer-destructuring
    const inMap = btn.inMap;
    const inlist = inMap.split(',');
    const masterArr = [];
    const slaveArr = [];
    const slaveInfoArr = [];
    const slaveChildArr = [];
    const controlArr = [];
    const materialsArr = [];
    const processArr = [];


    if (inlist.length > 0) {
      inlist.forEach((item) => {
        const itemArr = item.split('.');
        if (itemArr.length > 0) {
          const sname = itemArr[0];
          const stype = itemArr[1];
          if (commonUtils.isNotEmptyStr(sname) && sname === 'master') {
            masterArr.push(stype);
          }
          if (commonUtils.isNotEmptyStr(sname) && sname === 'slave') {
            slaveArr.push(stype);
          }
          if (commonUtils.isNotEmptyStr(sname) && sname === 'slaveInfo') {
            slaveInfoArr.push(stype);
          }
          if (commonUtils.isNotEmptyStr(sname) && sname === 'slaveChild') {
            slaveChildArr.push(stype);
          }
          if (commonUtils.isNotEmptyStr(sname) && sname === 'control') {
            controlArr.push(stype);
          }
          if (commonUtils.isNotEmptyStr(sname) && sname === 'materials') {
            materialsArr.push(stype);
          }
          if (commonUtils.isNotEmptyStr(sname) && sname === 'process') {
            processArr.push(stype);
          }
        }
      });

      if (commonUtils.isNotEmptyArr(masterArr) && commonUtils.isNotEmptyObject(masterData)) {
        const addState = {};
        addState.key = 'master';
        const val = [];
        const currVal = {};
        masterArr.forEach((filed) => {
          currVal[`${filed}`] = masterData[`${filed}`];
        });
        val.push(currVal);
        addState.value = val;
        inParams.push({ ...addState });
      }
      if (commonUtils.isNotEmptyArr(slaveArr)) {
        const addState = this.handleProParams('slave', slaveArr);
        if (commonUtils.isNotEmptyObject(addState)) {
          inParams.push({ ...addState });
        }
      }
      if (commonUtils.isNotEmptyArr(slaveInfoArr)) {
        const addState = this.handleProParams('slaveInfo', slaveInfoArr);
        if (commonUtils.isNotEmptyObject(addState)) {
          inParams.push({ ...addState });
        }
      }
      if (commonUtils.isNotEmptyArr(slaveChildArr)) {
        const addState = this.handleProParams('slaveChild', slaveChildArr);
        if (commonUtils.isNotEmptyObject(addState)) {
          inParams.push({ ...addState });
        }
      }
      if (commonUtils.isNotEmptyArr(controlArr)) {
        const addState = this.handleProParams('control', controlArr);
        if (commonUtils.isNotEmptyObject(addState)) {
          inParams.push({ ...addState });
        }
      }
      if (commonUtils.isNotEmptyArr(materialsArr)) {
        const addState = this.handleProParams('materials', materialsArr);
        if (commonUtils.isNotEmptyObject(addState)) {
          inParams.push({ ...addState });
        }
      }
      if (commonUtils.isNotEmptyArr(processArr)) {
        const addState = this.handleProParams('process', processArr);
        if (commonUtils.isNotEmptyObject(addState)) {
          inParams.push({ ...addState });
        }
      }
    }
    console.log('inParams', inParams);
    iResult = await this.handleProcedureCall(btnConfig, sProName, JSON.stringify({ params: inParams, changeValue: sValue }));
    return iResult;
  };
  // 存储过程按钮调用存储过程
  handleProcedureCall = async (btnConfig, proName, proInParam) => {
    const {
      app,
      sModelsId,
      // salveData,
      // slaveFilterCondition,
    } = this.props;
    let iResult = 0;
    let { masterData} = this.props;
    let { slaveChildData } = this.props;
    const value = { sProName: proName, sProInParam: proInParam };
    const url = `${commonConfig.server_host}procedureCall/doGenericProcedureCall?sModelsId=${sModelsId}`;
    const returnData = (await commonServices.postValueService(app.token, value, url)).data;
    iResult = returnData.code;
    if (returnData.code === 1) {
      Toast.success(returnData.msg);
      this.props.onButtonClick('BtnRefresh');
      if(sModelsId === '12710101117254593440940' || btnConfig.sControlName === 'BtnEventBind'){
        if(commonUtils.isNotEmptyObject(masterData)) {
          // if(document.getElementById('sBarcode')) {
          //   document.getElementById('sBarcode').value = '';
          // }
          const addState ={};
          addState.sBarcode1 = '';
          addState.sBarcode = '';
          addState.sBoardName = '';
          addState.sSlaveLength = 0;
          slaveChildData = [];
          masterData = {...masterData, ...addState};
          this.props.onSaveState({ masterData, slaveChildData });
        }
      }

    } else {
      this.props.getServiceError(returnData);
    }
    return  iResult
  }
  // 根据配置解析拼接具体参数
  handleProParams = (sKey, arr) => {
    const { [`${sKey}Data`]: tableData, [`${sKey}SelectedRowKeys`]: selectedRowKeys } = this.props;
    let keyData = commonUtils.isNotEmptyArr(tableData) && commonUtils.isNotEmptyArr(selectedRowKeys) ? tableData.filter(item => selectedRowKeys.includes(item.sId) || selectedRowKeys.includes(item.sSlaveId)) : [];
    if(sKey === 'slaveChild' && commonUtils.isNotEmptyArr(tableData) && commonUtils.isEmptyArr(selectedRowKeys)) {
      keyData = tableData;
    }
    if (commonUtils.isNotEmptyArr(keyData)) {
      const addState = {};
      addState.key = sKey;
      const val = [];
      keyData.forEach((currData) => {
        const currVal = {};
        arr.forEach((filed) => {
          currVal[`${filed}`] = currData[`${filed}`];
        });
        val.push(currVal);
      });
      addState.value = val;
      return addState;
    } else {
      return undefined;
    }
  };

  handleClick = async (name) => {
    if (name.startsWith('BtnEvent')) {
      const btnConfig = this.props.masterConfig.gdsconfigformslave.filter(item => (item.sControlName === name))[0];// sButtonEnabled  sButtonParam
      if (commonUtils.isNotEmptyObject(btnConfig) && commonUtils.isNotEmptyStr(btnConfig.sButtonParam)) {
        // this.handleBtnEent(btnConfig);
        /* 根据接口返回是之前调用还是之后调用 */
        const interfaceArr = commonUtils.isNotEmptyObject(btnConfig) ? btnConfig.interface :[];
        this.props.onSaveState({
          loading: true,
        });
        /* 根据接口返回是之前调用还是之后调用 */
        let flag = 0;
        if(commonUtils.isNotEmptyArr(interfaceArr)) {
          const beforeInterfaceArr = interfaceArr.filter(item => item.sInterfaceCallMethod === "1" );
          const afterInterfaceArr = interfaceArr.filter(item => item.sInterfaceCallMethod === "2" );
          if(commonUtils.isNotEmptyArr(beforeInterfaceArr)) {  /* 之前调用 */
            // beforeInterfaceArr.forEach((item) => {
            //   this.handleInterfaceCall(item);
            // });
            const asyncFunc = async () => {
              for (let i = 0; i < beforeInterfaceArr.length; i ++) {
                const data = await this.handleInterfaceCall(beforeInterfaceArr[i]);
                if (!data) {
                  flag += 1;
                  return;
                }
              }
            }
            await asyncFunc();

          }
          let result;
          if (flag == 0) {
            result = await this.handleBtnEent(btnConfig)
          } else {
            this.props.onSaveState({
              loading: false,
            });
          }
          if(commonUtils.isNotEmptyArr(afterInterfaceArr)) { /* 之后调用 */
            if(result) { /* 只有审核成功 才能调用接口 -5代表审核失败 */
              const asyncFunc = async () => {
                for (let i = 0; i < afterInterfaceArr.length; i++) {
                  await this.handleInterfaceCall(afterInterfaceArr[i],true);
                }
              }
              await asyncFunc();
            }
          }
        } else{
          this.handleBtnEent(btnConfig);
        }
      } else {
        Toast.fail('请配置按钮的存储过程');
      }
    } else {
      this.props.onButtonClick(name);
    }
  }
  /* 调用后台配置的接口 */
  handleInterfaceCall = async  (obj, showTip, key, ids) => {
    let bResult = false;
    const { app, sModelsId, masterData, slaveSelectedRowKeys, slaveData, masterConfig, slaveFilterCondition } = this.props;
    const sInterfaceName = obj.sInterfaceName;
    /* 如果key是BtnSendList 传从表的主键集合 */
    let idArr = '';
    /* 如果有对应字段 则取对应字段 ,否则 取默认值 */
    const btnConfig = commonUtils.isNotEmptyArr(masterConfig.gdsconfigformslave.filter(item => (item.sControlName === key))) ?
      masterConfig.gdsconfigformslave.filter(item => (item.sControlName === key))[0] : {};

    let sActiveKey = '';
    if(commonUtils.isNotEmptyObject(btnConfig)) {
      sActiveKey = btnConfig.sActiveKey;
    }
    if(sActiveKey) {
      if( sActiveKey.includes('master.sId')) {
        idArr = masterData.sId;
      }
    } else if(key && (key.includes('BtnSendList') ||  key.includes('BtnBatchExamine'))) {
      if(commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
        slaveSelectedRowKeys.forEach((item) => {
          if(commonUtils.isNotEmptyObject(item)) {
            idArr += `${item},`;
          }
        });
        idArr = commonUtils.isNotEmptyObject(idArr) ? idArr.substr(0, idArr.length - 1) : '';
      }
    } else if(location.pathname.includes('commobileList')){
      const { slaveSelectedRowKeys, slaveData } = this.props;
      let { slaveSelectedData } = this.props;
      if(commonUtils.isEmptyArr(slaveSelectedData) && commonUtils.isNotEmptyArr(slaveData)) {
        slaveSelectedData = slaveData.filter(item => slaveSelectedRowKeys.includes(item.sId) || slaveSelectedRowKeys.includes(item.sSlaveId));
      }
      const slaveSelectedDataNew = this.deteleObject(slaveSelectedData); // 删除sid重复的数据

      if(commonUtils.isNotEmptyArr(slaveSelectedDataNew)) {
        slaveSelectedDataNew.forEach((item) => {
          if(commonUtils.isNotEmptyObject(item)) {
            idArr += `${item.sId},`;
          }
        });
        idArr = commonUtils.isNotEmptyObject(idArr) ? idArr.substr(0, idArr.length - 1) : '';
      }
      if(commonUtils.isNotEmptyObject(ids)) { /* 如果是勾选多行 则sId为循环的每一条 */
        idArr = ids;
      }
    } else {
      idArr = masterData.sId;
    }
    const value = { sId: commonUtils.isNotEmptyObject(idArr) ? idArr : commonUtils.isNotEmptyObject(ids)  ? ids : masterData.sId, sSlaveId: slaveSelectedRowKeys?.toString(), masterData, userInfo: app.userinfo };
    if(location.pathname.includes('commonList') && commonUtils.isNotEmptyArr(slaveFilterCondition)){
      value.bFilter = JSON.stringify(slaveFilterCondition) ;
    }
    const url = `${commonConfig.interface_host}interfaceDefine/callthirdparty/${sInterfaceName}?sModelsId=${sModelsId}`;
    const returnData = (await commonServices.postValueService(app.token, value, url, app)).data;
    if(!returnData) {
      Toast.fail('接口调用失败！');
      return  false;
    }
    if (returnData.code === 1) {
      bResult = true;
      // message.success(returnData.msg);
    }else if (returnData.code === 2) {
      // Modal.info({
      //   title: '温馨提示:',
      //   content: (
      //     <div>
      //       {this.handleGetMsg(returnData.msg)}
      //     </div>
      //   ),
      //   okText: '确认',
      //   onOk() {},
      // });
      bResult = true;
    } else if (returnData.code === -8) {
      Modal.info({
        title: '温馨提示:',
        content: (
          <div>
            {this.handleGetMsg(returnData.msg)}
          </div>
        ),
        onOk() {},
      });
      bResult = false;
    } else {
      bResult = false;
      this.props.getServiceError(returnData);
    }
    /* 若配置的是按钮后调用第三方, 则调用成功后 需要重新回刷一次数据 */
    if(commonUtils.isNotEmptyObject(obj) && obj.sInterfaceCallMethod === "2"){
      if(bResult){
        this.props.onButtonClick('BtnRefresh');
      }
    }
    return bResult;
  }
  /**   渲染   */
  render() {
    const { buttonConfig, btnStyle, divStyle } = this.state;
    const {
      masterData, sModelsId, slaveSelectedRowKeys, slaveData,
    } = this.props;
    /* 手机端通用拍照上传功能 */
    let btnUpdConfig = {};
    if (commonUtils.isNotEmptyArr(buttonConfig)) {
      const iIndex = buttonConfig.findIndex(item => item.sControlName.includes('BtnUpdPic'));
      if (iIndex > -1) {
        btnUpdConfig = buttonConfig[iIndex];
      }
    }
    let sSlaveId = '';
    let selectedsId = ''; /*  列表选中行或窗体sFormId */
    let selectedRow = {};
    const bList = location.pathname === '/indexMobile/commobileList';

    if (commonUtils.isNotEmptyArr(slaveData)) {
      let iIndex = -1;
      if (commonUtils.isEmptyArr(slaveSelectedRowKeys)) {
        iIndex = 0;
      } else {
        iIndex = slaveData.findIndex(item => slaveSelectedRowKeys.includes(item.sSlaveId));
      }
      if (iIndex > -1) {
        selectedRow = slaveData[iIndex];
        selectedsId = commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyObject(selectedRow) ? (commonUtils.isNotEmptyObject(selectedRow.sFormId) ? selectedRow.sFormId : '') : ''; /* 列表从表的sFormId */
        sSlaveId = commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyObject(selectedRow) ? (commonUtils.isNotEmptyObject(selectedRow.sSlaveId) ? selectedRow.sSlaveId : '') : ''; /* 列表从表的sSlaveId */
      }
    }
    /* 如果配置按钮有sqlConditon条件 则根据SQLCondition条件 否则走正常 */
    let conditonValues = { sSrcId: bList ? selectedsId : commonUtils.isNotEmptyObject(masterData) ? masterData.sId : '' };
    if (commonUtils.isNotEmptyObject(btnUpdConfig) && btnUpdConfig.sSqlCondition) {
      /* 选中行 */
      if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
        const iIndex = slaveData.findIndex(item => slaveSelectedRowKeys.includes(item.sSlaveId));
        if (iIndex > -1) {
          if (commonUtils.isNotEmptyObject(selectedRow)) {
            conditonValues = this.props.getSqlCondition(btnUpdConfig, 'slave', selectedRow);
          }
        }
      }
    }

    const filemanageType = {
      app: {
        ...this.props.app,
        currentPane: {
          name: 'elefilfilemanage',
          config: btnUpdConfig,
          conditonValues,
          title: '上传',
          route: '/elefilfilemanage',
          formId: '15864832090002447752315825731600',
          key: `${sModelsId}15864832090002447752315825731600`,
          sModelsType: 'element/filfilemanage',
          sSrcNo: bList ? (commonUtils.isNotEmptyArr(selectedRow) ? selectedRow.sBillNo : '') : (commonUtils.isNotEmptyObject(masterData) ? masterData.sBillNo : ''), /* 源单号 */
          sSrcFormId: bList ? (commonUtils.isNotEmptyArr(selectedRow) ? sModelsId : '') : (commonUtils.isNotEmptyObject(masterData) ? masterData.sFormId : ''), /* 源单窗体Id */
          sSrcId: bList ? (commonUtils.isNotEmptyObject(selectedRow) ? selectedRow.sId : '') : commonUtils.isNotEmptyObject(masterData) ? masterData.sId : '', /* 源单Id */
          sSrcSlaveId: commonUtils.isNotEmptyObject(sSlaveId) ? sSlaveId : '', /* 工单控制表选中行或列表的是sSlaveId */
          onFilfileOk: this.handleFilfileManageOk,
          onFilfileCancel: this.handleFilfileManageCancel,
        },
      },
      config: btnUpdConfig,
      sModelsId: '15864832090002447752315825731600',
      enabled: true, /* this.props.enabled */
      dispatch: this.props.dispatch,
      content: this.props.content,
      id: new Date().getTime().toString(),
      btnStyle,
    };

    return (
      <div style={divStyle}>
        {commonUtils.isEmptyArr(buttonConfig) ? '' :
          buttonConfig.map((item) => {
            if (!commonConfig.isWeiXin && item.sControlName.includes('BtnUpdPic')) {
              return (
                <FileManageMobile {...filemanageType} />
              );
            } else if (true && item.sControlName.includes('BtnUpdPic')) {
              return (
                <FileManageMobileWx {...filemanageType} />
              );
            } else if (item.sControlName.includes('BtnShowPic')) {
              return (
                <FileShowMobile {...this.props} btnConfig={item} selectedRow={selectedRow} />);
            }
            return (<Button type={btnStyle?.type} inline style={btnStyle} disabled={this.getMenuStatus(item)} onClick={this.handleClick.bind(this, item.sControlName)} >{item.showName}</Button>);
          })}
      </div>

    );
  }
}

export default CommobileToolBar;
