import { forwardRef, memo, useEffect, useImperativeHandle, useState } from 'react'
import { cloneDeep } from 'lodash-es'
import { getTenantApply, ITenantApplyInfo } from '@/api/services/riskcontrol/declare'
import { orderStateMap } from './constants/orderState'
import DynamicForm from './components/DynamicForm'

export interface FormParseRef {}

interface FormParseProps {
  declFormData: Nullable<API.OpenDeclFormResult>
  formData: Record<string, any>
  formRule?: any
  disabled?: boolean
  state?: string
  expiry?: string
  isExpiry?: boolean
  className?: string
  onFormDataChange: (data: Record<string, any>) => void
  onFormRuleChange: (rule: any) => void
}

const checkStateMap = {
  PASSED: '通过',
  REJECTED: '拒绝',
  TO_RECT: '整改'
}

const FormParse = memo(
  forwardRef<FormParseRef, FormParseProps>(
    (
      {
        declFormData,
        formData,
        formRule,
        disabled,
        state,
        expiry,
        isExpiry,
        onFormDataChange,
        onFormRuleChange
      },
      ref
    ) => {
      console.log(formData)
      console.log(formRule)
      console.log(disabled)
      // 对外暴露方法
      useImperativeHandle(ref, () => {
        return {}
      })

      const formItemsCopy = cloneDeep(declFormData?.formItems)
      console.log(formItemsCopy)

      const [showViewPayInfoDialog, setShowViewPayInfoDialog] = useState(false)
      console.log(showViewPayInfoDialog)
      const [payInfo, setPayInfo] = useState<Partial<API.PayDetail>>({
        reqSn: '',
        amount: '',
        orderState: '',
        paymentTime: '',
        issueTime: '',
        expireTime: '',
        payType: ''
      })
      console.log(payInfo)
      const viewPayInfoDialog = () => {
        setPayInfo(declFormData!.payDetail)
        setShowViewPayInfoDialog(true)
      }

      const [tennantInfo, setTennantInfo] = useState<Partial<ITenantApplyInfo>>()
      console.log(tennantInfo)
      const [showAccountDialog, setShowAccountDialog] = useState(false)
      console.log(showAccountDialog)
      const viewAccountInfoDialog = async () => {
        const res = await getTenantApply({
          declId: declFormData!.declarationId,
          regCode: declFormData!.regCode
        })
        if (res?.code === '2000') {
          setTennantInfo(res.data)
          setShowAccountDialog(true)
        }
      }

      const [isInited, setIsInited] = useState(false)
      const initFn = () => {
        console.log('init')
        // 初始化表单
        formItemsCopy?.forEach((item) => {
          // 初始化数据
          if (item.itemStruct?.type === 'FILE_PICKER') {
            onFormDataChange((prev: Record<string, any>) => ({
              ...prev,
              [item.itemStruct!.widgetId!]: item.itemDeli?.length
                ? item.itemDeli.map((deli) => ({
                    fileName: deli.value.fileName, // 用来回显
                    original: deli.value.fileName, // 文件原始名称, 后续保存提交此参数
                    name: deli.value.fileName, // 用来回显
                    url: deli.value.ossLink, // 用来回显
                    viewUrl: deli.value.ossLink, // 用来图片放大器回显
                    originUrl: deli.value.url, // 用来保存原始url, 后续保存提交此参数
                    state: 'old' // 旧数据
                  }))
                : []
            }))
          } else if (item.itemStruct?.type === 'INVOICE_PICKER') {
            onFormDataChange((prev: Record<string, any>) => ({
              ...prev,
              [item.itemStruct!.widgetId!]: item.itemDeli?.length
                ? item.itemDeli.map((deli) => ({
                    fileName: deli.value.fileName, // 用来回显
                    original: deli.value.fileName, // 文件原始名称, 后续保存提交此参数
                    name: deli.value.fileName, // 用来回显
                    url: deli.value.ossLink, // 用来回显
                    viewUrl: deli.value.ossLink, // 用来图片放大器回显
                    originUrl: deli.value.url, // 用来保存原始url, 后续保存提交此参数
                    state: 'old' // 旧数据
                  }))
                : []
            }))
          } else if (item.itemStruct?.type === 'FINANCE_PICKER') {
            onFormDataChange((prev: Record<string, any>) => ({
              ...prev,
              [item.itemStruct!.widgetId!]: item.itemDeli?.length
                ? item.itemDeli.map((deli) => ({
                    fileName: deli.value.fileName, // 用来回显
                    original: deli.value.fileName, // 文件原始名称, 后续保存提交此参数
                    name: deli.value.fileName, // 用来回显
                    url: deli.value.ossLink, // 用来回显
                    viewUrl: deli.value.ossLink, // 用来图片放大器回显
                    originUrl: deli.value.url, // 用来保存原始url, 后续保存提交此参数
                    state: 'old' // 旧数据
                  }))
                : []
            }))
          } else if (item.itemStruct?.type === 'INPUT') {
            onFormDataChange((prev: Record<string, any>) => ({
              ...prev,
              [item.itemStruct!.widgetId!]: item.itemDeli?.length ? item.itemDeli[0].value : ''
            }))
          } else if (item.itemStruct?.type === 'NUMBER_INPUT') {
            onFormDataChange((prev: Record<string, any>) => ({
              ...prev,
              [item.itemStruct!.widgetId!]: item.itemDeli?.length ? item.itemDeli[0].value : ''
            }))
          } else if (item.itemStruct?.type === 'AMOUNT_INPUT') {
            onFormDataChange((prev: Record<string, any>) => ({
              ...prev,
              [item.itemStruct!.widgetId!]: item.itemDeli?.length ? item.itemDeli[0].value : ''
            }))
          } else if (item.itemStruct?.type === 'RADIO') {
            onFormDataChange((prev: Record<string, any>) => ({
              ...prev,
              [item.itemStruct!.widgetId!]: item.itemDeli?.length ? item.itemDeli[0].value : ''
            }))
          } else if (item.itemStruct?.type === 'SELECT') {
            onFormDataChange((prev: Record<string, any>) => ({
              ...prev,
              [item.itemStruct!.widgetId!]: item.itemDeli?.length
                ? item.itemDeli[0].value
                : (item.itemStruct?.expand as API.FD_COM['SELECT']).multiple
                  ? []
                  : ''
            }))
          } else if (item.itemStruct?.type === 'DATETIME_PICKER') {
            const isRangeType = ['DATERANGE', 'DATETIMERANGE'].includes(
              (item.itemStruct.expand as API.FD_COM['DATETIME_PICKER']).dateType
            )
            onFormDataChange((prev: Record<string, any>) => ({
              ...prev,
              [item.itemStruct!.widgetId!]: item.itemDeli?.length
                ? item.itemDeli[0].value
                : isRangeType
                  ? []
                  : ''
            }))
          }
          // 初始化rules
          if (formRule) {
            const rules: any[] = []
            if (item.itemStruct!.required) {
              const tipMap = {
                INPUT: '请输入',
                FILE_PICKER: '请上传',
                INVOICE_PICKER: '请上传',
                NUMBER_INPUT: '请输入数值',
                AMOUNT_INPUT: '请输入金额',
                FINANCIAL_PICKER: '请上传',
                DATETIME_PICKER: '请选择',
                SELECT: '请选择'
              }

              const tipText = tipMap[item.itemStruct?.type as keyof typeof tipMap] ?? '请输入'
              rules.push({
                required: true,
                message:
                  item.itemStruct?.type === 'SELECT' &&
                  (item.itemStruct.expand as API.FD_COM['SELECT']).multiple
                    ? '请至少选择一个选项'
                    : `${tipText}${item.itemStruct?.label.text}`,
                trigger: 'blur'
              })
              // requireLimit
              if ((item.itemStruct!.expand as API.FD_COM['FILE_PICKER'])?.requiredLimit) {
                rules.push({
                  validator: (_rule: any, value: any, callback: any) => {
                    if (
                      value.length <
                      (item.itemStruct!.expand as API.FD_COM['FILE_PICKER'])!.requiredLimit!
                    ) {
                      callback(
                        new Error(
                          `至少上传${(item.itemStruct!.expand as API.FD_COM['FILE_PICKER'])!
                            .requiredLimit!}个文件`
                        )
                      )
                    } else {
                      callback()
                    }
                  },
                  trigger: 'blur'
                })
              }
              if (
                (item.itemStruct!.expand as API.FD_COM_ENHANCE['INVOICE_PICKER'])?.requiredLimit
              ) {
                rules.push({
                  validator: (_rule: any, value: any, callback: any) => {
                    if (
                      value.length <
                      (item.itemStruct!.expand as API.FD_COM_ENHANCE['INVOICE_PICKER'])!
                        .requiredLimit!
                    ) {
                      callback(
                        new Error(
                          `至少上传${(item.itemStruct!
                            .expand as API.FD_COM_ENHANCE['INVOICE_PICKER'])!.requiredLimit!}个文件`
                        )
                      )
                    } else {
                      callback()
                    }
                  },
                  trigger: 'blur'
                })
              }
              if (
                (item.itemStruct!.expand as API.FD_COM_ENHANCE['FINANCE_PICKER'])?.requiredLimit
              ) {
                rules.push({
                  validator: (_rule: any, value: any, callback: any) => {
                    if (
                      value.length <
                      (item.itemStruct!.expand as API.FD_COM_ENHANCE['FINANCE_PICKER'])!
                        .requiredLimit!
                    ) {
                      callback(
                        new Error(
                          `至少上传${(item.itemStruct!
                            .expand as API.FD_COM_ENHANCE['FINANCE_PICKER'])!.requiredLimit!}个文件`
                        )
                      )
                    } else {
                      callback()
                    }
                  },
                  trigger: 'blur'
                })
              }
            }

            if ((item.itemStruct!.expand as API.FD_COM['INPUT'])?.maxChars) {
              rules.push({
                max: parseInt((item.itemStruct!.expand as API.FD_COM['INPUT'])?.maxChars),
                message: `最多输入${(item.itemStruct!.expand as API.FD_COM['INPUT'])?.maxChars}个字符`,
                trigger: 'blur'
              })
            }
            if ((item.itemStruct!.expand as API.FD_COM['NUMBER_INPUT'])?.maxChars) {
              rules.push({
                max: parseInt((item.itemStruct!.expand as API.FD_COM['NUMBER_INPUT'])?.maxChars),
                message: `最多输入${
                  (item.itemStruct!.expand as API.FD_COM['NUMBER_INPUT'])?.maxChars
                }个字符`,
                trigger: 'blur'
              })
            }
            if ((item.itemStruct!.expand as API.FD_COM['AMOUNT_INPUT'])?.maxChars) {
              rules.push({
                max: parseInt((item.itemStruct!.expand as API.FD_COM['AMOUNT_INPUT'])?.maxChars),
                message: `最多输入${
                  (item.itemStruct!.expand as API.FD_COM['AMOUNT_INPUT'])?.maxChars
                }个字符`,
                trigger: 'blur'
              })
            }
            // 这里可以根据需要添加其他规则
            item.itemStruct!.valid?.forEach((validItem) => {
              rules.push({
                validator: (_rule: any, value: any, callback: any) => {
                  const reg = new RegExp(validItem.expression.body, validItem.expression.modifier)
                  if (!reg.test(value)) {
                    callback(new Error(validItem.message))
                  } else {
                    callback()
                  }
                },
                trigger: 'blur'
              })
            })
            if (Array.isArray(formRule![item.itemStruct!.widgetId!]) && disabled) {
              onFormRuleChange((prev: any) => ({
                ...prev,
                [item.itemStruct!.widgetId!]: [
                  ...((formRule![item.itemStruct!.widgetId!] as []) || [])
                ]
              }))
            } else {
              onFormRuleChange((prev: any) => ({
                ...prev,
                [item.itemStruct!.widgetId!]: rules as any
              }))
            }
          }
        })
        setIsInited(true)
      }
      useEffect(() => {
        initFn()
      }, [])

      return (
        <div>
          {state && (
            <div className='text-[14px] pl-[12px] mb-[8px] text-text-secondary f-b-c'>
              <div>
                <span>
                  {typeof isExpiry === 'boolean'
                    ? isExpiry
                      ? '已结束'
                      : `有效期至：${expiry}`
                    : ''}
                </span>
                <span className='ml-[20px]'>填报状态：{state}</span>
                {declFormData?.declarationState === 'ROLLBACK' && (
                  <span className='ml-[20px]'>退回原因：{declFormData?.rollbackRemark}</span>
                )}
              </div>
              <div className='flex'>
                {declFormData?.payDetail?.bizPayType === 'HYBRID_PAID' && (
                  <div>
                    <span>
                      准入管理费支付状态：
                      {
                        orderStateMap[
                          declFormData?.payDetail?.orderState as keyof typeof orderStateMap
                        ]
                      }
                    </span>
                    <span
                      className='text-primary ml-[6px] cursor-pointer'
                      onClick={viewPayInfoDialog}>
                      详情
                    </span>
                  </div>
                )}
                {declFormData?.isTenantApplied && (
                  <div className='ml-[16px]'>
                    <span>登录账号：</span>
                    <span
                      className='text-primary ml-[6px] cursor-pointer'
                      onClick={viewAccountInfoDialog}>
                      查看
                    </span>
                  </div>
                )}
              </div>
            </div>
          )}
          <div className='mb-[12px] text-[14px] text-text-secondary bg-[#F6FAFF] rounded-[4px] px-[12px] py-[8px]'>
            <span>
              企业审核结果：
              {declFormData?.checkState
                ? checkStateMap[declFormData.checkState as keyof typeof checkStateMap]
                : '-'}
            </span>
            <span className='ml-20'>审核意见：{declFormData?.checkMsg || '-'}</span>
            <span className='ml-20 break-all'>原因说明：{declFormData?.remarks || '-'}</span>
          </div>
          {/* 动态生成表单 */}
          {isInited && <DynamicForm formItems={formItemsCopy} />}
        </div>
      )
    }
  )
)

export default FormParse
