import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { useInfo } from '@/pages/Zother/InfoContext'
import ImageLazy from '@/components/ImageLazy'
import { Button } from 'antd'
import { openLink } from '@/utils/history'
import { useParams } from 'react-router-dom'
import { GIrowArr } from '@/pages/ZgoodsInfo/data'
import { API_getFileListByIds } from '@/store/action/Cledger/C4file'
import MyTable from '@/components/MyTable'
import { baseURL } from '@/utils/http'
import { GoodsType } from '@/pages/Zother/SonGoodsList/data'
import { resTagFu } from '@/utils/dataChange'
import AddGoods from '@/pages/Zother/AddGoods'
import { MessageFu } from '@/utils/message'
import { arrFiltersFu } from '@/utils'

function D2info() {
  const { snaps, editObj, setEditObjFu } = useInfo()
  const { key } = useParams<any>()
  // key:1 新增 2编辑 3审批 4查看
  const isLook = useMemo(() => {
    return ['3', '4'].includes(key)
  }, [key])

  const [tableList, setTableList] = useState<any[]>([])

  const getList = useCallback(async (changeObj: any) => {
    // console.log('-------', changeObj)

    let resArr: any[] = []
    if (changeObj.keyArr) {
      const arr = [
        ...GIrowArr,
        { key: 'name', name: '藏品名称' },
        {
          key: 'tagDictId',
          name: '藏品标签',
          resFu: (info: GoodsType) => {
            let resTxt = info.tagDictId
            if (resTxt) return resTagFu(resTxt, '藏品') || '（空）'
            return resTxt || '（空）'
          }
        }
      ]

      const oldInfo: any = changeObj.old
      const newInfo: any = changeObj.new
      const keyArr = changeObj.keyArr
      arr.forEach(v1 => {
        keyArr.forEach((v2: any) => {
          const type = typeof v1.key
          let flag = false
          flag = type === 'string' ? v1.key === v2 : v1.key.includes(v2)

          if (flag) {
            resArr.push({
              id: v2,
              label: v1.name,
              old: v1.resFu ? v1.resFu(oldInfo) : oldInfo[v2],
              new: v1.resFu ? v1.resFu(newInfo) : newInfo[v2]
            })
          }
        })
      })

      if (keyArr.includes('thumb')) {
        resArr.push({
          id: 'thumb',
          label: '封面图',
          old: { thumb: oldInfo.thumb, thumbPc: oldInfo.thumbPc },
          new: { thumb: newInfo.thumb, thumbPc: newInfo.thumbPc }
        })
      }

      if (keyArr.includes('fileIds')) {
        // 有藏品附件
        let ids: any = new Set([...oldInfo['fileIds'].split(','), ...newInfo['fileIds'].split(',')])

        const res = await API_getFileListByIds([...ids].filter(v => v))
        if (res.code === 0) {
          const fileList: any[] = res.data || []

          resArr.push({
            id: 'fileIds',
            label: '附件',
            old: fileList.filter(v => oldInfo['fileIds'].includes(v.id + '')),
            new: fileList.filter(v => newInfo['fileIds'].includes(v.id + ''))
          })
          setTableList(arrFiltersFu(resArr, 'label'))
        }
      } else setTableList(arrFiltersFu(resArr, 'label'))
    }
  }, [])

  useEffect(() => {
    getList(editObj)
  }, [editObj, getList])

  const tableLastBtn2Fu = useCallback((item: any, key: 'new' | 'old') => {
    if (item.label === '附件') {
      let arr = item[key] as any[]

      return arr.length
        ? arr.map((v: any) => (
            <a
              id='tableTxtAc2'
              key={v.id}
              href={baseURL + v.filePath}
              download
              target='_blank'
              rel='noreferrer'
            >
              {v.fileName}
            </a>
          ))
        : '-'
    } else if (item.label === '封面图') {
      const info: any = item[key]

      return (
        <div className='tableImgAuto'>
          <ImageLazy
            width={60}
            height={60}
            srcBig={info.thumbPc || info.thumb}
            src={info.thumb || info.thumbPc}
          />
        </div>
      )
    } else return item[key] || '（空）'
  }, [])

  const tableLastBtn = useMemo(() => {
    return [
      {
        width: 300,
        title: '编辑项',
        render: (item: any) =>
          ['封面图', '附件'].includes(item.label) ? (
            <span className='tableTxtAc'>{item.label}</span>
          ) : (
            item.label
          )
      },
      {
        title: '编辑前',
        render: (item: any) => tableLastBtn2Fu(item, 'old')
      },
      {
        title: '编辑后',
        render: (item: any) => tableLastBtn2Fu(item, 'new')
      }
    ]
  }, [tableLastBtn2Fu])

  // 点击重新编辑
  const [goodInfo, setGoodInfo] = useState({} as GoodsType)

  return (
    <div className={styles.D2info}>
      <div className='EdTit'>
        <div>修改详情</div>
      </div>
      <div className='Edtop1'>
        <div className='Edtop1row Edtop1rowFull'>
          <div className='Edtop1ll'>
            <span>* </span>
            关联藏品：
          </div>
          {snaps.length > 0 ? (
            <div className='Edtop1rr2'>
              <ImageLazy
                width={60}
                height={58}
                src={snaps[0].thumb || snaps[0].thumbPc}
                srcBig={snaps[0].thumbPc || snaps[0].thumb}
              />
              <div className='Edtop1rr2Txt' title={snaps[0].num + ' - ' + snaps[0].name}>
                {snaps[0].num + ' - ' + snaps[0].name}
              </div>
              <div>
                <Button
                  type='text'
                  size='small'
                  onClick={() => openLink(`/goodsLook/${snaps[0].id}`)}
                >
                  查看
                </Button>
                {isLook ? null : (
                  <Button type='text' size='small' onClick={() => setGoodInfo(editObj.new)}>
                    重新编辑
                  </Button>
                )}
              </div>
            </div>
          ) : isLook ? (
            '（空）'
          ) : null}
        </div>
      </div>

      <MyTable list={tableList} columnsTemp={[]} lastBtn={tableLastBtn} pagingInfo={false} />

      {/* 藏品编辑弹窗 */}
      {goodInfo.id ? (
        <AddGoods
          info={goodInfo}
          editSnap={goodInfo}
          closeFu={() => setGoodInfo({} as GoodsType)}
          isEdit={true}
          succFu={async (val, newObj, oldObj, keyArr) => {
            const newCanObj = { new: newObj, old: oldObj, keyArr }
            getList(newCanObj)
            setEditObjFu(newCanObj)
            MessageFu.success('重新编辑成功')
            setGoodInfo({} as GoodsType)
          }}
          moduleId={0}
          fileUpInfo={{ myUrl: 'cms/order/edit/son/upload', dirCode: 'goodEditSon' }}
          APIsave={null}
        />
      ) : null}
    </div>
  )
}

const MemoD2info = React.memo(D2info)

export default MemoD2info
