import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { FourTableType, TypeB3PageSta } from '../type'
import { Button } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import history, { btnFlagFu2 } from '@/utils/history'
import B3goodsTable from '../../B3goodsTable'
import B3flowTable from '../../B3flowTable'
import { B3TiaoObjUrl, B3TitObjKey } from './data'
import B3aTop from './B3aTop'
import { MessageFu } from '@/utils/message'
import {
  FourAPI_audit,
  FourAPI_create,
  FourAPI_del,
  FourAPI_getInfo,
  FourAPI_revocation,
  FourAPI_saveApply,
  FourAPI_saveCreate,
  FourAPI_saveDraft
} from '@/store/action/FourAll'
import { EXbtnFu } from '@/utils/EXBtn'

type Props = {
  pageSta: TypeB3PageSta
}

function B3editMain({ pageSta }: Props) {
  const { key, id, pageKey } = useParams<any>()

  // 顶部数据
  const [topInfo, setTopInfo] = useState({} as FourTableType)

  // 创建订单
  const creatFu = useCallback(async () => {
    const res = await FourAPI_create(pageKey)
    if (res.code === 0) {
      setTopInfo(res.data)
    }
  }, [pageKey])

  // 获取详情
  const getInfoFu = useCallback(async () => {
    const res = await FourAPI_getInfo(pageKey, id)
    if (res.code === 0) {
      setTopInfo(res.data)

      // 设置藏品清单数据

      goodsTableRef.current?.setData(res.data.goods || [])
    }
  }, [id, pageKey])

  useEffect(() => {
    if (key === '1') creatFu()
    else getInfoFu()
    // key 1 2 3 4 新增 编辑 审批 查看
    // pageKey 1 2 3 4 入馆 入藏 登记 删除
  }, [creatFu, getInfoFu, key])

  // key改变的时候，滚动到顶部
  const scrollTopFu = useCallback(() => {
    const dom = document.querySelector('#B3aTop') as HTMLDivElement
    if (dom) dom.scrollTop = 0
  }, [])

  useEffect(() => {
    scrollTopFu()
  }, [key, scrollTopFu])

  // 点击按钮调用子组件的方法获取数据
  const topRef = useRef<any>(null)

  // 藏品清单子组件
  const goodsTableRef = useRef<any>(null)

  // 新增的按钮点击
  const btnClickFu = useCallback(
    async (val: '草稿' | '创建', flag: '当前页' | '编辑页') => {
      // 从顶部组件中拿到数据
      const resData = topRef.current?.resData()
      // console.log('从子组件获取数据', resData)

      const obj = {
        ...resData.formData,
        fileIds: resData.filesRes.join(','),
        rtf: resData.rtf1
      }
      if (!resData.formData.name) return MessageFu.warning('申请名称不能为空')

      if (val === '草稿') {
        // 存草稿 当前页保存 不跳转
        const res = await FourAPI_saveDraft(pageKey, obj)
        if (res.code === 0) {
          MessageFu.success(flag === '当前页' ? '草稿保存成功' : '添加藏品成功')
          if (flag === '编辑页') {
            const url = Reflect.get(B3TiaoObjUrl, pageKey)
            history.push(`${url}_edit/2/${resData.formData.id}/${pageKey}`)
          }
        }
      } else {
        const res = await FourAPI_saveCreate(pageKey, obj)
        if (res.code === 0) {
          MessageFu.success('创建成功')
          const url = Reflect.get(B3TiaoObjUrl, pageKey)
          history.push(`${url}_edit/2/${resData.formData.id}/${pageKey}`)
        }
      }
    },
    [pageKey]
  )

  // 编辑点击提交
  const editBtnOk = useCallback(
    async (obj: any, id: number) => {
      const res = await FourAPI_saveApply(pageKey, obj)

      if (res.code === 0) {
        MessageFu.success('操作成功')
        // 跳详情页
        const url = Reflect.get(B3TiaoObjUrl, pageKey)
        history.push(`${url}_edit/4/${id}/${pageKey}`)
      }
    },
    [pageKey]
  )

  // 点击保存
  const btnOk = useCallback(async () => {
    // 从顶部组件中拿到数据
    const resData = topRef.current?.resData()
    // console.log('从子组件获取数据', resData)

    if (!resData.formData.name) return MessageFu.warning('申请名称不能为空')

    const resData2 = goodsTableRef.current?.resData()

    const obj = {
      ...resData.formData,
      fileIds: resData.filesRes.join(','),
      goodsIds: resData2.tableIds,
      rtf: resData.rtf1
    }
    if (pageSta === '审批') {
      // 审批逻辑
      // console.log('xxxxx', resData)
      const auditObj = resData.audit || {}

      if (!auditObj.auditSta) {
        scrollTopFu()
        return MessageFu.warning('请选择审批结果')
      }

      const res = await FourAPI_audit(pageKey, {
        orderId: resData.formData.id,
        rtfOpinion: auditObj.rtf2,
        status: auditObj.auditSta === '同意' ? 1 : 2
      })

      if (res.code === 0) {
        MessageFu.success('审批成功')
        // editBtnOk(obj, resData.formData.id)
        // 跳详情页
        const url = Reflect.get(B3TiaoObjUrl, pageKey)
        history.push(`${url}_edit/4/${resData.formData.id}/${pageKey}`)
      }

      // 编辑逻辑
    } else editBtnOk(obj, resData.formData.id)
  }, [editBtnOk, pageKey, pageSta, scrollTopFu])

  // 点击取消
  const btnX = useCallback(() => {
    let url = Reflect.get(B3TiaoObjUrl, pageKey)
    history.push(url)
  }, [pageKey])

  // const lookBtnFu = useCallback((val: string) => {
  //   const obj = {
  //     创建: '在当前页，改状态 草稿-待提交',
  //     提交: '在当前页，改状态 待提交-待审批/已完成',
  //     撤回: '在当前页，改状态 待审批/待提交',
  //     审批: '跳审批页',
  //     编辑: '跳编辑页',
  //     重新提交: '当前页,审批不通过-待审批'
  //   }
  // }, [])

  // 查看的按钮创建-提交-撤回
  const lookBtnFu = useCallback(
    async (val: '创建' | '提交' | '撤回') => {
      // 从顶部组件中拿到数据
      const resData = topRef.current?.resData()
      const resData2 = goodsTableRef.current?.resData()
      const obj = {
        ...resData.formData,
        fileIds: resData.filesRes.join(','),
        goodsIds: resData2.tableIds,
        rtf: resData.rtf1
      }

      const res =
        val === '创建'
          ? await FourAPI_saveCreate(pageKey, obj)
          : val === '提交'
          ? await FourAPI_saveApply(pageKey, obj)
          : await FourAPI_revocation(pageKey, id)

      if (res.code === 0) {
        scrollTopFu()
        MessageFu.success(val + '成功')
        getInfoFu()
      }
    },
    [getInfoFu, id, pageKey, scrollTopFu]
  )

  // 查看模式点击删除
  const delFu = useCallback(async () => {
    const res = await FourAPI_del(pageKey, id)
    if (res.code === 0) {
      MessageFu.success('删除成功')
      btnX()
    }
  }, [btnX, id, pageKey])

  // 查看模式点击审批 编辑
  const lookJumpFu = useCallback(
    (val: '审批' | '编辑') => {
      const url = Reflect.get(B3TiaoObjUrl, pageKey)
      history.push(`${url}_edit/${val === '审批' ? 3 : 2}/${id}/${pageKey}`)
      MessageFu.success(`已跳转至${val}页面`)
    },
    [id, pageKey]
  )

  // 查看模式下的按钮
  const lookBtn = useMemo(() => {
    return (
      <>
        {btnFlagFu2(topInfo)['创建'] ? (
          <Button type='primary' onClick={() => lookBtnFu('创建')}>
            创建
          </Button>
        ) : null}
        {btnFlagFu2(topInfo)['提交'] ? (
          <Button type='primary' onClick={() => lookBtnFu('提交')}>
            提交
          </Button>
        ) : null}

        {btnFlagFu2(topInfo)['撤回'] ? (
          <MyPopconfirm
            txtK='撤回'
            onConfirm={() => lookBtnFu('撤回')}
            Dom={
              <Button type='primary' danger>
                撤回
              </Button>
            }
          />
        ) : null}

        {btnFlagFu2(topInfo)['审批'] ? (
          <Button type='primary' onClick={() => lookJumpFu('审批')}>
            审批
          </Button>
        ) : null}
        {btnFlagFu2(topInfo)['编辑'] ? (
          <Button type='primary' onClick={() => lookJumpFu('编辑')}>
            编辑
          </Button>
        ) : null}

        {btnFlagFu2(topInfo)['重新提交'] ? (
          <Button type='primary' onClick={() => lookBtnFu('提交')}>
            重新提交
          </Button>
        ) : null}

        {EXbtnFu(topInfo)}

        {btnFlagFu2(topInfo)['删除'] ? (
          <MyPopconfirm
            txtK='删除'
            onConfirm={() => delFu()}
            Dom={
              <Button type='primary' danger>
                删除
              </Button>
            }
          />
        ) : null}

        <Button onClick={btnX}>返回</Button>
      </>
    )
  }, [btnX, delFu, lookBtnFu, lookJumpFu, topInfo])

  // 申请记录
  const [auditsShow, setAuditsShow] = useState(false)

  return (
    <div className={styles.B3editMain}>
      <div className='pageTitle'>
        藏品{Reflect.get(B3TitObjKey, pageKey)}-{pageSta}
      </div>

      <B3aTop
        info={topInfo}
        pageSta={pageSta}
        ref={topRef}
        Dom={
          <>
            {/* 藏品清单 */}
            {pageSta === '新增' ? null : <B3goodsTable ref={goodsTableRef} pageSta={pageSta} />}

            {/* 申请流程 */}
            {auditsShow ? (
              <B3flowTable tableArr={topInfo.audits || []} closeFu={() => setAuditsShow(false)} />
            ) : null}
          </>
        }
      />

      {/* 底部按钮 */}
      <div className='B3eBtn'>
        {['查看', '审批'].includes(key) && topInfo.audits && topInfo.audits.length ? (
          <Button type='primary' onClick={() => setAuditsShow(true)}>
            申请记录
          </Button>
        ) : null}

        {/* 编辑的时候是保存 审批的时候是提交 */}
        {['编辑', '审批'].includes(pageSta) ? (
          <Button type='primary' onClick={btnOk}>
            {pageSta === '编辑' ? '保存' : '提交'}
          </Button>
        ) : null}

        {pageSta === '新增' ? (
          <>
            <Button type='primary' onClick={() => btnClickFu('草稿', '编辑页')}>
              添加藏品
            </Button>
            <Button type='primary' onClick={() => btnClickFu('创建', '编辑页')}>
              创建
            </Button>
            <Button type='primary' onClick={() => btnClickFu('草稿', '当前页')}>
              存草稿
            </Button>
          </>
        ) : null}

        {pageSta === '查看' ? lookBtn : <MyPopconfirm txtK='取消' onConfirm={() => btnX()} />}
      </div>
    </div>
  )
}

const MemoB3editMain = React.memo(B3editMain)

export default MemoB3editMain
