import React, {useEffect, useContext, useState} from 'react';
import {MyContext} from '../../utils/contextManage';
import GTable from "../GTable";

// 不需要编辑的表格
const GTableList: React.FC<any> = (props) => {
  const {REFTABLERRN, DISPLAYTYPE, detail, customTableProps, value, onChange} = props
  const {state} = useContext(MyContext);
  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 [tableId, setTableId] = useState<any>('')
  useEffect(() => {
    getRefTableInfo()
  }, [])
  useEffect(() => {
    if (dataListParams && dataListParams.ENTITYMODEL) {
      getDataList()
    }
  }, [dataListParams, DISPLAYTYPE])
  useEffect(() => {
    if (needWatchFields.length > 0 && needReGet && oldDetail) {
      const isNeedReGet = needWatchFields.some((x: string | number) => detail[x] !== oldDetail[x])
      isNeedReGet && getDataList()
      setOldDetail(detail)
    }
  }, [detail])
  const getRefTableInfo = () => {
    const params = {
      ENTITYMODEL: state.refTableEntityModel,
      OBJECTRRN: REFTABLERRN
    }
    state.getEntity(params)
        .then((res: any) => {
          if (res.Header.RESULT === 'SUCCESS') {
            const refInfo = res.Body.DATA
            getTableInfo(refInfo)
            setTableId(refInfo.TABLERRN)
          }
        })
        .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)
          }
        })
        .catch((err: any) => {
          console.log('请求失败，todo解锁加载中', err)
        })
  }
  const getDataList = () => {
    if (value) {
      setDataList(value)
      onChange(value)
      return
    }
    const WHERECLAUSE = dataListParams.WHERECLAUSE
    const params = JSON.parse(JSON.stringify(dataListParams))
    if (WHERECLAUSE && ~WHERECLAUSE.indexOf(':')) {
      setNeedReGet(true)
    }
    setDataList([])
    onChange([])
    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
    console.log('gtablelist的数据请求参数', params);
    
    state.getEntityList(params).then((res: any) => {
      // 表格数据加key字段
      const keyData = [...res.Body.DATALIST]
      for (let i = 0; i < keyData.length; i++) {
        if (keyData[i].OBJECTRRN) {
          keyData[i].key = keyData[i].OBJECTRRN
        }
        keyData[i].ADTABLERRN = tableId;
      }
      console.log('keyData', keyData);
      setDataList(keyData)
      onChange(keyData)
    }).catch((err: any) => {
      console.log('请求失败，todo解锁加载中', err)
    })
  }

  return (
      <GTable columns={columns || []}
              size="small"
              dataSource={value || dataList || []}
              rowKey={(r: any) => r.key}
              pagination={false}
              {...customTableProps}
      />
  );
};

export default GTableList;


