import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { FourTableType } from '../../B1collect/type'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import classNames from 'classnames'
import { Button, DatePicker, Input } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import {
  FourAPI_audit,
  FourAPI_create,
  FourAPI_del,
  FourAPI_getInfo,
  FourAPI_revocation,
  FourAPI_saveApply,
  FourAPI_saveCreate,
  FourAPI_saveDraft
} from '@/store/action/FourAll'
import { MessageFu } from '@/utils/message'
import history, { btnFlagFu2, infoPageBackFu, openGoodsInfoFu } from '@/utils/history'
import { EXbtnFu } from '@/utils/EXBtn'
import { pageTitTxtObj } from '@/pages/D_storeManage/D4impStor/D4edit'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import { B34TableC2, statusObj } from '@/utils/tableData'
import dayjs from 'dayjs'
import MyTable from '@/components/MyTable'
import ZflowTable from '@/components/ZflowTable'
import ZupFileTable from '@/components/ZupFileTable'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'
import ZGaddNow from '@/components/ZGaddNow'
import B34MoAdd from '../B34MoAdd'
import { EXPORT_WORD_ENUM } from '@/utils/exportTemplates'

type Props = {
  type: '入馆' | '入藏'
}

function B34edit({ type }: Props) {
  const { key, id } = useParams<any>()
  // key:1 新增 2编辑 3审批 4查看

  // 滚到顶部
  const sollrDom = useRef<HTMLDivElement>(null)

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

  // 藏品清单快照数据
  const [snaps, setSnaps] = useState<C1GoodType[]>([])
  const delSnapIdsRef = useRef<number[]>([])

  const snapsID2ref = useRef<{ goodsId: number; id: number }[]>([])

  // -------新增藏品-新字段-------------
  const [openInfo, setOpenInfo] = useState({} as C1GoodType)

  // 打开侧边栏
  const [cathet, setCathet] = useState(0)

  const startBtn = useMemo(() => {
    return [
      {
        title: '藏品编号',
        render: (item: C1GoodType) => {
          return (
            <span
              onClick={() => setCathet(item.id)}
              className={classNames('D1GtNum', item.id === cathet ? 'D1GtNumAc' : '')}
            >
              {item.num || '（空）'}
            </span>
          )
        }
      }
    ]
  }, [cathet])

  const tableLastBtn = useMemo(() => {
    let arr: any = []

    arr.push({
      title: '关联藏品登记',
      render: (item: C1GoodType) => {
        return item.subNum && item.relatedOrderId ? (
          <span
            onClick={() => openGoodsInfoFu(item.relatedOrderId, 999, '#/register_edit/4/')}
            className='D1GtNum'
          >
            {item.subNum}
          </span>
        ) : (
          '（空）'
        )
      }
    })

    arr.push({
      title: '操作',
      render: (item: any) => {
        return (
          <>
            <Button size='small' type='text' onClick={() => setOpenInfo(item)}>
              {['3', '4'].includes(key) ? '查看' : '编辑'}
            </Button>
            {['3', '4'].includes(key) ? null : (
              <MyPopconfirm
                txtK='删除'
                onConfirm={() => {
                  if (item.id2 && !delSnapIdsRef.current.includes(item.id2))
                    delSnapIdsRef.current.push(item.id2)
                  setSnaps(snaps.filter(v => v.id !== item.id))
                }}
              />
            )}
          </>
        )
      }
    })

    return arr
  }, [key, snaps])
  // -------新增藏品-新字段-------------

  // 创建订单
  const creatFu = useCallback(async () => {
    const res = await FourAPI_create(type === '入馆' ? '1' : '2')
    if (res.code === 0) {
      setTopInfo(res.data)
    }
  }, [type])

  // 获取详情
  const getInfoFu = useCallback(
    async (id2?: number) => {
      const res = await FourAPI_getInfo(type === '入馆' ? '1' : '2', id2 || id)
      if (res.code === 0) {
        const data = res.data
        setTopInfo(data)
        // 藏品清单快照信息id对比
        const arrTemp: any = []
        const snapsTemp = data.snaps || []

        snapsTemp.forEach((v: any) => {
          snapsID2ref.current.push({ goodsId: v.goodsId, id: v.id })

          const obj = JSON.parse(v.snap || '{}')
          if (obj.id) obj.id2 = v.id

          arrTemp.push({
            ...obj,
            subNum: v.subNum ? v.subNum : '',
            relatedOrderId: v.relatedOrderId ? v.relatedOrderId : ''
          })
        })

        setSnaps(arrTemp)
      }
    },
    [id, type]
  )

  useEffect(() => {
    if (key === '1') creatFu()
    else getInfoFu()

    if (sollrDom.current) sollrDom.current.scrollTop = 0
  }, [creatFu, getInfoFu, key])

  // 审批意见的ref
  const ZAuditRef = useRef<any>(null)

  // 审批的sta
  const [auditSta, setAuDitSta] = useState('')

  const timeChange = useCallback(
    (e: any) => {
      setTopInfo({ ...topInfo, date: dayjs(e).format('YYYY-MM-DD') })
    },
    [topInfo]
  )

  // 新增的底部按钮点击
  const btnClickFu = useCallback(
    async (val: '草稿' | '创建' | '保存' | '审批') => {
      if (!topInfo.num) return MessageFu.warning('请输入入馆凭证号')

      if (val !== '草稿') {
        if (snaps.length === 0) return MessageFu.warning('请添加藏品')
      }

      if (val === '审批') {
        // console.log('审批信息富文本', rtf2)
        if (!auditSta) {
          if (sollrDom.current) sollrDom.current.scrollTop = 0
          return MessageFu.warning('请选择审批结果')
        }
        const rtf2 = ZAuditRef.current?.resData()

        const res = await FourAPI_audit(type === '入馆' ? '1' : '2', {
          orderId: topInfo.id,
          rtfOpinion: rtf2,
          status: auditSta === '同意' ? 1 : 2
        })

        if (res.code === 0) {
          MessageFu.success('审批成功')
          // 跳详情页
          history.push(`/${type === '入馆' ? 'entering' : 'enterTibet'}_edit/4/${topInfo.id}`)
        }
      } else {
        const obj = {
          ...topInfo,
          goodsIds: snaps.map(v => v.id).join(','),
          delSnapIds: delSnapIdsRef.current.length ? delSnapIdsRef.current : '',
          snaps: snaps.map(v => ({
            goodsId: v.id,
            id: v.id2 ? v.id2 : null,
            orderId: topInfo.id,
            tempStatus: type === '入馆' ? null : v.statusCollect || null,
            snap: JSON.stringify(v)
          }))
        }
        // console.log(123, obj.snaps)

        // if (1 + 1 === 2) return

        if (val === '草稿') {
          // 存草稿 当前页保存 不跳转
          const res = await FourAPI_saveDraft(type === '入馆' ? '1' : '2', obj)
          if (res.code === 0) {
            MessageFu.success('草稿保存成功')
            getInfoFu(topInfo.id)
          }
        } else {
          const res =
            val === '创建'
              ? await FourAPI_saveCreate(type === '入馆' ? '1' : '2', obj)
              : await FourAPI_saveApply(type === '入馆' ? '1' : '2', obj)
          if (res.code === 0) {
            MessageFu.success(`${val}成功`)
            // 跳到详情页
            history.push(`/${type === '入馆' ? 'entering' : 'enterTibet'}_edit/4/${topInfo.id}`)
          }
        }
      }
    },
    [auditSta, getInfoFu, snaps, topInfo, type]
  )
  // 查看的按钮创建-提交-撤回
  const lookBtnFu = useCallback(
    async (val: '创建' | '提交' | '撤回') => {
      if (!topInfo.num) return MessageFu.warning('请输入入馆凭证号')

      if (val !== '撤回') {
        if (snaps.length === 0) {
          if (val === '创建')
            history.push(`/${type === '入馆' ? 'entering' : 'enterTibet'}_edit/2/${id}`)
          return MessageFu.warning('请添加藏品')
        }
      }

      const obj = {
        ...topInfo,
        goodsIds: snaps.map(v => v.id).join(','),
        delSnapIds: delSnapIdsRef.current.length ? delSnapIdsRef.current : '',
        snaps: snaps.map(v => ({
          goodsId: v.id,
          id: v.id2 ? v.id2 : null,
          orderId: topInfo.id,
          tempStatus: type === '入馆' ? null : v.statusCollect || null,
          snap: JSON.stringify(v)
        }))
      }

      // console.log(123, obj.snaps)

      // if (1 + 1 === 2) return

      const res =
        val === '创建'
          ? await FourAPI_saveCreate(type === '入馆' ? '1' : '2', obj)
          : val === '提交'
          ? await FourAPI_saveApply(type === '入馆' ? '1' : '2', obj)
          : await FourAPI_revocation(type === '入馆' ? '1' : '2', id)

      if (res.code === 0) {
        if (sollrDom.current) sollrDom.current.scrollTop = 0
        MessageFu.success(val + '成功')
        getInfoFu()
      }
    },
    [topInfo, snaps, type, id, getInfoFu]
  )
  // 查看模式点击删除
  const delFu = useCallback(async () => {
    const res = await FourAPI_del(type === '入馆' ? '1' : '2', id)
    if (res.code === 0) {
      MessageFu.success('删除成功')
      history.push(`/${type === '入馆' ? 'entering' : 'enterTibet'}`)
    }
  }, [id, type])

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

  // 查看模式下的按钮
  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, [
          type === '入馆' ? EXPORT_WORD_ENUM.VOUCHER : EXPORT_WORD_ENUM.STORAGE_VOUCHER
        ])}

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

        <Button onClick={() => infoPageBackFu(`/${type === '入馆' ? 'entering' : 'enterTibet'}`)}>
          返回
        </Button>
      </>
    )
  }, [delFu, lookBtnFu, lookJumpFu, topInfo, type])

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

  // 点击从入馆的藏品中添加
  const [nowSta, setNowSta] = useState({ key: '', id: '' })

  return (
    <div className={styles.B34edit}>
      <div className='pageTitle'>
        藏品{type}-{Reflect.get(pageTitTxtObj, key)}
      </div>

      <div className='B34main' ref={sollrDom}>
        {['3'].includes(key) ? (
          <X3auditInfo
            dirCode='B34typeIn'
            myUrl='cms/goodsFile/upload'
            auditSta={auditSta}
            auditStaFu={val => setAuDitSta(val)}
            ref={ZAuditRef}
          />
        ) : null}

        {/* 表单字段、附件等 */}
        <div className='B34Tit'>
          申请信息
          {key === '1' ? null : (
            <Button type='dashed'>{Reflect.get(statusObj, topInfo.status)}</Button>
          )}
        </div>

        {topInfo.id ? (
          <div className='B34rowAll'>
            <div className='B34row'>
              <div className='B34rowll'>
                <span> * </span>
                {type}凭证号：
              </div>
              <div className='B34rowrr'>
                <Input
                  value={topInfo.num}
                  onChange={e => setTopInfo({ ...topInfo, num: e.target.value.trim() })}
                  readOnly={['3', '4'].includes(key)}
                  placeholder='请输入内容'
                  maxLength={30}
                  showCount
                />
              </div>
            </div>

            <div className='B34row'>
              <div className='B34rowll'>业务名称：</div>
              <div className='B34rowrr'>{topInfo.name}</div>
            </div>

            <div className='B34row'>
              <div className='B34rowll'>发起人：</div>
              <div className='B34rowrr'>
                {topInfo.creatorName || ''} - {topInfo.createTime || ''}
              </div>
            </div>

            <div className='B34row'>
              <div className='B34rowll'>发起部门：</div>
              <div className='B34rowrr'>{topInfo.deptName}</div>
            </div>
            <div className='B34row'>
              <div className='B34rowll'>
                <span> * </span>
                {type}日期：
              </div>
              <div className='B34rowrr'>
                <DatePicker
                  disabled={['3', '4'].includes(key)}
                  allowClear={false}
                  value={dayjs(topInfo.date)}
                  onChange={timeChange}
                />
              </div>
            </div>
          </div>
        ) : null}

        {/* 藏品清单 */}
        <div className='B34goodsBox'>
          <div className='B34Tit2'>
            <div className='B34Tit2ll'>藏品清单</div>
            <div className='B34Tit2rr'>
              {['3', '4'].includes(key) ? null : (
                <>
                  {type === '入馆' ? null : (
                    <Button
                      type='primary'
                      onClick={() =>
                        setNowSta({
                          key: '入藏',
                          id: `cms/orderHide/goods/getList`
                        })
                      }
                    >
                      从已入馆的藏品中添加
                    </Button>
                  )}

                  <Button type='primary' onClick={() => setOpenInfo({ id: -1 } as C1GoodType)}>
                    新增
                  </Button>
                </>
              )}
            </div>
          </div>

          {/* 表格 */}
          <MyTable
            list={snaps}
            columnsTemp={B34TableC2}
            startBtn={startBtn}
            lastBtn={tableLastBtn}
            pagingInfo={false}
          />
        </div>

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

        {/* 附件归档 */}
        {topInfo.status === 4 ? (
          <ZupFileTable
            listTemp={topInfo.filing || []}
            dirCode='B34typeIn'
            myUrl={`cms/${type === '入馆' ? 'orderHouse' : 'orderHide'}/upload`}
            fromData={{ moduleId: topInfo.id }}
          />
        ) : null}
      </div>
      {/* 底部按钮 */}
      <div className='B34btn'>
        {['3', '4'].includes(key) &&
        topInfo.audits &&
        topInfo.audits.length &&
        [2, 3, 4].includes(topInfo.status) ? (
          <Button type='primary' onClick={() => setAuditsShow(true)}>
            申请记录
          </Button>
        ) : null}

        {key === '4' ? (
          lookBtn
        ) : (
          <>
            {key === '3' ? (
              <Button type='primary' onClick={() => btnClickFu('审批')}>
                审批
              </Button>
            ) : (
              <Button type='primary' onClick={() => btnClickFu(key === '1' ? '创建' : '保存')}>
                {key === '1' ? '创建' : '保存'}
              </Button>
            )}

            {key === '1' ? (
              <Button type='primary' onClick={() => btnClickFu('草稿')}>
                存草稿
              </Button>
            ) : null}

            <MyPopconfirm
              txtK='取消'
              onConfirm={() => history.push(`/${type === '入馆' ? 'entering' : 'enterTibet'}`)}
            />
          </>
        )}
      </div>

      {/* 打开侧边栏 */}
      <Y1cathet sId={cathet} closeFu={() => setCathet(0)} />

      {/* 选中藏品弹窗 */}
      {nowSta.id ? (
        <ZGaddNow
          menuId={9999}
          nowSta={nowSta}
          closeFu={() => setNowSta({ key: '入藏', id: '' })}
          dataResFu={data => {
            //需要过滤掉已经有id的-不替换数据，没有id的替换数据 因为数据可能已经在另外一个弹窗更新了
            const nowIds = snaps.map(v => v.id)
            let dataRes = data.map((v, i) => {
              if (nowIds.includes(v.id)) return snaps[i]
              else return v
            })

            dataRes.forEach(v => {
              // id2表示的是自己这条数据的id id才是goodsId
              const obj = snapsID2ref.current.find(c => c.goodsId === v.id)

              if (obj) v.id2 = obj.id
            })

            setSnaps(dataRes)
          }}
          oldCheckArr={snaps}
        />
      ) : null}

      {openInfo.id ? (
        <B34MoAdd
          info={openInfo}
          closeFu={() => setOpenInfo({} as C1GoodType)}
          type={type}
          succFu={(obj, newFlag) => {
            if (newFlag) {
              // 是新增
              // console.log(5454, [obj, ...snaps])

              setSnaps([obj, ...snaps])
            } else {
              setSnaps(
                snaps.map(v => {
                  if (v.id === obj.id) return obj
                  else return v
                })
              )
            }
          }}
          look={['3', '4'].includes(key)}
        />
      ) : null}
    </div>
  )
}

const MemoB34edit = React.memo(B34edit)

export default MemoB34edit
