import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { useParams } from 'react-router-dom'
import { Y1tabArr, Y1TabArrType } from '../Y1cathet/Y1main'
import classNames from 'classnames'
import { Button, Dropdown, MenuProps, Tag } from 'antd'
import Y11com from '../Y1cathet/Y11com'
import Y22com from '../Y1cathet/Y22com'
import Y33com from '../Y1cathet/Y33com'
import Y44com from '../Y1cathet/Y44com'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import { API_getGoodsLedger, API_goodsInfo } from '@/store/action/C1ledger'
import { EXPORT_WORD_ENUM, exportWordHandler } from '@/utils/exportTemplates'
import { API_goodFileList } from '@/store/action/C2files'
import { C3_APIfocus, C3_APIfocusNo } from '@/store/action/C3focus'
import { MessageFu } from '@/utils/message'
import C22revamp from '@/pages/C_goodsManage/C22goodEdit/C22revamp'
import history, { useQuery } from '@/utils/history'
import { statusStorageObj } from '@/utils/tableData'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import NoPower from '@/components/NoPower'
import { selectObj } from '@/utils/select'

function Y2look() {
  // 获取权限数据
  const goodsInfoPower = useSelector((state: RootState) => state.A0Layout.goodsInfoPower)
  const downImg = useSelector((state: RootState) => state.A0Layout.downImg)

  const { id: sId, menuId } = useParams<any>()
  const query = useQuery()

  const [info, setInfo] = useState({} as C1GoodType)

  const getInfoFu = useCallback(
    async (id: number) => {
      const res = await API_goodsInfo(id, menuId, query.oId)
      if (res.code === 0) {
        setInfo(res.data)
      }
    },
    [menuId, query.oId]
  )

  const handleExport = async () => {
    Promise.all([API_goodFileList(sId), API_getGoodsLedger(sId)]).then(res => {
      exportWordHandler(EXPORT_WORD_ENUM.COLLECTION_ARCHIVES, {
        ...info,
        records: res[1].data
          .filter((i: any) => i.type === 'JD')
          .map((i: any) => ({ ...i, ...JSON.parse(i.snap) })),
        repairs: res[1].data
          .filter((i: any) => i.type === 'XF')
          .map((i: any) => ({ ...i, ...JSON.parse(i.snap) })),
        status: res[1].data
          .filter((i: any) => i.type === 'XZ')
          .map((i: any) => ({ ...i, ...JSON.parse(i.snap) })),
        imagePages: [
          {
            thumb: info.thumb
          },
          ...(res[0].data?.filter((i: any) => i.type === 'img') || [])
        ]
      })
    })
  }
  const handleExport2 = async () => {
    const res = await API_getGoodsLedger(sId)
    exportWordHandler(EXPORT_WORD_ENUM.COLLECTION_CARD, {
      ...info,
      records: res.data
        .filter((i: any) => i.type === 'JD')
        .map((i: any) => ({ ...i, ...JSON.parse(i.snap) }))
    })
  }

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

  const [tabAc, setTabAc] = useState<Y1TabArrType>('藏品信息')

  const items1 = useMemo(() => {
    let arr: MenuProps['items'] = [
      {
        key: '1',
        label: (
          <span
            className='Y2xia'
            onClick={() => {
              if (info.isEdit === 1) MessageFu.warning('该藏品修改审核中，无法重复修改')
              else setIsEdit(true)
            }}
          >
            编辑
          </span>
        )
      },
      {
        key: '2',
        label: (
          <span
            style={{ color: '#ff4d4d' }}
            className='Y2xia'
            onClick={() => {
              if (info.statusStorage === 6) {
                MessageFu.warning('该藏品注销审核中，无法重复注销')
              } else if (info.statusStorage === 7) {
                MessageFu.warning('该藏品已注销')
              } else history.push(`/cancel_edit/1/null?id=${sId}`)
            }}
          >
            注销
          </span>
        )
      }
    ]

    return arr
  }, [info.isEdit, info.statusStorage, sId])

  const items2 = useMemo(() => {
    let arr: MenuProps['items'] = [
      {
        key: '1',
        label: (
          <span
            className='Y2xia'
            onClick={() => {
              if (!info.statusStorage || info.statusStorage === 4) {
                history.push(`/impStor_edit/1/null?id=${sId}`)
              } else {
                const txt = statusStorageObj[info.statusStorage]
                MessageFu.warning(`该藏品${txt}，无法入库`)
              }
            }}
          >
            入库
          </span>
        )
      },
      {
        key: '2',
        label: (
          <span
            className='Y2xia'
            onClick={() => {
              let txt = statusStorageObj[info.statusStorage] || ''
              const txtRes = txt ? `该藏品${txt}，` : ''
              if (info.statusStorage === 2) history.push(`/moveStor_edit/1/null?id=${sId}`)
              else MessageFu.warning(txtRes + `只有已入库的藏品才能移库`)
            }}
          >
            移库
          </span>
        )
      },
      {
        key: '3',
        label: (
          <span
            className='Y2xia'
            onClick={() => {
              let txt = statusStorageObj[info.statusStorage] || ''
              const txtRes = txt ? `该藏品${txt}，` : ''
              if (info.statusStorage === 2) history.push(`/putsStor_edit/1/null?id=${sId}`)
              else MessageFu.warning(txtRes + `只有已入库的藏品才能出库`)
            }}
          >
            出库
          </span>
        )
      }
    ]
    return arr
  }, [info.statusStorage, sId])

  const items3 = useMemo(() => {
    let arr: MenuProps['items'] = [
      {
        key: '1',
        label: (
          <span className='Y2xia' onClick={() => history.push(`/accident_edit/1/null?id=${sId}`)}>
            事故登记
          </span>
        )
      },

      {
        key: '3',
        label: (
          <span className='Y2xia' onClick={() => history.push(`/actuality_edit/1/null?id=${sId}`)}>
            现状登记
          </span>
        )
      },
      {
        key: '4',
        label: (
          <span className='Y2xia' onClick={() => history.push(`/repair_edit/1/null?id=${sId}`)}>
            文物修复
          </span>
        )
      }
    ]
    return arr
  }, [sId])

  // 点击关注
  const focusFu = useCallback(
    async (val: '关注' | '取消关注') => {
      const res = val === '关注' ? await C3_APIfocus(sId) : await C3_APIfocusNo(sId)

      if (res.code === 0) {
        MessageFu.success(val + '成功!')
        getInfoFu(sId)
      }
    },
    [getInfoFu, sId]
  )

  // 点击藏品编辑（修改）
  const [isEdit, setIsEdit] = useState(false)

  return (
    <div className={styles.Y2look}>
      <div className='pageTitle'>
        藏品详情
        {info.statusStorage > 0 && (
          <Tag>{selectObj['库存状态'].find(i => i.value === info.statusStorage)?.label}</Tag>
        )}
      </div>
      <div className='Y2top'>
        <div className='Y2topll'>
          {Y1tabArr.map(v => (
            <div
              key={v}
              className={classNames('Y1tRow', tabAc === v ? 'Y1tRowAc' : '')}
              onClick={() => setTabAc(v)}
            >
              {v}
            </div>
          ))}
        </div>
        <div className='Y2toprr'>
          {info.display === 1 && info.statusStorage !== 7 ? (
            <>
              <Button
                type='primary'
                danger={info.isFocus === 1}
                onClick={() => focusFu(info.isFocus === 1 ? '取消关注' : '关注')}
              >
                {info.isFocus === 1 ? '取消' : ''}关注
              </Button>
              &emsp;
              {goodsInfoPower.includes('goodsBtn1') ? (
                <>
                  <Button type='primary' onClick={handleExport}>
                    导出藏品档案
                  </Button>
                  &emsp;
                </>
              ) : null}
              {goodsInfoPower.includes('goodsBtn2') ? (
                <>
                  <Button type='primary' onClick={handleExport2}>
                    导出藏品卡片
                  </Button>
                  &emsp;
                </>
              ) : null}
              {goodsInfoPower.includes('goodsBtn3') ? (
                <>
                  <Dropdown menu={{ items: items1 }} placement='bottom' arrow>
                    <Button type='primary'>档案管理</Button>
                  </Dropdown>
                  &emsp;
                </>
              ) : null}
              {goodsInfoPower.includes('goodsBtn4') ? (
                <>
                  <Dropdown menu={{ items: items2 }} placement='bottom' arrow>
                    <Button type='primary'>分库管理</Button>
                  </Dropdown>
                  &emsp;
                </>
              ) : null}
              {goodsInfoPower.includes('goodsBtn5') ? (
                <>
                  <Dropdown menu={{ items: items3 }} placement='bottom' arrow>
                    <Button type='primary'>保管管理</Button>
                  </Dropdown>
                  &emsp;
                </>
              ) : null}
            </>
          ) : null}

          {/* <Button onClick={() => history.go(-1)}>返回</Button> */}
        </div>
      </div>

      {info.id ? (
        <div className='Y2info'>
          {tabAc === '藏品信息' ? (
            goodsInfoPower.includes('goodsPage1') ? (
              <Y11com info={info} />
            ) : (
              <NoPower />
            )
          ) : null}
          {tabAc === '库存信息' ? (
            goodsInfoPower.includes('goodsPage2') ? (
              <Y22com info={info} />
            ) : (
              <NoPower />
            )
          ) : null}
          {tabAc === '藏品附件' ? (
            goodsInfoPower.includes('goodsPage3') || downImg['可见'] ? (
              <Y33com sId={sId} isLook={true} info={info} setImgCover={() => getInfoFu(sId)} />
            ) : (
              <NoPower />
            )
          ) : null}
          {tabAc === '藏品日志' ? (
            goodsInfoPower.includes('goodsPage4') ? (
              <Y44com sId={sId} isLook={true} />
            ) : (
              <NoPower />
            )
          ) : null}
        </div>
      ) : null}

      {isEdit ? (
        <div className='C22revampBox'>
          <C22revamp goodsId={sId} closeFu={() => setIsEdit(false)} type='新增' />
        </div>
      ) : null}
    </div>
  )
}

const MemoY2look = React.memo(Y2look)

export default MemoY2look
