import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { B1listType } from '@/pages/B1ledger/data'
import { B3_APIaduit, B3_APIgetInfo } from '@/store/action/B3edit'
import { API_getFileListByIds } from '@/store/action/B1ledger'
import { MessageFu } from '@/utils/message'
import history, { backPageFu } from '@/utils/history'
import { Button } from 'antd'
import { statusSelect } from '@/utils/select'
import TextArea from 'antd/es/input/TextArea'
import MyTable from '@/components/MyTable'
import { auditTableC } from '@/utils/tableData'
import { pageShowArr1, pageShowArr2 } from '@/pages/A0goodsInfo/Tab1info/data'
import ImageLazy from '@/components/ImageLazy'
import { baseURL } from '@/utils/http'
function B3look() {
  const { key, id } = useParams<any>()

  // 订单相关信息
  const [topInfo, setTopInfo] = useState({} as B1listType)

  // 藏品相关信息
  const [oldInfo, setOldInfo] = useState({} as B1listType)
  const [newInfo, setNweInfo] = useState({} as B1listType)

  const getInfoFu = useCallback(async (id: number) => {
    const res = await B3_APIgetInfo(id)
    if (res.code === 0) {
      setTopInfo(res.data)

      // 获取藏品修改前的数据

      // 拿到快照新数据
      const goodsArr = res.data.snaps

      if (goodsArr && goodsArr[0] && goodsArr[0].snap) {
        const objStr = goodsArr[0].snap
        try {
          const obj: B1listType = JSON.parse(objStr)

          if (obj.oldGoods) {
            const oldTemp = JSON.parse(obj.oldGoods)

            setOldInfo(oldTemp)
          }

          if (obj.fileIds) {
            const fileArr = obj.fileIds.split(',').map(v => Number(v))

            const res2 = await API_getFileListByIds(fileArr)

            if (res2.code === 0) {
              obj.file = res2.data

              setNweInfo(obj)
            }
          } else setNweInfo(obj)
        } catch (error) {
          MessageFu.warning('JSON数据错误')
        }
      }
    }
  }, [])

  useEffect(() => {
    if (id) getInfoFu(id)
  }, [getInfoFu, id, key])

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

  // 新旧数据对比
  useEffect(() => {
    if (oldInfo.id && newInfo.id) {
      let arr: any[] = []
      ;[...pageShowArr1, ...pageShowArr2].forEach(c => {
        for (const k in oldInfo) {
          if (k === c.key) {
            const oldValObj = oldInfo[k as 'num']
            const newValObj = newInfo[k as 'num']

            const oldVal = c.fu ? c.fu(oldInfo) : oldValObj
            const newVal = c.fu ? c.fu(newInfo) : newValObj

            if (oldVal !== newVal) {
              arr.push({ id: c.name, oldVal, newVal })
            }
          }
        }
      })

      // 封面图处理
      if (oldInfo.thumb !== newInfo.thumb) {
        arr.push({
          id: '封面图',
          oldVal: (
            <div className='tableImgAuto'>
              <ImageLazy
                width={60}
                height={60}
                srcBig={oldInfo.thumbPc || oldInfo.thumb}
                src={oldInfo.thumb}
              />
            </div>
          ),
          newVal: (
            <div className='tableImgAuto'>
              <ImageLazy
                width={60}
                height={60}
                srcBig={newInfo.thumbPc || newInfo.thumb}
                src={newInfo.thumb}
              />
            </div>
          )
        })
      }

      const oldFileArr = (oldInfo.file || []).map(v => v.id).join(',')
      const newFileArr = (newInfo.file || []).map(v => v.id).join(',')

      // 附件处理
      if (oldFileArr !== newFileArr) {
        arr.push({
          id: '附件信息',
          oldVal: (oldInfo.file || []).length
            ? oldInfo.file.map((v: any, i: number) => (
                <a key={v.id} href={baseURL + v.filePath} download target='_blank' rel='noreferrer'>
                  {v.fileName}
                  {i < oldInfo.file!.length - 1 ? '，' : ''}
                </a>
              ))
            : '-',
          newVal: (newInfo.file || []).length
            ? newInfo.file.map((v: any, i: number) => (
                <a key={v.id} href={baseURL + v.filePath} download target='_blank' rel='noreferrer'>
                  {v.fileName}
                  {i < newInfo.file!.length - 1 ? '，' : ''}
                </a>
              ))
            : '-'
        })
      }

      setTableList(arr)

      // console.log(oldInfo, newInfo)
    }
  }, [newInfo, oldInfo])

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

  const boxRef = useRef<HTMLDivElement>(null)

  // 点击提交
  const btnOk = useCallback(async () => {
    if (!auditSta) {
      MessageFu.warning('请选择审批结果')
      boxRef.current?.scrollTo({ top: 0, behavior: 'smooth' })
      return
    }

    const res = await B3_APIaduit({
      orderId: id,
      rtfOpinion,
      status: auditSta === '同意' ? 1 : 2
    })

    if (res.code === 0) {
      MessageFu.success('审批成功')
      history.replace(`/edit_look/1/${id}`)
    }
  }, [auditSta, id, rtfOpinion])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '编辑项',
        render: (item: any) =>
          ['封面图', '附件信息'].includes(item.id) ? (
            <span className='B3tableTit'>{item.id}</span>
          ) : (
            item.id
          )
      },
      {
        title: '编辑前',
        render: (item: any) => item.oldVal || '（空）'
      },
      {
        title: '编辑后',
        render: (item: any) => item.newVal || '（空）'
      }
    ]
  }, [])

  return (
    <div className={styles.B3look} ref={boxRef}>
      <div className='pageTitle'>藏品修改 - {key === '1' ? '查看' : '审批'}</div>

      {oldInfo.id && newInfo.id && topInfo.id ? (
        <>
          <div className='B3lTop'>
            <div className='B3lTopll'>
              <div className='B3lTit'>申请信息</div>
              <div className='B3lTopllBtn'>
                <Button type='dashed'>
                  {statusSelect.find(v => v.value === topInfo.status)?.label}
                </Button>
              </div>
            </div>
            <div className='B3lToprr'>
              {key === '2' ? (
                <>
                  <Button type='primary' onClick={btnOk}>
                    提交
                  </Button>
                  &emsp;
                </>
              ) : null}
              <Button onClick={() => backPageFu('/edit')}>返回</Button>
            </div>
          </div>

          <div className='B3lTxt'>
            <div className='B3lTrow'>
              <div className='B3lTrow1'>订单编号：</div>
              <div className='B3lTrow2'>{topInfo.num}</div>
            </div>
            <div className='B3lTrow'>
              <div className='B3lTrow1'>订单名称：</div>
              <div className='B3lTrow2'>藏品修改</div>
            </div>
            <div className='B3lTrow'>
              <div className='B3lTrow1'>发起人：</div>
              <div className='B3lTrow2'>{topInfo.creatorName + ' - ' + topInfo.createTime}</div>
            </div>

            {/* 审批相关 */}
            {key === '2' ? (
              <>
                <div className='B3lTrow B3lTrowAll'>
                  <div className='B3lTrow1'>
                    <span>* </span>审批结果：
                  </div>
                  <div className='B3lTrow2'>
                    {['同意', '不同意'].map(v => (
                      <Button
                        key={v}
                        onClick={() => setAuDitSta(v)}
                        type={auditSta === v ? 'primary' : 'default'}
                      >
                        {v}
                      </Button>
                    ))}
                  </div>
                </div>
                <div className='B3lTrow B3lTrowAll' style={{ marginBottom: 25 }}>
                  <div className='B3lTrow1'>审批意见：</div>
                  <div className='B3lTrow2'>
                    <TextArea
                      value={rtfOpinion}
                      onChange={e => setRtfOpinion(e.target.value)}
                      placeholder='请输入内容'
                      maxLength={200}
                      showCount
                    />
                  </div>
                </div>
              </>
            ) : null}
          </div>

          <div className='B3lTit'>修改详情</div>

          <MyTable
            list={tableList}
            columnsTemp={[]}
            lastBtn={tableLastBtn}
            pagingInfo={false}
            widthSet={{ rtfOpinion: 600 }}
          />
          <br />
          <div className='B3lTit'>申请流程</div>
          <MyTable
            list={topInfo.audits || []}
            columnsTemp={auditTableC}
            pagingInfo={false}
            widthSet={{ rtfOpinion: 600 }}
          />
        </>
      ) : null}
    </div>
  )
}

const MemoB3look = React.memo(B3look)

export default MemoB3look
