import React, { useContext, useEffect, useState, useRef } from 'react';
import './index.less'
import { MyContext } from '../../utils/contextManage';
import { ActiveTableProps } from '../../index.d'
import GPanel from "../../components/GPanel";
import { GPanelProps } from "../../components/GPanel";
import LeftTable from "../../components/LeftTable";
import RightContent from "../../components/RightContent";
import LeftToolButton from "../../components/LeftToolButton";
import RightToolButton from "../../components/RightToolButton"
import { Button, message, Modal } from 'antd';
import { FolderAddOutlined, SaveOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';


const ContextChild: React.FC<ActiveTableProps> = (props) => {
  const childRef = useRef<any>(null);
  const { state } = useContext(MyContext);
  const { tableRrn, panelLayOut, offsetHeight = 0, rightToolBtns } = props
  console.log('ContextChild的props', props)
  const [tableInfo, setTableInfo] = useState<any>({})
  const [leftTableDataList, setLeftTableDataList] = useState<any[]>([])
  const [panelInfo, setPanelInfo] = useState<any>({})
  const [leftSelectedDetail, setLeftSelectedDetail] = useState<any>({})
  const [referRuleInfo, setReferRuleInfo] = useState<any>({})
  const [searchParam, setSearchParam] = useState<any>({})
  const [createRefresh, setCreateRefresh] = useState<any>(0)

  let btns: any = [
    {
      key: 'create',
      name: '新建',
      icon: <FolderAddOutlined />,
      display: true,
      disabled: false,
      click: function () {
        if (childRef.current) {
          // 清空右侧表单
          childRef.current.changeVal()
          // 清空左侧表格勾选
          setLeftSelectedDetail({})
          setCreateRefresh(new Date().getTime())
        }
      }
    },
    {
      key: 'save',
      name: '保存',
      icon: <SaveOutlined />,
      display: true,
      disabled: false,
      click: function ({ tableInfo, formValidate }: any) {
        // todosm
        console.log('tableInfo', tableInfo);
        if (childRef.current) {
          formValidate().then((res: any) => {
            console.log('表单校验values:', res)
            const values = res.data
            const fullFormContent = res.fullFormContent
            const saveType = fullFormContent.OBJECTRRN ? 'UPDATEENTITY' : 'SAVEENTITY'
            const xModelData = JSON.stringify({
              ...values,
              OBJECTRRN: fullFormContent.OBJECTRRN,
              ADTABLERRN: tableInfo.OBJECTRRN,
            })
            const params = {
              ACTIONTYPE: saveType,
              ENTITYMODEL: tableInfo.MODELCLASS,
              XMODELDATA: xModelData
            }
            console.log('保存参数', params);
            state.cudEntity(params)
              .then((res: any) => {
                if (res.Header.RESULT === 'SUCCESS') {
                  console.log('保存成功', res)
                  message.success('保存成功')
                  // 更新右侧表单数据fullFormContent
                  const resData = { ...res.Body.DATA }
                  if (childRef.current) {
                    childRef.current.saveRefresh(resData)
                  }
                } else {
                  console.log('保存失败');
                }
              })
              .catch((err: any) => {
                console.log('保存失败，todo解锁加载中', err)
              })
          }).catch((err: any) => {
            console.log('校验失败', err)
          })
        }
      }
    },
    {
      key: 'delete',
      name: '删除',
      icon: <DeleteOutlined />,
      display: true,
      disabled: !(leftSelectedDetail.OBJECTRRN),
      click: function ({ tableInfo }: any) {
        // todosm
        console.log('leftSelectedDetail', leftSelectedDetail);
        Modal.confirm({
          title: 'warning',
          icon: <ExclamationCircleOutlined />,
          style: { top: 20 },
          content: '确认删除吗?',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            certainDelete(tableInfo)
          },
          onCancel() {
          }
        })
      }
    }
  ]
  // 确认删除
  const certainDelete = (tableInfo: any) => {
    const params = {
      ACTIONTYPE: 'DELETEENTITY',
      ENTITYMODEL: tableInfo.MODELCLASS,
      OBJECTRRN: `${leftSelectedDetail.OBJECTRRN}`
    }
    console.log('删除参数', params)
    state.cudEntity(params)
      .then((res: any) => {
        if (res.Header.RESULT === 'SUCCESS') {
          message.success('删除成功')
          if (childRef.current) {
            childRef.current.deleteRefresh({})
          }
        } else {
          console.log('删除失败');
        }
      })
      .catch((err: any) => {
        console.log('请求失败，todo解锁加载中', err)
      })
  }
  // 处理外部传入的按钮
  if (rightToolBtns && rightToolBtns.length > 0) {
    const rightToolButtons = [...rightToolBtns]
    const tempBtns = []
    for (let v of rightToolButtons) {
      if (btns.some((it: any) => it.key === v.key)) {
        let btnIndex = btns.findIndex((item: any) => Object.is(item.key, v.key))
        const newBtn = { ...btns[btnIndex], ...v }
        btns.splice(btnIndex, 1, newBtn)
      } else {
        if (v.before) {
          // before 代表外部传入按钮的插入位置
          let beforeIndex = btns.findIndex((item: any) => item.key === v.before)
          if (beforeIndex === -1) {
            tempBtns.push(v)
          } else {
            btns.splice(beforeIndex, 0, v)
          }
        } else {
          tempBtns.push(v)
        }
      }
    }
    btns = tempBtns.concat(btns)
  }

  useEffect(() => {
    console.log('tableRrn', tableRrn)
    if (tableRrn && state.getEntity) {
      state.getEntity({
        ENTITYMODEL: state.entityModel,
        OBJECTRRN: tableRrn
      }).then((res: any) => {
        if (res.Header.RESULT === 'SUCCESS') {
          console.log(res.Body.DATA)
          const adTable = res.Body.DATA
          setTableInfo(adTable)
        }
      }).catch((err: any) => {
        console.log('请求失败，todo解锁加载中', err)
      })
    }
  }, [tableRrn, state.getEntity])
  // 参考规则栏位实现级联
  const handleReferRule = () => {
    const obj = {} as any
    tableInfo.ADFIELDLIST?.filter((x: any) => x.REFERENCERULE && /[a-zA-Z0-9]+.[a-zA-Z0-9]+/g.test(x.REFERENCERULE))
      .forEach((x: any) => {
        const arr = x.REFERENCERULE.toUpperCase().split('.')
        const key = arr[0]
        const value = arr[1]
        if (obj[key]) {
          obj[key].push({ name: x.NAME, value })
        } else {
          obj[key] = [{ name: x.NAME, value }]
        }
      })
    setReferRuleInfo(obj)
  }
  useEffect(() => {
    if (tableInfo) {
      const obj: GPanelProps = {} as GPanelProps
      const { LABELZH, LABEL } = tableInfo
      obj.lTitle = state.lang === 'zh-CN' ? `${LABELZH || ''}列表` : `${LABEL || ''} List`
      obj.rTitle = state.lang === 'zh-CN' ? `${LABELZH || ''}详细信息` : `${LABEL || ''} Detail Information`
      setPanelInfo(obj)
      handleReferRule()
    }
  }, [tableInfo])
  const changeFormDetail = (detail: any) => {
    if (props.changeFormDetail) {
      setLeftSelectedDetail(props.changeFormDetail(detail))
    }
    setLeftSelectedDetail(detail)
  }
  const handleBooleanField = (record: any) => {
    let detail = { ...record }
    const booleanFieldList = tableInfo.ADFIELDLIST.filter((x: any) => x.DISPLAYTYPE === 'boolean')
    Object.keys(record).forEach(function (key) {
      if (booleanFieldList.some((x: any) => x.NAME.toUpperCase() === key)) {
        // @ts-ignore
        detail[key] = detail[key] === 'Y' || detail[key] === true
      }
    })
    changeFormDetail(detail)
  }
  const handleSelectedDetail = (record: any) => {
    if (!record.OBJECTRRN) {
      handleBooleanField(JSON.parse(JSON.stringify(record)))
    } else {
      const params = {
        ENTITYMODEL: tableInfo.MODELCLASS,
        OBJECTRRN: record.OBJECTRRN
      }
      state.getEntity(params).then((res: any) => {
        if (res.Header.RESULT === 'SUCCESS') {
          handleBooleanField(res.Body.DATA)
        }
      })
    }
  }
  const ale = () => {
    setLeftSelectedDetail({ NAME: 'TEST' })
  }
  const handleDataListChange = (data: any) => {
    // 用于判断删除表格某行数据的刷新
    setLeftTableDataList([...data])
  }
  const renderLeftContent = () => {
    if (props.renderLeftContent) return props.renderLeftContent(tableInfo, { ale })
    return <LeftTable offsetHeight={offsetHeight} {...tableInfo} onChange={handleSelectedDetail}
      searchParam={searchParam} createRefresh={createRefresh} onDataListChange={handleDataListChange}
    />
  }
  const height = document.documentElement.clientHeight - offsetHeight

  const renderRightContent = () => {
    if (props.renderRightContent) return props.renderRightContent(tableInfo, { ale })
    return <div style={{ height: `${height - 100}px`, overflow: 'auto', padding: '0 15px' }}>
      <RightContent
        {...tableInfo}
        formDetail={leftSelectedDetail}
        tableDataList={leftTableDataList}
        referRuleInfo={referRuleInfo}
        cRef={childRef}
        onChange={(val: any) => {
          console.log(val)
        }}
        onRefresh={(r: any) => {
          setSearchParam({ ...r, ...searchParam })
        }}
      />
    </div>
  }
  // 左边按钮
  const renderLeftToolButton = () => {
    if (tableInfo.ADFIELDLIST && tableInfo.ADFIELDLIST.length > 0) {
      return <LeftToolButton
        fieldList={tableInfo.ADFIELDLIST}
        referRuleInfo={referRuleInfo}
        onSearchHandleOk={(v: any) => {
          console.log('搜索执行', v)
          setSearchParam(v)
          // 置空左侧表格单击
          setLeftSelectedDetail({})
          setCreateRefresh(new Date().getTime())
        }}
        onRefresh={() => { setSearchParam({}); setLeftSelectedDetail({}) }}
      />
    } else {
      return <div />
    }
  }
  // 右边按钮
  const renderRightToolButton = () => {
    const btnComps = btns.map((it: any) => {
      const display = it.hasOwnProperty('display') ? (typeof (it.display) === 'function' ? it.display(leftSelectedDetail) : it.display) : true
      // console.log('display', display);    
      return display ? (<Button
        key={it.key}
        icon={it.icon}
        disabled={typeof (it.disabled) === 'function' ? it.disabled(leftSelectedDetail) : it.disabled}
        onClick={() => {
          it.click({
            tableInfo,
            leftSelectedDetail,
            leftTableDataList,
            ...childRef.current
          })
        }}
      >{it.name}</Button>) : null
    })
    return <RightToolButton>{...btnComps}</RightToolButton>
  }

  return (<div>
    {
      tableInfo.OBJECTRRN ?
        <GPanel
          rTitle={panelInfo.rTitle}
          lTitle={panelInfo.lTitle}
          lColSpanC={panelLayOut ? panelLayOut.l : 8}
          rColSpanC={panelLayOut ? panelLayOut.r : 16}
          lToolButton={renderLeftToolButton()}
          lContent={renderLeftContent()}
          rToolButton={renderRightToolButton()}
          rContent={renderRightContent()}
        /> : <div>loading...</div>
    }
  </div>
  )
};

export default ContextChild;
