import React, {useEffect, useContext, useState} from 'react';
import {MyContext} from '../../utils/contextManage';
import TableSelect from "../TableSelect";
// @ts-ignore
import sqlUtil from '../../utils/sqlUtil'

const GRefTable: React.FC<any> = (props) => {
  const {REFTABLERRN, DISPLAYTYPE, value, disabled, detail, onChange, referRule, onReferChange} = props
  const {state} = useContext(MyContext);
  const [options, setOptions] = useState<any>()
  const [dataListParams, setDataListParams] = useState<any>({})
  const [columns, setColumns] = useState<any>()
  const [needReGet, setNeedReGet] = useState<boolean>(false)
  const [dataList, setDataList] = useState<any[]>([])
  const [needWatchFields, setNeedWatchFields] = useState<any>([])
  const [oldDetail, setOldDetail] = useState<any>({})
  const [type, setType] = useState<string>('')
  useEffect(() => {
    setType(DISPLAYTYPE.toUpperCase())
    getRefTableInfo()
  }, [])
  useEffect(() => {
    const type = DISPLAYTYPE.toUpperCase()
    if (dataListParams && dataListParams.ENTITYMODEL && (type === 'REFTABLE' || type === 'REFTABLECOMBO')) {
      getDataList()
    }
  }, [dataListParams, DISPLAYTYPE])
  useEffect(() => {
    if (needWatchFields.length > 0 && needReGet && oldDetail) {
      const type = DISPLAYTYPE.toUpperCase()
      if ((type === 'REFTABLE' || type === 'REFTABLECOMBO')) {
        const isNeedReGet = needWatchFields.some((x: string | number) => detail[x] !== oldDetail[x])
        isNeedReGet && getDataList()
        setOldDetail(detail)
      }
    }
  }, [detail])

  // 初始化时，出发参考值逻辑
  // useEffect(() => {
  //   if (detail && !isInited && dataList && dataList.length > 0) { 
  //     setIsInited(true)
  //     handleReferChange(detail[NAME.toUpperCase()])
  //   }
  // }, [detail,dataList])
  
  const getRefTableInfo = () => {
    const params = {
      ENTITYMODEL: state.refTableEntityModel,
      OBJECTRRN: REFTABLERRN
    }
    state.getEntity(params)
        .then((res: any) => {
          if (res.Header.RESULT === 'SUCCESS') {
            console.log('getRefTableInfo', res.Body.DATA)
            const refInfo = res.Body.DATA
            let value = refInfo.KEYFIELD.toUpperCase()
            const type = DISPLAYTYPE.toUpperCase()
            if (type !== 'REFTABLE' && type !== 'REFTABLECOMBO') {
              value = value === 'KEY' ? 'KEYID' : value
            }
            const textField = refInfo.TEXTFIELD.toUpperCase()
            setOptions({
              value,
              LABEL: textField === 'ID' ? 'NAME' : textField,
              queryKey: refInfo.KEYFIELD,
              queryLABEL: refInfo.TEXTFIELD
            })
            console.log('options', refInfo)
            getTableInfo(refInfo)
          }
        })
        .catch((err: any) => {
          console.log('请求失败，todo解锁加载中', err)
        })
  };
  const getTableInfo = (info: any) => {
    const params = {
      ENTITYMODEL: state.entityModel,
      OBJECTRRN: info.TABLERRN
    }
    state.getEntity(params)
        .then((res: any) => {
          if (res.Header.RESULT === 'SUCCESS') {
            console.log('getTableInfo', res.Body.DATA)
            const tableInfo = res.Body.DATA
            const WHERECLAUSE = (info.WHERECLAUSE && tableInfo.WHERECLAUSE)
                ? `${info.WHERECLAUSE} and ${tableInfo.WHERECLAUSE}`
                : `${info.WHERECLAUSE || ''}${tableInfo.WHERECLAUSE || ''}`
            setDataListParams({
              WHERECLAUSE,
              ENTITYMODEL: tableInfo.MODELCLASS,
              ORDERBYCLAUSE: tableInfo.ORDERBYCLAUSE,
              MAX: 100
            })
            const isZh = state.lang === 'zh-CN'
            const cols = tableInfo.ADFIELDLIST
                .filter((x: any) => x.ISMAIN)
                .filter((x: any) => x.ISDISPLAY)
                .sort((a: any, b: any) => a.SEQNO - b.SEQNO)
                .map((item: any) => ({
                  title: isZh ? item.LABELZH : item.LABEL,
                  dataIndex: item.NAME.toUpperCase()
                }))
            setColumns(cols)
            const type = DISPLAYTYPE.toUpperCase()
            console.log('字段显示类型displaytype', type)
            switch (type) {
              case 'REFTABLE':
              case 'REFTABLECOMBO':
                break
              case 'SYSREFLIST':
              case 'SYSREFCOMBO':
                getAdreflist(props.REFLISTNAME)
                break
              case 'USERREFLIST':
              case 'USERREFCOMBO':
                getAdureflist(props.UREFLISTNAME)
                break
            }
          }
        })
        .catch((err: any) => {
          console.log('请求失败，todo解锁加载中', err)
        })
  }
  const getDataList = (inputValue?: string) => {
    const WHERECLAUSE = dataListParams.WHERECLAUSE
    const params = JSON.parse(JSON.stringify(dataListParams))
    if (WHERECLAUSE && ~WHERECLAUSE.indexOf(':')) {
      setNeedReGet(true)
    }
    setDataList([])
    let clauseWithData = WHERECLAUSE
    const needWatches: any[] = []
    const regexp = RegExp(':[a-zA-Z0-9]+', 'g');
    let match;
    while ((match = regexp.exec(WHERECLAUSE)) !== null) {
      const key = match[0].substr(1).toUpperCase()
      needWatches.push(key)
      if (detail[key]) {
        clauseWithData = clauseWithData.replace(match[0], `'${detail[key]}'`)
      }
    }
    setNeedWatchFields(needWatches)
    if (clauseWithData && ~clauseWithData.indexOf(':')) {
      return
    }
    params.WHERECLAUSE = clauseWithData
    if (inputValue) {
      const queryParams = {
        [`${options.queryLABEL}_like`]: inputValue
      }
      if (queryParams) {
        const sqlwhere = sqlUtil.convertSqlWhere(queryParams)
        if (sqlwhere) {
          params.WHERECLAUSE = params.WHERECLAUSE ? params.WHERECLAUSE + ' and ' + sqlwhere : sqlwhere
        }
      }
    } else {
      const defaultVal = detail[props.NAME] || props.DEFAULTVALUE
      if (defaultVal) {
        const name = `${options.queryKey} = '${defaultVal}'`
        if (params.WHERECLAUSE) {
          params.WHERECLAUSE = `${params.WHERECLAUSE} and ${name}`
        } else {
          params.WHERECLAUSE = name
        }
      }
    }
    console.log(params)
    state.getEntityList(params).then((res: any) => {
      // if (res.Header.RESULT === 'SUCCESS') {
      // }
      setDataList(res.Body.DATALIST)
    }).catch((err: any) => {
      console.log('请求失败，todo解锁加载中', err)
    })
  }

  const getAdreflist = (refname: string) => {
    const params = {
      ACTIONTYPE: 'GETDETAIL',
      REFERENCENAME: refname,
      LEVEL:10
    }
    state.adreflist(params).then((res: any) => {
      if (res.Header.RESULT === 'SUCCESS') {
        setDataList(res.Body.REFLIST)
      } else {
        setDataList([])
      }
    }).catch((err: any) => {
      console.log('请求失败，todo解锁加载中', err)
    })
  }
  const getAdureflist = (refname: string) => {
    const params = {
      'ACTIONTYPE': 'GETDETAIL',
      'REFERENCENAME': refname,
      'LEVEL':10
    }
    state.adureflist(params).then((res: any) => {
      if (res.Header.RESULT === 'SUCCESS') {
        setDataList(res.Body.REFLIST)
      } else {
        setDataList([])
      }
    }).catch((err: any) => {
      console.log('请求失败，todo解锁加载中', err)
    })
  }
  // const handleSelectChange = (val: any) => {
  //   if (onChange) {
  //     onChange(val)
  //   }
  //   handleReferChange(val)
  // }
  const handleReferChange = (val: any) => {
    if (referRule && referRule.length > 0 && dataList && dataList.length > 0) {
      if (!val) { 
        const obj: any = {}
        referRule.forEach((x: any) => {
          obj[x.name.toUpperCase()] = undefined
        })
        onReferChange(obj)
        return ;
      }
      const key = options.value
      const selectOne = dataList.find(x => x[key] === val)
      console.log('handleReferChange中的selectOne和referRule', selectOne, referRule);
      
      if (selectOne) { 
        const obj: any = {}
        referRule.forEach((x: any) => {
          obj[x.name.toUpperCase()] = selectOne[x.value]
        })
        if (onReferChange) {
          onReferChange(obj)
        }
      }
    }
  }
  const handleInputChange = (val: any) => {
    getDataList(val)
  }
  const handleOnChange = (val: any) => {
    console.log('TableSelect val..', val)
    if (onChange) { 
      onChange(val)
    }
    handleReferChange(val)
  }
  return (
      <TableSelect options={options}
                   searchFromApi={type === 'REFTABLE' || type === 'REFTABLECOMBO'}
                   dataSource={dataList}
                   // onSelect={handleSelectChange}
                   onChange={handleOnChange}
                   onSearch={handleInputChange}
                   columns={columns}
                   value={value}
                   disabled={disabled}
      />
  );
};

export default GRefTable;
