import React, { useContext, useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import './index.less'
import { Form, Input, Tabs, Row, Col } from 'antd'
import { MyContext } from "../../utils/contextManage";
import ActiveField from "../ActiveField";
// @ts-ignore
import { handleFormDetail,modelFormDetailToBoolean } from "../../utils/common.js"

// export interface RightContentProps {
//   ADFIELDLIST: any[]
//   ADTABLIST?: any[]
//   referRuleInfo: any
//   onChange: (val: any) => void
//   formDetail: any
//   cRef: any
// }
export interface RightContentProps {
  [propsName: string]: any
}

const { TabPane } = Tabs;
const RightContent: React.FC<RightContentProps> = (props) => {
  console.log('RightContent的props', props);

  const { state } = useContext(MyContext);
  const { ADFIELDLIST = [], formDetail = {}, tableDataList = [], ADTABLIST = [], referRuleInfo, cRef, onRefresh } = props
  const [tableMainForm] = Form.useForm();
  const [fullFormContent, setFullFormContent] = useState<any>({})
  const [refValues, setRefValues] = useState<any>({})

  useEffect(() => {
    if (formDetail) {
      tableMainForm.resetFields()
      setFullFormContent(formDetail)
    }
  }, [formDetail])

  useEffect(() => {
    tableMainForm.setFieldsValue({ ...fullFormContent, ...refValues })
  }, [fullFormContent, refValues])

  // 处理右上按钮点击事件
  useImperativeHandle(cRef, () => ({
    // 暴露给父组件的方法
    changeVal: () => {
      console.log('触发子组件事件');
      // 新建，清空右侧form
      tableMainForm.resetFields()
      setFullFormContent({})
    },
    formValidate: () => {
      return new Promise((resolve, reject) => {
        tableMainForm.validateFields()
          .then((values: any) => {
            const adFieldList = JSON.parse(JSON.stringify(ADFIELDLIST))
              .filter((x: any) => x.ISDISPLAY) || []
            // console.log('adFieldList', adFieldList)
            const data = handleFormDetail(values, adFieldList)
            console.log('处理过的data', data);
            const res = {
              data,
              fullFormContent
            }
            resolve(res)
          })
          .catch((err: any) => {
            // console.log('校验失败',err)
            reject(err)
          })
      })
    },
    deleteRefresh: (resData: any) => {
      // 清除搜索条件刷新左侧表格:cleanSearchRefresh: true;不清除搜索刷新:cleanSearchRefresh: false;
      // 是否留着当前页: isCurrentPage: true
      // 取消勾选:cleanSelected: true; 不取消勾选: cleanSelected: false
      let initialParams = {
        cleanSearchRefresh: true,
        isCurrentPage: false,
        cleanSelected: true
      }
      if (tableDataList.length > 1) {
        initialParams.cleanSearchRefresh = false
        initialParams.isCurrentPage = true
      }
      onRefresh(initialParams)
      // 清空右侧表单数据
      tableMainForm.resetFields()
      setFullFormContent(resData)
    },
    saveRefresh: (resData: any) => {
      // 刷新左侧表格,不取消勾选
      let initialParams = {
        cleanSearchRefresh: false,
        isCurrentPage: true,
        cleanSelected: false
      }
      onRefresh(initialParams)
      setFullFormContent(modelFormDetailToBoolean(resData))
    },
    freshLeftTable: (param: {cleanSearchRefresh: boolean; isCurrentPage: boolean; cleanSelected: boolean}) => {
      onRefresh(param)
    },
    setFormData: (resData: any) => {
      setFullFormContent(modelFormDetailToBoolean(resData))
    },
    formInstance: tableMainForm
  }));



  // 基础信息 数据里有ISBASIC字段
  const renderBasicInfo = () => {
    const isZh = state.lang === 'zh-CN'
    const list = JSON.parse(JSON.stringify(ADFIELDLIST))
      .filter((x: any) => x.ISBASIC && x.ISDISPLAY)
      .sort((a: any, b: any) => a.SEQNO - b.SEQNO) || []
    console.log('动态表单数据adfieldlist', list)
    return (
      list.length > 0 ?
        <>
          <div style={{
            height: '30px',
            fontWeight: 'bold',
            borderBottom: '1px solid #e8e8e8',
            marginBottom: '15px'
          }}>{isZh ? '基本信息' : 'Basic Info'}
          </div>
          <Row gutter={24}>
            {list.map(
              (item: any) => <Col span={24 / (props.GRIDYBASIC || 1)}>
                <ActiveField
                  key={item.OBJECTRRN}
                  field={item}
                  referRuleInfo={referRuleInfo}
                  formDetail={fullFormContent}
                  onChange={(val) => {
                    setRefValues({ ...val })
                  }} />
              </Col>)}
          </Row>
        </> : <div />)
  }
  // 动态选项卡， 没有ISBASIC字段
  const renderTabs = () => {
    const isZh = state.lang === 'zh-CN'
    const tabList = ADTABLIST.map((x: any, i: number) => {
      // console.log('ADFIELDLIST', x.ADFIELDLIST)
      return (
        <TabPane key={i} tab={isZh ? x.LABELZH : x.LABEL}>
          <Row gutter={24}>
            {x.ADFIELDLIST ? x.ADFIELDLIST.filter((field: any) => field.ISDISPLAY && !field.ISBASIC).map(
              (item: any) => <Col span={24 / (x.GRIDY || 1)}><ActiveField
                key={item.OBJECTRRN}
                field={item}
                referRuleInfo={referRuleInfo}
                formDetail={fullFormContent}
                onChange={(val) => {
                  setRefValues({ ...val })
                }} /></Col>) : null}
          </Row>
        </TabPane>
      )
    })
    return (
      <Tabs default-active-key={0}>
        {tabList}
        {/* 自定义添加tab*/}
        {props.renderAddCustomTabs && props.renderAddCustomTabs(fullFormContent)}
      </Tabs>
    )
  }
  return <Form
    onValuesChange={(val: any) => {
      setFullFormContent({ ...fullFormContent, ...val })
    }}
    form={tableMainForm}
    onFinish={(val: any) => {
      console.log(val)
    }}
    labelCol={{ span: 5 }}
    wrapperCol={{ span: 19 }}
    labelAlign="left"
  >
    <Form.Item label="OBJECTRRN" name="OBJECTRRN" hidden>
      <Input />
    </Form.Item>
    {renderBasicInfo()}
    {props.renderCustomTabs ? props.renderCustomTabs(fullFormContent) : ADTABLIST.length > 0 ? renderTabs() : null}
  </Form>
};

export default forwardRef((props, ref) => (<RightContent {...props} ref={ref} />));
// export default RightContent