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

const GTableWithReferenceRule: React.FC<any> = (props) => {
  console.log('GTableWithReferenceRule的props', props);
  const {fields, dataSource, ...restProps} = props;
  const { state } = useContext(MyContext);
  useEffect(() => {
    if (props.fields && dataSource) {
      getFieldsRefAndRule()
    }
  }, [props.fields, dataSource])
  const [mergeData, setMergeData] = useState<any>([])
  function unique(arr: any[]) {
    return arr.reduce((prev, cur) => prev.includes(cur) ? prev : [...prev, cur], [])
  }

  const getFieldsRefAndRule = () => {
    if (!(fields && fields.length > 0)) return
    let ruleList: any[] = []
    fields.filter((x: any) => x.REFERENCERULE && x.ISMAIN && /[a-zA-Z0-9]+.[a-zA-Z0-9]+/g.test(x.REFERENCERULE))
      .forEach((x: any) => {
      const arr = x.REFERENCERULE.split('.')
      const key = arr[0]
      const value = arr[1]
      ruleList.push({name: x.NAME, key, value})
    })
    if (ruleList.length === 0) { 
      setMergeData(dataSource)
      return
    }
    ruleList = ruleList.map((x: any) => {
      const obj = {...x}
      const findOne = fields.find((field: any) => field.NAME.toUpperCase() === x.key.toUpperCase())
      if (findOne) {
        const type = findOne.DISPLAYTYPE.toUpperCase()
        if (type === 'REFTABLE' || type === 'REFTABLECOMBO') {
          obj.refTableRrn = findOne.REFTABLERRN
        }
      }
      return obj
    })
    const refTableRrnListInfo = ruleList.filter(x => x.refTableRrn)
    const refTableRrnList = refTableRrnListInfo.map(x => x.refTableRrn)
    if (refTableRrnList.length === 0) return
    const rrnString = unique(refTableRrnList).join(", ")
    const params = {
      ENTITYMODEL: state.refTableEntityModel,
      WHERECLAUSE: `objectRrn in (${rrnString}) `
    }
    state.getEntityList(params).then((res: any) => {
      const tableRrnList = res.Body.DATALIST
      const result = refTableRrnListInfo.map((x: any) => {
        const obj = {...x}
        const findOne = tableRrnList.find((table: any) => table.OBJECTRRN === x.refTableRrn)
        obj.tableRrn = findOne.TABLERRN
        obj.keyField = findOne.KEYFIELD
        return obj
      })
      handleRefRrn(result)
      console.log(res)
    }).catch((err: any) => {
      console.log('请求失败，todo解锁加载中', err)
    })
  }
  const handleRefRrn = (result: any) => {
    const rrnList = result.filter((x: any) => x.tableRrn).map((x: any) => x.tableRrn)
    const wherein = "'"+unique(rrnList).join("', '")+"'";
    const params = {
      ENTITYMODEL: state.entityModel,
      WHERECLAUSE: `objectRrn in (${wherein}) `
    }
    state.getEntityList(params).then((res: any) => {
      const tableRrnList = res.Body.DATALIST
      const resultTables = result.map((x: any) => {
        const findOne = tableRrnList.find((table: any) => table.OBJECTRRN === x.tableRrn)
        return {...x, ...findOne}
      })
      handleTableModel(resultTables)
    }).catch((err: any) => {
      console.log('请求失败，todo解锁加载中', err)
    })
  }
  const handleTableModel = (entityModelInfoList: any) => {
    const modelObj: any = {}
    entityModelInfoList.forEach((x: any) => {
      modelObj[x.MODELCLASS] = x
    })
    let originList = JSON.parse(JSON.stringify(dataSource))
    const requestList: any[] = []
    Object.keys(modelObj).forEach(function (key) {
      console.log('key', key)
      const obj = modelObj[key]
      const keyName = obj.key
      const uppercaseKeyName = keyName.toUpperCase()
      const dataListValueOfTheKey = (props.dataSource || []).filter((x: any) => x[uppercaseKeyName]).map((x: any) => x[uppercaseKeyName])
      if (dataListValueOfTheKey && dataListValueOfTheKey.length > 0) { 
        const wherein = "'"+unique(dataListValueOfTheKey).join("', '")+"'";
        const tableParam = {
          ENTITYMODEL: obj.MODELCLASS,
          WHERECLAUSE: `${obj.keyField} in (${wherein}) `
        }
        requestList.push({name: key, request: state.getEntityList(tableParam)})
      }
    })
    Promise.all(requestList.map(x => x.request)).then((values: any) => {
      values.forEach((res: any, i: number) => {
        // entityMdel
        const key = requestList[i].name
        // entityModel对应的Adtable配置
        const obj = modelObj[key]
        //参考数据map {[keyField对应的值]: value }
        const referenceDataStore = new Map()
        // 每个entitymodel返回的数据 
        const list = res.Body.DATALIST ? res.Body.DATALIST : []
        list.forEach((x: any) => {
          referenceDataStore.set(x[obj.keyField.toUpperCase()], x)
        })
        // console.log('entityMdel', obj.key)
        // console.log('refrence', obj)
        // console.log('obj.keyField',obj.keyField)
        // console.log('referenceDataStore',referenceDataStore)
        const newList = originList.map((x: any) => {
          const das = {...x}
            entityModelInfoList.forEach((ref: any) => {
              // console.log('ref', ref)
              const info = referenceDataStore.get(das[ref.key.toUpperCase()])
              if (info) { 
                // 如果本身有值则不参考
                if (!das[ref.name.toUpperCase()]) {
                  das[ref.name.toUpperCase()] = info[ref.value.toUpperCase()]
                }
              }
            })
          return das
        })
        originList = newList
      })
      setMergeData(originList)
    })
  }
  return (<GTable {...restProps} dataSource={mergeData}/>);
};

export default GTableWithReferenceRule;
