import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
import {
  C6_APIcreate,
  C6_APIgetInfo,
  C6_APIsaveApply,
  C6_APIsaveDraft
} from '@/store/action/C6edit'
import AddGoods from '../../C1register/AddGoods'
import { GoodFileType } from '@/components/Z3upFiles'
import {
  ArrKeyType,
  Y11infoArr1,
  Y11infoArr2,
  Y11infoArr3,
  Y11infoArr4,
  Y11infoArr5
} from '@/pages/Y_goodsDetails/Y1cathet/data'
import history from '@/utils/history'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'

export type OldNewType = {
  name: string
  qian: string | GoodFileType[]
  hou: string | GoodFileType[]
  key: string
}

const oldNewTxtArr: ArrKeyType = [
  ...Y11infoArr1,
  ...Y11infoArr2,
  ...Y11infoArr3,
  ...Y11infoArr4,
  ...Y11infoArr5,
  {
    name: '封面图',
    key: 'thumb',
    backFu: info => {
      return { thumb: info.thumb, thumbPc: info.thumbPc }
    }
  }
]

type Props = {
  goodsId: number
  sId?: number
  closeFu: () => void
  type: '新增' | '编辑'
  upTableFu?: () => void
}

function C22revamp({ goodsId, closeFu, type, sId, upTableFu }: Props) {
  // 顶部数据
  const [topInfo, setTopInfo] = useState({} as FourTableType)

  // 藏品清单快照数据1对1-把本身的id存起来
  const snapsIdRef = useRef(0)

  // 快照的最新对象信息
  const [snapsNewObj, setSnapsNewObj] = useState({} as C1GoodType)

  // 藏品修改 进来创建订单
  const createFu = useCallback(async () => {
    const res = await C6_APIcreate()
    if (res.code === 0) {
      setTopInfo(res.data)
    }
  }, [])

  // 获取详情
  const getInfoFu = useCallback(async (id: string) => {
    const res = await C6_APIgetInfo(Number(id))
    if (res.code === 0) {
      const data = res.data
      setTopInfo(data)
      if (data.snaps && data.snaps.length) {
        const info = data.snaps[0]
        snapsIdRef.current = info.id
        const newObj = JSON.parse(info.snap)
        setSnapsNewObj(newObj.newObj)
      }
    }
  }, [])

  useEffect(() => {
    if (type === '新增') createFu()
    else getInfoFu(sId! + '')
  }, [createFu, getInfoFu, sId, type])

  return (
    <div className={styles.C22revamp}>
      {topInfo.id ? (
        <AddGoods
          editSnap={snapsNewObj && snapsNewObj.id ? snapsNewObj : undefined}
          closeFu={() => closeFu()}
          nowSta={{ key: '藏品修改', id: goodsId + '' }}
          isEdit={true}
          succFu={async (newObj, _, sta, fileNewTemp, fileOldTemp, objOld) => {
            const arrRes: OldNewType[] = []

            oldNewTxtArr.forEach(v => {
              const oldInfo = objOld!
              let oldTxt: any = oldInfo[v.key]
              let newTxt = newObj[v.key] as string

              if (
                (oldTxt || newTxt) &&
                oldTxt !== newTxt &&
                v.name !== '制档日期' &&
                v.name !== '制档人'
              ) {
                if (v.backFu && v.name !== '备注') oldTxt = v.backFu(oldInfo)
                if (v.backFu && v.name !== '备注') newTxt = v.backFu(newObj)

                arrRes.push({
                  name: v.name,
                  qian: oldTxt,
                  hou: newTxt,
                  key: v.key
                })
              }
            })

            // 附件信息的对比

            const fileOld = fileOldTemp || []
            const fileNew = fileNewTemp || []

            const fileOldIds = fileOld.map(v => v.id).join('')

            const fileNewIds = fileNew.map(v => v.id).join('')

            if (fileOldIds !== fileNewIds) {
              arrRes.push({
                name: '附件信息',
                qian: fileOld.map(
                  v =>
                    ({
                      id: v.id,
                      fileName: v.fileName,
                      filePath: v.filePath
                    } as GoodFileType)
                ),
                hou: fileNew.map(
                  v =>
                    ({
                      id: v.id,
                      fileName: v.fileName,
                      filePath: v.filePath
                    } as GoodFileType)
                ),
                key: 'fileIds'
              })
            }

            const houObj: any = {}
            houObj['id'] = newObj.id

            arrRes.forEach(v => {
              if (v.key === 'fileIds') {
                const fileArr = (v.hou || []) as GoodFileType[]
                houObj['fileIds'] = fileArr.map(c => c.id).join(',')
              } else if (v.key === 'thumb') {
                const thumbObj: any = v.hou
                houObj['thumb'] = thumbObj.thumb
                houObj['thumbPc'] = thumbObj.thumbPc
              } else houObj[v.key] = v.hou
            })

            // console.log(16546, arrRes, sta, houObj)

            const obj2 = {
              ...topInfo,
              goodsIds: newObj.id + '',
              snaps: [
                {
                  goodsId: newObj.id,
                  id: snapsIdRef.current ? snapsIdRef.current : null,
                  orderId: topInfo.id,
                  snap: JSON.stringify({
                    pageShow: arrRes,
                    newObj: { ...newObj, file: fileNewTemp },
                    rear: houObj
                  })
                }
              ]
            }

            // console.log('pppp', JSON.parse(obj2.snaps[0].snap))
            const res = sta === '存草稿' ? await C6_APIsaveDraft(obj2) : await C6_APIsaveApply(obj2)

            if (res.code === 0) {
              if (type === '新增') history.push('/goodEdit')
              else if (upTableFu) upTableFu()
            }

            // setTopInfo({ ...topInfo, tempGoodsJson: newObj })

            // setOldNewArr(arrRes)
          }}
        />
      ) : null}
    </div>
  )
}

const MemoC22revamp = React.memo(C22revamp)

export default MemoC22revamp
