/* eslint-disable prefer-destructuring */
/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React from 'react';
import weixin from 'weixin-js-sdk';
import { Tabs, Badge, SearchBar, Modal, Button, Menu, ActivityIndicator, Flex, WhiteSpace, Toast, List } from 'antd-mobile-v2';
import 'antd-mobile-v2/dist/antd-mobile.css';
import styles from '.././mobile.less';
import commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import * as commonUtils from '../../utils/utils';
import scan from '../../assets/mobile/scanning.svg';
// eslint-disable-next-line import/first
import BarCodeUtil from './BarCodeUtil';
// eslint-disable-next-line import/first,no-unused-vars
import moment from 'moment';
import ShowType from './CommobileComponent';
// eslint-disable-next-line import/first
import { createForm } from 'rc-form';
import * as commonFunc from "@/components/Common/commonFunc";


// const data = [
//   {
//     value: '1',
//     label: '全部数据',
//   },
// ];

class CommobileSearchComponent extends React.Component {
  constructor(props) {
    super(props);
    const returnFilterCondition = props.returnFilterCondition;
    const returnFilterName = props.returnFilterName; /* 未清搜索框字段 */
    let returnValue = '';
    if (commonUtils.isNotEmptyArr(returnFilterCondition)) {
      const returnData = returnFilterCondition.filter(item => item.bFilterName === returnFilterName);
      if (commonUtils.isNotEmptyArr(returnData)) {
        returnValue = returnData[0];
      }
    }
    this.state = {
      scanValue: commonUtils.isNotEmptyObject(returnValue) ? returnValue.bFilterValue : '',
    };
    this.bFilterCondition = true;
    this.textInput = null;
  }

  async componentWillMount() {
    const { token, sModelsId } = this.props;
    const dataUrl = `${commonConfig.server_host}syssearch/getSyssearchData/${sModelsId}?sModelsId=${sModelsId}`; /* 获取快捷查找方案 */
    const dataReturn = (await commonServices.getService(token, dataUrl)).data;
    if (dataReturn.code === 1) {
      const returnData = dataReturn.dataset.rows;
      const addState = {};
      if (commonUtils.isNotEmptyArr(returnData)) {
        addState.searchOperation = [];
        returnData.forEach((item) => {
          addState.searchOperation.push({ text: item.sName });
        });
        let iIndex = returnData.findIndex(item => item.bDefault);
        iIndex = iIndex > -1 ? iIndex : commonUtils.isEmptyArr(returnData) ? -1 : 0;
        addState.label = returnData[iIndex].sName;
      }
      if (sModelsId === '12710101117217437977130') {
        if (this.inputSearch) this.inputSearch.focus();
      }
      this.props.onSaveState({ searchSolution: returnData, ...addState });
    } else {
      this.props.getServiceError(dataReturn);
    }
  }

  componentWillReceiveProps(nextProps) {
    const {
      returnFilterCondition, returnFilterName, clearSearchValue, sModelsType, sModelsId,
    } = nextProps;
    if (sModelsId === '12710101117217437977130') {
      if (this.inputSearch) this.inputSearch.focus();
    }
    if (commonUtils.isNotEmptyArr(returnFilterCondition) && clearSearchValue && sModelsType === 'mobile/productionReport') {
      const returnData = returnFilterCondition.filter(item => item.bFilterName === returnFilterName);
      let returnValue = '';
      if (commonUtils.isNotEmptyArr(returnData)) {
        returnValue = returnData[0];
      }
      this.setState({
        scanValue: commonUtils.isNotEmptyObject(returnValue) ? returnValue.bFilterValue : '',
      });
    }
  }


  onClose = key => () => {
    this.setState({
      [key]: false,
    });
  }

  onChange = async (value) => {
    let label = '';
    const { initData } = this.props;
    initData.forEach((dataItem) => {
      if (dataItem.value === value[0]) {
        label = dataItem.label;
        if (dataItem.children && value[1]) {
          dataItem.children.forEach((cItem) => {
            if (cItem.value === value[1]) {
              label += ` ${cItem.label}`;
            }
          });
        }
      }
    });

    const { searchSolution, slaveConfig } = this.props;
    const iIndex = searchSolution.findIndex(item => item.sName === label);

    const addState = await this.props.onGetData(slaveConfig, JSON.parse(searchSolution[iIndex].sCondition), 1, true);
    // const slaveFilterConditionOld = addState.slaveFilterCondition;
    this.props.onSaveState({
      show: !this.props.show,
      label,
      ...addState,
      // slaveFilterConditionOld,
    });
  }

