import React from 'react';
import { Button, Grid, Toast } from 'antd-mobile-v2';
import 'antd-mobile-v2/dist/antd-mobile.css';
import styles from './SceneMobile.less';
// eslint-disable-next-line import/first
import { createForm } from 'rc-form';
import commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import * as commonUtils from '../../utils/utils';
import ShowType from './CommobileComponent';
import CommobileBase from './CommobileBase';
import CommobileBillEvent from './CommobileBillEvent';
import * as commonFunc from "@/components/Common/commonFunc";

class SceneMobile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      totalData: [],
    };
  }
  async componentWillMount() {
    const masterConfig = {};
    const masterData = [];
    this.props.onSaveState({ masterConfig, masterData });
    /* 获取配置 */
    let { sModelType } = this.props;
    sModelType = commonUtils.isEmptyObject(sModelType) ? 'scene' : sModelType;
    const { token } = this.props.app;
    const configUrl = `${commonConfig.server_host}mobilephone/getMenu/${sModelType}?sModelsId=100`;
    const configReturn = (await commonServices.getService(token, configUrl)).data;
    if (configReturn.code === 1) {
      const returnData = configReturn.dataset.rows;/* 全部数据 */
      if (commonUtils.isNotEmptyArr(returnData)) {
        this.setState({ totalData: returnData });
      }
    } else {
      Toast.success(configReturn.msg);
    }
  }
  handleGetAllMenuData = () => {
    const { totalData } = this.state;
    const { token } = this.props.app;
    if (commonUtils.isNotEmptyArr(totalData)) {
      return totalData.map((item) => {
        const firstMenu = {};
        firstMenu.bUnReason = item.bUnReason;
        firstMenu.bUnTask = item.bUnTask;
        firstMenu.bVisible = item.bVisible;
        firstMenu.children = item.children;
        firstMenu.iOrder = item.iOrder;
        firstMenu.sChinese = item.sChinese;
        firstMenu.sMenuName = item.sMenuName;
        firstMenu.sId = item.sId;
        firstMenu.sModelType = item.sModelType;
        firstMenu.sName = item.sName;
        firstMenu.sParentId = item.sParentId;
        firstMenu.sProcName = item.sProcName;
        firstMenu.sTitleLogoPath = item.sTitleLogoPath;
        firstMenu.sUnType = item.sUnType;
        const childrenData = item.children;
        const gridData = [];
        if (commonUtils.isNotEmptyArr(childrenData)) {
          childrenData.forEach((itemChild) => {
            const addStata = {};
            const dataUrl = `${commonConfig.file_host}file/download?savePathStr=${itemChild.sTitleLogoPath}&sModelsId=100&token=${token}`;
            addStata.icon = dataUrl;
            addStata.text = itemChild.sMenuName;
            addStata.url = itemChild.sName;
            addStata.sModelsId = itemChild.sId;
            addStata.sModelType = itemChild.sModelType;
            addStata.iOrder = itemChild.iOrder;
            gridData.push(addStata);
          });
        }
        gridData.sort((item, item2) => item.iOrder - item2.iOrder);
        return (
          <div className="GridContent">
            <div className={styles.SubTitle}>{firstMenu.sMenuName}</div>
            <Grid data={gridData} hasLine={false} onClick={this.handleGridClick} />
          </div>
        );
      });
    }
  }

  handleChangeIframeVisible = (visible, iframeUrl) => {
    if (visible) {
      document.querySelector('#root').classList.add('mesIframe');
    } else {
      document.querySelector('#root').classList.remove('mesIframe');
    }
    this.props.onSaveState({
      iframeVisible: visible,
      iframeUrl,
    });
  }
  handleGridClick = (el) => {
    const { dispatch, app, token } = this.props;
    const { userinfo } = app;
    const { url, sModelType } = el;/* 菜单对应的路由地址 */

    const iframeUrl = sModelType !== undefined ?
      sModelType
        .replace('{sBrandsId}', userinfo.sBrandsId)
        .replace('{sSubsidiaryId}', userinfo.sSubsidiaryId)
        .replace('{sUserName}', userinfo.sUserName)
        .replace('{sUserId}', userinfo.sId)
        .replace('{token}', token)
      : '';
    if (iframeUrl.startsWith('http')) {
      this.handleChangeIframeVisible(true, iframeUrl);
      return;
    }

    if (url !== '') {
      const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${el.sModelsId}?sModelsId=${el.sModelsId}`;
      dispatch({
        type: 'content/onRouterMobile',
        payload: {
          url, /*   接口地址   */
          urlKey: sNameUrl,
          sModelsId: el.sModelsId,
          sModelType: el.sModelType,
        },
      });
    }
  }

  /** 修改主表数据 */
  handleMasterChange = async (name, sFieldName, changeValue, sId, dropDownData, isWait, masterDataNew) => {
    if (sFieldName === 'sMachineId') {
      const { dispatch } = this.props;
      const returnData = await this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, true, masterDataNew);
      dispatch({
        type: 'app/saveMachineId',
        payload: { sMachineId: returnData.masterData.sMachineId },
      });
      this.props.onSaveState({ ...returnData });
    } else {
      this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, isWait, masterDataNew);
    }
  }


  render() {
    const {
      sModelsId,
      app,
      iframeVisible,
      iframeUrl,
    } = this.props;
    const child = {
      bCanInput: false,
      bEntireLine: false,
      bFilter: false,
      bFind: false,
      bFirstEmpty: true,
      bIsOther: false,
      bMergeCell: false,
      bMultipleChoice: false,
      bNewRecord: false,
      bNotEmpty: true,
      bNotRepeat: false,
      bReadonly: false,
      bSum: false,
      bTree: false,
      bVisible: true,
      iColValue: 1,
      iFitWidth: 119,
      iIncrement: 71019,
      iOrder: 16,
      iTag: 0,
      iVisCount: 1,
      sActiveId: '19211681019715540861764830',
      sActiveKey: 'sMachineId',
      sAssignField: 'sMachineId:sId',
      sBig5: '机台名稱',
      sBig5DropDown: 'SELECT sMachineName,sMachineNo, sId FROM eleMachine where 1=1 #companyId# and bInvalid = 0',
      sBrandsId: '1111111111',
      sChinese: '机台名称',
      sChineseDropDown: 'SELECT sMachineName,sMachineNo, sId FROM eleMachine where 1=1 #companyId# and bInvalid = 0',
      sColor: '',
      sControlName: '',
      sDateFormat: '',
      sDefault: '',
      sDropDownType: 'sql',
      sEnglish: '',
      sEnglishDropDown: 'SELECT sMachineName,sMachineNo, sId FROM eleMachine where 1=1 #companyId# and bInvalid = 0',
      sFieldToContent: '',
      sFilterSql: '',
      sId: '15943635830008892519957335923000',
      sKeyUpFilter: '',
      sMaxValue: '',
      sMinValue: '',
      sName: 'sMachineId',
      sNotRepeatColumn: '',
      sParentId: '101251240115015916850902230',
      sRelation: '',
      sSelectRelation: '',
      sSqlCondition: '',
      sSubsidiaryId: '1111111111',
      showDropDown: 'SELECT sMachineName,sMachineNo, sId FROM eleMachine where 1=1 #companyId# and bInvalid = 0',
      showName: '当前设备',
    };
    const showTypeProps = {
      app,
      record: {},
      sId: '', /*   修改当前编号(数据格式:字符串)   */
      name: 'master',
      form: this.props.form,
      formId: sModelsId,
      getSqlDropDownData: this.props.getSqlDropDownData,
      getSqlCondition: this.props.getSqlCondition,
      handleSqlDropDownNewRecord: this.props.handleSqlDropDownNewRecord,
      getFloatNum: this.props.getFloatNum,
      getDateFormat: this.props.getDateFormat,
      onChange: this.handleMasterChange,
      showConfig: child,
      formItemLayout: {},
      textArea: false,
      enabled: true,
      dataValue: this.props.app.sMachineId,
      bTable: false,
      onFilterDropDownData: this.props.onFilterDropDownData,
      onSaveState: this.props.onSaveState,
    };
    const btnBackEbc = commonFunc.showMessage(app.commonConst, 'btnBackEbc');/* 返回 */


    const iconSettingShow = true;
    return iframeVisible ? (
      <div className={styles.iframe}>
        <iframe title="iframe" src={iframeUrl} frameBorder={0} />
        <div className={styles.iframeBakBtn}>
          <Button type="link" onClick={() => { this.handleChangeIframeVisible(false); }}>{btnBackEbc}</Button>
        </div>
      </div>
    ) : (
      <div>
        <div className={styles.pickerList}>
          { false && <ShowType {...showTypeProps} iconSettingShow={iconSettingShow} /> }
        </div>
        {this.handleGetAllMenuData()}
      </div>
    );
  }
}
const SceneMobileComponent = createForm()(SceneMobile);
export default CommobileBase(CommobileBillEvent(SceneMobileComponent));
