import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
import {
  C6_APIdel,
  C6_APIgetInfo,
  C6_APIrevocation,
  C6_APIsaveApply,
  C6_APIsaveAudit
} from '@/store/action/C6edit'
import { MessageFu } from '@/utils/message'
import C22revamp, { OldNewType } from '../C22revamp'
import history, { openGoodsInfoFu, textFu } from '@/utils/history'
import { pageTitTxtObj } from '@/pages/D_storeManage/D4impStor/D4edit'
import { Button } from 'antd'
import { statusObj } from '@/utils/tableData'
import X3auditInfo from '@/pages/X_stock/X3auditInfo'
import ZupFileTable from '@/components/ZupFileTable'
import { C22infoBtnFu } from '../data'
import { EXbtnFu } from '@/utils/EXBtn'
import MyPopconfirm from '@/components/MyPopconfirm'
import ZflowTable from '@/components/ZflowTable'
import { GoodFileType } from '@/components/Z3upFiles'
import { baseURL } from '@/utils/http'
import ImageLazy from '@/components/ImageLazy'
import X2lookText from '@/pages/X_stock/X2lookText'
import MyTable from '@/components/MyTable'
function C22look() {
  const { key, id } = useParams<any>()
  // key: 3审批 4查看

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

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

  // 获取详情
  const getInfoFu = useCallback(async () => {
    const res = await C6_APIgetInfo(id)
    if (res.code === 0) {
      const data = res.data
      setTopInfo(data)
      if (data.snaps && data.snaps.length) {
        const info = JSON.parse(data.snaps[0].snap)
        setOldNewArr(info.pageShow)
      }
    }
  }, [id])

  useEffect(() => {
    getInfoFu()
  }, [getInfoFu])

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

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

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

  // 点击编辑
  const editBtnFu = useCallback(() => {
    setIsEdit(true)
  }, [])

  // 点击提交
  const btnOkFu = useCallback(async () => {
    const res = await C6_APIsaveApply(topInfo)
    if (res.code === 0) {
      MessageFu.success('提交成功')
      history.push('/goodEdit')
    }
  }, [topInfo])

  // 点击删除
  const delFu = useCallback(async () => {
    const res = await C6_APIdel(id)
    if (res.code === 0) {
      MessageFu.success('删除成功')
      history.push('/goodEdit')
    }
  }, [id])

  // 点击撤回
  const cheHuiFu = useCallback(async () => {
    // 撤回-该状态 刷新当前页
    const res = await C6_APIrevocation(id)
    if (res.code === 0) {
      MessageFu.success('撤回成功')
      if (sollrDom.current) sollrDom.current.scrollTop = 0
      getInfoFu()
    }
  }, [getInfoFu, id])

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

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

    if (res.code === 0) {
      MessageFu.success('提交成功')
      history.push(`/goodEdit`)
    }
  }, [auditSta, topInfo.id])

  const [isEdit, setIsEdit] = useState(false)

  //查看富文本信息
  const [look, setLook] = useState('')

  // 新旧附件信息对比
  const [oldNewArr, setOldNewArr] = useState<OldNewType[]>([])

  // 编辑明细 表格

  const tableLastBtn2Fu = useCallback((item: OldNewType, key: 'qian' | 'hou') => {
    if (item.name === '备注') {
      if (textFu(item[key] as string)) {
        return (
          <Button size='small' type='text' onClick={() => setLook(textFu(item[key] as string))}>
            查看
          </Button>
        )
      } else return '-'
    } else if (item.name === '附件信息') {
      let arr = item[key] as GoodFileType[]

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

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

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '编辑项',
        render: (item: OldNewType) =>
          ['封面图', '附件信息', '备注'].includes(item.name) ? (
            <span className='C6tab2Tit'>{item.name}</span>
          ) : (
            item.name
          )
      },
      {
        title: '编辑前',
        render: (item: OldNewType) => tableLastBtn2Fu(item, 'qian')
      },
      {
        title: '编辑后',
        render: (item: OldNewType) => tableLastBtn2Fu(item, 'hou')
      }
    ]
  }, [tableLastBtn2Fu])

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

      {/* 主体 */}
      <div className='C22lBox' ref={sollrDom}>
        <div className='C22Tit'>
          申请信息
          {key === '1' ? null : (
            <Button type='dashed'>{Reflect.get(statusObj, topInfo.status)}</Button>
          )}
        </div>
        {topInfo.id ? (
          <div className='C22rowAll'>
            <div className='C22row'>
              <div className='C22rowll'>业务单号：</div>
              <div className='C22rowrr'>{topInfo.num}</div>
            </div>

            <div className='C22row'>
              <div className='C22rowll'>业务名称：</div>
              <div className='C22rowrr'>{topInfo.name}</div>
            </div>

            <div className='C22row'>
              <div className='C22rowll'>发起人：</div>
              <div className='C22rowrr'>{topInfo.creatorName + ' - ' + topInfo.createTime}</div>
            </div>

            <div className='C22row'>
              <div className='C22rowll'>发起部门：</div>
              <div className='C22rowrr'>{topInfo.deptName}</div>
            </div>
          </div>
        ) : null}

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

        <div className='C22Tit C22Tit2'>
          修改明细
          <div className='C22TitRR'>
            <Button type='primary' onClick={() => openGoodsInfoFu(Number(topInfo.goodsIds))}>
              藏品详情
            </Button>
          </div>
        </div>

        <div className='C22table'>
          {/* 表格 */}
          <MyTable
            rowKey='name'
            list={oldNewArr}
            columnsTemp={[]}
            lastBtn={tableLastBtn}
            pagingInfo={false}
          />
        </div>

        {/* 附件归档 */}
        {topInfo.status === 4 ? (
          <ZupFileTable
            listTemp={topInfo.filing || []}
            dirCode='C22orderEdit'
            myUrl='cms/orderEdit/upload'
            fromData={{ moduleId: topInfo.id }}
          />
        ) : null}
      </div>

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

        {/* 能进审批页，点审批按钮的必定有权限 */}
        {key === '3' ? (
          C22infoBtnFu(topInfo)['审批'] ? (
            <Button type='primary' onClick={auditFu}>
              提交
            </Button>
          ) : null
        ) : (
          <>
            {C22infoBtnFu(topInfo)['编辑'] ? (
              <Button type='primary' onClick={editBtnFu}>
                编辑
              </Button>
            ) : null}
            {C22infoBtnFu(topInfo)['提交'] ? (
              <Button type='primary' onClick={btnOkFu}>
                提交
              </Button>
            ) : null}

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

            {EXbtnFu(topInfo)}

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

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

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

      {/* 在点编辑 在打开编辑弹窗 */}
      {isEdit ? (
        <div className='C22revampBox'>
          <C22revamp
            upTableFu={() => {
              if (sollrDom.current) sollrDom.current.scrollTop = 0
              getInfoFu()
            }}
            goodsId={Number(topInfo.goodsIds)}
            sId={id}
            closeFu={() => setIsEdit(false)}
            type='编辑'
          />
        </div>
      ) : null}

      {/* 查看富文本 */}
      {look ? <X2lookText closeFu={() => setLook('')} text={look} /> : null}
    </div>
  )
}

const MemoC22look = React.memo(C22look)

export default MemoC22look