  onMaskClick = () => {
    this.props.onSaveState({
      show: false,
    });
  }
  // eslint-disable-next-line react/sort-comp
  handleClick = () => {
    // e.preventDefault(); // Fix event propagation on Android
    this.props.onSaveState({
      show: !this.props.show,
    });
    // mock for async data loading
    if (!this.props.initData) {
      const data = [];
      const { searchOperation: searchOperationOld } = this.props;
      const childrenData = commonUtils.isEmptyArr(searchOperationOld) ? [] : searchOperationOld;
      if (commonUtils.isNotEmptyArr(childrenData)) {
        for (let i = 0; i < childrenData.length; i += 1) {
          const addStata = {};
          addStata.value = i;
          addStata.label = childrenData[i].text;
          data.push(addStata);
        }
      } else {
        this.props.onSaveState({
          show: false,
        });
      }
      if (!this.props.initData && commonUtils.isNotEmptyArr(data)) {
        setTimeout(() => {
          this.props.onSaveState({
            initData: data,
          });
        }, 500);
      }
    }
  }

  handleSearch = async (value, type) => {
    const { slaveConfig, sModelsId } = this.props;
    let { slaveFilterCondition } = this.props;
    if (commonUtils.isNotEmptyArr(slaveFilterCondition)) {
      slaveFilterCondition[0].bFilterValue = value;
    } else {
      const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.bFind);
      if (iIndex > -1) {
        slaveFilterCondition = [{ bFilterName: slaveConfig.gdsconfigformslave[iIndex].sName, bFilterCondition: 'like', bFilterValue: value }];
      }
    }
    if (type === 'searchScan') {
      /* 打钩 扫码出来的数据行  */
      const addState = await this.props.onGetData(this.props.slaveConfig, slaveFilterCondition, undefined, true);
      const slaveSelectedRowKeys = [];
      if (commonUtils.isNotEmptyObject(addState) && commonUtils.isNotEmptyArr(addState.slaveData)) {
        const slaveData = addState.slaveData;
        slaveData.forEach((item) => {
          slaveSelectedRowKeys.push(item.sSlaveId);
        });
        addState.slaveSelectedRowKeys = slaveSelectedRowKeys;

        /* 扫码后只查询到一条数据则自动调用copyTo */
        if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys) && slaveSelectedRowKeys.length === 1) {
          /* 查找复制到按钮名称 */
          const filterData = slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName === '' && commonUtils.isNotEmptyObject(item.sControlName) && item.sControlName.indexOf('BtnCopyTo') > -1);
          if (commonUtils.isNotEmptyArr(filterData) && filterData.length === 1) {
            // const BtnCopyToName = filterData[0].sControlName;
            setTimeout(() => {
              this.props.onCopyToClick(slaveData[0]);
            }, 500);
          }
        }
      }
      this.props.onSaveState({ ...addState });
      if (this.inputSearch) this.inputSearch.focus();
      return;
    }
    const addState = await this.props.onGetData(slaveConfig, slaveFilterCondition, undefined, true);
    if (commonUtils.isNotEmptyObject(addState)) {
      if (sModelsId === '12710101117217437977130' && commonUtils.isNotEmptyArr(addState.slaveData) && addState.slaveData.length === 1) { /* 一条时 默认选中 */
        const slaveSelectedRowKeys = [];
        const slaveData = addState.slaveData;
        const key = commonUtils.isNotEmptyObject(slaveData[0].sSlaveId) ? slaveData[0].sSlaveId : slaveData[0].sId;
        slaveSelectedRowKeys.push(key);
        addState.slaveSelectedRowKeys = slaveSelectedRowKeys;
      }
      addState.clearSearchValue = false;
      this.props.onSaveState({ ...addState });
      if (this.inputSearch) this.inputSearch.focus();
    }
  }
  onChangeScan = async (event) => {
    const file = event.target.files[0];
    if (file) {
      this.parseQrCode(file)
        .then((data) => {
          Toast.info(data);
        })
        .catch((error) => {
          Toast.fail(error.message);
        });
    }
    // this.parseLineCode(file);
  }

  // /**
  //  * 解析条形码（识别率太低，暂用不了）
  //  * @param {Blob} file 文件流
  //  */
  // async parseLineCode(file) {
  //   const src = URL.createObjectURL(file);
  //   Quagga.decodeSingle({
  //     src,
  //     decoder: {
  //       readers: ['code_128_reader'],
  //     },
  //     locate: true,
  //   }, (result) => {
  //     console.log('linecode', result);
  //     if (result.codeResult) {
  //       console.log('result', result.codeResult.code);
  //     } else {
  //       console.log('not detected');
  //     }
  //   });
  // }

  /**
   * 解析qrcode
   * @param {Blob} file 文件流
   */
  // async parseQrCode(file) {
  //   const imgData = await this.readImage(file);
  //   try {
  //     const result = jsQR(
  //       imgData.data,
  //       imgData.width,
  //       imgData.height,
  //     );
  //     return Promise.resolve(result.data);
  //   } catch (error) {
  //     return Promise.reject(new Error(`识别失败:${error.message}`));
  //   }
  // }

  /**
   * 文件解析为imageData
   * @param {Blob} file 文件流
   */
  // readImage = (file) => {
  //   return new Promise((resolve, reject) => {
  //     const reader = new FileReader();
  //     reader.onloadend = () => {
  //       // 读取文件
  //       const imageElement = document.createElement('img');
  //       imageElement.style.width = '100px';
  //       imageElement.src = reader.result;
  //       imageElement.onload = () => {
  //         // 把图片绘制到canvas，并获取imageData
  //         const canvas = document.createElement('canvas');
  //         const width = 300;
  //         // eslint-disable-next-line no-mixed-operators
  //         const height = (imageElement.height * width / imageElement.width);
  //         canvas.width = width;
  //         canvas.height = height;
  //         const g = canvas.getContext('2d');
  //         g.drawImage(imageElement, 0, 0, width, height);
  //         const imageData = g.getImageData(0, 0, width, height);
  //         resolve(imageData);
  //       };
  //       imageElement.onerror = () => {
  //         reject(new Error('图片加载失败'));
  //       };
  //     };
  //     reader.onerror = () => {
  //       reject(new Error('文件读取失败'));
  //     };
  //     reader.readAsDataURL(file);
  //   });
  // }
  handleScan = () => {
    BarCodeUtil.startScan((type, code) => {
      if (!commonUtils.isEmpty(code)) {
        this.handleSearch(code, 'searchScan');
        this.setState({
          scanValue: code,
        });
      }
    });
    // if (this.textInput) {
    //   this.textInput.click();
    // }
  }

  handleGetWxCode = async (successHandler) => {
    let scanResult = '';
    const { app } = this.props;
    // eslint-disable-next-line prefer-destructuring,no-unused-vars
    const userinfo = app.userinfo;
    const myUrl = location.href;
    const configUrl = `${commonConfig.server_host}wechat/getWxToken`;
    const values = {
      url: myUrl,
      sBrandsId: userinfo.sBrandsId,
      sSubsidiaryId: userinfo.sSubsidiaryId,
    };
    // const values = {
    //   url: myUrl,
    //   sBrandsId: '1111111111',
    //   sSubsidiaryId: '1111111111',
    // };
    const configReturn = (await commonServices.postValueService(null, values, configUrl)).data;
    console.log('configReturn::', configReturn, values);
    if (configReturn.code === 1) {
      const { rows } = configReturn.dataset;/* 获取费用分摊单据配置 */
      if (commonUtils.isNotEmptyArr(rows)) {
        const appId = rows[0].appId.toString();
        const nonceStr = rows[0].nonceStr.toString();
        const signature = rows[0].signature.toString();
        const timestamp = rows[0].timestamp.toString();
        weixin.config({
          beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId, // 必填，公众号的唯一标识
          timestamp, // 必填，生成签名的时间戳    <%= Html.Encode(ViewData["timestamp" ]) %>
          nonceStr, // 必填，生成签名的随机串
          signature, // 必填，签名
          jsApiList: ['checkJsApi', 'scanQRCode'], // 必填，需要使用的JS接口列表, 这里只需要调用扫一扫
        });
        weixin.ready(() => {
          weixin.checkJsApi({ // 判断当前客户端版本是否支持指定JS接口
            jsApiList: ['scanQRCode'],
            success(res) { // 以键值对的形式返回，可用true，不可用false。如：{"checkResult":{"scanQRCode":true},"errMsg":"checkJsApi:ok"}
              console.log(res);
              if (res.checkResult.scanQRCode !== true) {
                Toast.fail(`URL不对，当前URL：${myUrl}请使用正式地址！`);
              }
            },
            // eslint-disable-next-line no-unused-vars
            fail(res) { // 检测getNetworkType该功能失败时处理
              Toast.fail('checkJsApi error');
            },


          }); // wx.ready结束
          weixin.scanQRCode({
            desc: 'scanQRCode desc',
            needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
            scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
            success(res) {
              // console.log("调用扫描成功",res);
              scanResult = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
              if (commonUtils.isNotEmptyObject(scanResult)) {
                const codeResult = scanResult.split(',');
                if (codeResult.length > 1) {
                  scanResult = codeResult[1];
                }
              }
              successHandler(scanResult);
              // return scanResult;
              // console.log('微信扫码结果：', scanResult);
            },
            error(res) {
              // console.log(res);
              if (res.errMsg.indexOf('function_not_exist') > 0) {
                Toast.fail('版本过低请升级');
              }
            },
          });
        });
      } else {
        Toast.fail(configReturn.msg);
      }
    } else {
      Toast.fail(configReturn.msg);
    }
    return scanResult;
  }

  handleWxScan = async () => {
    this.handleGetWxCode((code) => {
      if (!commonUtils.isEmpty(code)) {
        this.handleSearch(code, 'searchScan');
        this.setState({
          scanValue: code,
        });
      }
    });
  }

  handleChangleInput = (value) => {
    this.setState({ scanValue: value });
  }
  // setTextInputRef = (element) => {
  //   this.textInput = element;
  // };

  handleCancel = () => {
    this.setState({ scanValue: '' });
    this.handleSearch('');
  }

  /** 修改主表数据 */
  handleMasterChange = async (name, sFieldName, changeValue, sId, dropDownData) => {
    this.props.onChange('master', sFieldName, changeValue, sId, dropDownData);
  };
  handleFilterSearch = (value) => {
    const { masterData, slaveFilterCondition: slaveFilterConditionOld, slaveConfig } = this.props;
    if (commonUtils.isNotEmptyArr(masterData) && commonUtils.isNotEmptyArr(slaveFilterConditionOld)) {
      // eslint-disable-next-line array-callback-return
      slaveFilterConditionOld.map(async (item) => {
        let filterOne = {};
        if (commonUtils.isNotEmptyArr(value)) {
          filterOne = value.filter(e => item.bFilterName === e.sName);
        }
        if (commonUtils.isNotEmptyArr(filterOne) && filterOne[0].sDropDownType === 'sql') {
          item.bFilterValue = masterData[item.bFilterName][0] ? masterData[item.bFilterName][0] : item.bFilterValue;
        } else {
          item.bFilterValue = masterData[item.bFilterName] ? masterData[item.bFilterName] : item.bFilterValue;
        }
      });
    }
    this.props.onGetData(slaveConfig, slaveFilterConditionOld);
    this.setState({ modal1: false });
  }
  handleFilterSearchCancle = () => {
    let { slaveFilterCondition: slaveFilterConditionOld } = this.props;
    const { slaveConfig, masterData } = this.props;
    if (commonUtils.isNotEmptyArr(slaveFilterConditionOld)) {
      // eslint-disable-next-line array-callback-return
      slaveFilterConditionOld.map((item) => {
        masterData[item.bFilterName] = '';
      });
      this.props.onSaveState({
        masterData,
        label: '',
      });
      slaveFilterConditionOld = [];
      this.props.onGetData(slaveConfig, slaveFilterConditionOld);
    }
    this.setState({ modal1: false });
  }
  render() {
    const {
      label, initData, show, slavePagination, token, slaveFilterCondition, slaveConfig, showScan, app, sModelsId, masterData,
    } = this.props;
    const allDataTitle = commonFunc.showLocalMessage(this.props, 'allData', '全部数据');
    const filter = commonFunc.showLocalMessage(this.props, 'filter', '筛选');
    const clearConditions = commonFunc.showLocalMessage(this.props, 'clearConditions', '清空条件');

    const btnSure = commonFunc.showLocalMessage(this.props, 'btnSure', '确定');

    const showName = [];
    const solutionData = [];
    if (commonUtils.isNotEmptyArr(slaveFilterCondition) && commonUtils.isNotEmptyArr(slaveConfig)) {
      const slaveConfigData = slaveConfig.gdsconfigformslave;
      // eslint-disable-next-line array-callback-return,no-unused-vars
      slaveFilterCondition.map((item, index) => {
        const iIndex = slaveConfigData.findIndex(i => i.sName === item.bFilterName);
        if (iIndex > -1) {
          solutionData.push(slaveConfigData[iIndex]);
          showName.push(slaveConfigData[iIndex].showName);
        }
      });
    }
    const total = commonUtils.isEmptyObject(slavePagination) ? 0 : slavePagination.total;
    const showlabel = commonUtils.isEmptyObject(label) ? allDataTitle : label;
    const downUrl = `${commonConfig.file_host}file/download?savePathStr=/home/monkey/xlyerp/modlePath/Down.png&sModelsId=100&token=${token}`;
    const upUrl = `${commonConfig.file_host}file/download?savePathStr=/home/monkey/xlyerp/modlePath/Up.png&sModelsId=100&token=${token}`;
    const imgUrl = show ? upUrl : downUrl;
    const tabs = [
      { title: <Badge text="">{filter} <img style={{ height: '15px', marginleft: '20px' }} src={downUrl} alt="" /></Badge> },
      {
        title:
  <Badge style={{ left: '0px' }} text={total}>{showlabel}
    <img style={{ height: '15px', marginleft: '20px' }} src={imgUrl} alt="" />
  </Badge>,
      },
    ];
    const menuEl = (
      <Menu
        className="single-foo-menu"
        data={initData}
        value={['1']}
        level={1}
        onChange={this.onChange}
        height={document.documentElement.clientHeight * 0.6}
      />
    );
    const loadingEl = (
      <div style={{
        position: 'absolute', width: '100%', height: document.documentElement.clientHeight * 0.6, display: 'flex', justifyContent: 'center',
      }}
      >
        <ActivityIndicator size="large" />
      </div>
    );

    return (
      <div>
        <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
          <div
            style={{
              backgroundImage: `url(${scan})`,
              backgroundSize: "cover",
              width: "30px",
              height: "30px",
              marginLeft: "8px",
              // eslint-disable-next-line no-undef
              display: `${showScan ? "block" : "none"}`,
            }}
            onClick={commonConfig.isWeiXin ? this.handleWxScan : this.handleScan}
          />
          <SearchBar
            placeholder={showName[0]}
            onSubmit={this.handleSearch}
            style={{ flex: 1 }}
            value={this.state.scanValue}
            onChange={this.handleChangleInput}
            onCancel={this.handleCancel}
            ref={el => {
              this.inputSearch = el;
            }}
          />
        </div>
        <Tabs
          tabs={tabs}
          initialPage={1}
          onChange={(tab, index) => {
            console.log("onChange", index, tab);
          }}
          onTabClick={(tab, index) => {
            if (index === 1) {
              this.handleClick();
            } else {
              this.setState({
                modal1: true,
              });
              this.props.onSaveState({
                show: false,
              });
            }
          }}
        >
          <div />
          <div />
        </Tabs>

        <div>
          {show ? (initData ? menuEl : loadingEl) : null}
          {show ? <div className="menu-mask" onClick={this.onMaskClick} /> : null}
        </div>

        <Modal
          popup
          visible={this.state.modal1}
          onClose={this.onClose("modal1")}
          animationType="slide-down"
          className={styles.modal}
          // afterClose={() => { alert('afterClose'); }}
        >
          <List className={styles.filterListContent} renderHeader={() => `${showlabel}`}>
            {solutionData.map((item, index) => {
              const showTypeProps = {
                app,
                record: {},
                sId: item.sId /*   修改当前编号(数据格式:字符串)   */,
                name: "slave",
                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: item,
                formItemLayout: {},
                textArea: false,
                enabled: true,
                dataValue: commonUtils.isNotEmptyObject(masterData) ? masterData[item.sName] : "",
                bTable: true,
                onFilterDropDownData: this.props.onFilterDropDownData,
                onSaveState: this.props.onSaveState,
              };
              return (
                <div>
                  {/* eslint-disable-next-line react/no-array-index-key */}
                  <div className={styles.filterItem} key={index}>
                    <ShowType {...showTypeProps} />
                  </div>
                  <WhiteSpace size="sm" />
                </div>
              );
            })}
            <List.Item className={`${styles.filterList} ${styles.filterListBtn}`}>
              <Flex>
                <Flex.Item>
                  {" "}
                  <Button style={{ background: "#f0f0f0", color: "#000" }} onClick={this.handleFilterSearchCancle}>
                    {clearConditions}
                  </Button>
                </Flex.Item>
                <Flex.Item>
                  {" "}
                  <Button type="primary" onClick={this.handleFilterSearch.bind(this, solutionData)}>
                    {btnSure}
                  </Button>
                </Flex.Item>
              </Flex>
            </List.Item>
          </List>
        </Modal>
      </div>
    );
  }
}
const CommobileSearchComponentMobile = createForm()(CommobileSearchComponent);
export default CommobileSearchComponentMobile;

