import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { GoodsType } from '../Zother/SonGoodsList/data'
import { API_getGoodsInfo } from '@/store/action/Cledger/C1ledger'
import { useParams } from 'react-router-dom'
import { resTagFu, selectObj } from '@/utils/dataChange'
import { Button, Dropdown, Tag } from 'antd'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import classNames from 'classnames'
import history from '@/utils/history'
import { authorityFu } from '@/utils/authority'
import { CaretDownOutlined } from '@ant-design/icons'
import GItab1 from './GItab1'
import GItab2 from './GItab2'
import GItab3 from './GItab3'
import GItab4 from './GItab4'
import GItab5 from './GItab5'
import { MessageFu } from '@/utils/message'
import { FileListType } from '@/components/Z3upFiles/data'
import { API_getFileListByIds } from '@/store/action/Cledger/C4file'
import { infoPageIDGet, infoPageIDSet } from '@/utils/storage'
import AddGoods from '../Zother/AddGoods'
import { D2API_obj } from '@/store/action/Dmanage/D2edit'

type tabArr1Type = {
  id: number
  name: string
  done: boolean
  show: boolean
  son?: any[]
  Dom?: any
}

function ZgoodsInfo() {
  const { id } = useParams<any>()
  // 藏品详情
  const [info, getInfo] = useState({} as GoodsType)
  // 藏品附件
  const [fileList, setFileList] = useState<FileListType[]>([])
  const getInfoFu = useCallback(async () => {
    const res = await API_getGoodsInfo(id)
    if (res.code === 0) {
      getInfo(res.data)
      // 获取附件信息
      const fileIds = res.data.fileIds || ''
      if (fileIds) {
        const res22 = await API_getFileListByIds(fileIds.split(','))
        if (res22.code === 0) {
          setFileList(res22.data)
        }
      }
    }
  }, [id])
  useEffect(() => {
    getInfoFu()
  }, [getInfoFu])

  const tabArr1Temp = useMemo(() => {
    return [
      {
        id: 331,
        name: '藏品信息',
        done: false,
        show: false,
        Dom: <GItab1 info={info} fileList={fileList} />
      },
      { id: 332, name: '库存信息', done: false, show: false, Dom: <GItab2 info={info} /> },
      {
        id: 333,
        name: '藏品附件',
        done: false,
        show: false,
        Dom: <GItab3 info={info} fileList={fileList} />
      },
      { id: 334, name: '藏品故事', done: false, show: false, Dom: <GItab4 goodId={info.id} /> },
      { id: 335, name: '藏品日志', done: false, show: false, Dom: <GItab5 goodId={info.id} /> }
    ]
  }, [fileList, info])

  // 藏品修改模块特有的
  const [goodInfo, setGoodInfo] = useState({} as GoodsType)

  // 点击的时候校验前置状态和页面权限
  const tabArr2Temp = useMemo(() => {
    let arr: any[] = []
    if ([3, 4, 6, 7].includes(info.status)) {
      arr = [
        {
          id: 336,
          name: '档案管理',
          done: true,
          show: true,
          son: [
            {
              key: '1',
              label: '修改',
              onClick: () => {
                if (info.isEdit === 1) return MessageFu.warning(`当前藏品为 修改中 状态，不可 修改`)
                authorityFu(420, '藏品修改', () => setGoodInfo(info))
              }
            },
            {
              key: '2',
              label: '注销',
              onClick: () => {
                if ([3, 6].includes(info.status)) {
                  authorityFu(430, '藏品注销', () =>
                    history.push(`/writeOff_edit/1/null?gId=${id}`)
                  )
                } else {
                  const txtObj = selectObj['藏品入藏状态'].find(v => v.value === info.status)
                  MessageFu.warning(`当前藏品为 ${txtObj ? txtObj.label : '草稿'} 状态，不可 注销`)
                }
              }
            }
          ]
        },
        {
          id: 337,
          name: '库房管理',
          done: true,
          show: true,
          son: [
            {
              key: '1',
              label: '入库',
              onClick: () => {
                if (!info.siteStatus || info.siteStatus === 1) {
                  authorityFu(1010, '藏品入库', () =>
                    history.push(`/inStorage_edit/1/null?gId=${id}`)
                  )
                } else {
                  const txtObj = selectObj['藏品库存状态'].find(v => v.value === info.siteStatus)
                  MessageFu.warning(`当前藏品为 ${txtObj ? txtObj.label : '草稿'} 状态，不可 入库`)
                }
              }
            },
            {
              key: '2',
              label: '移库',
              onClick: () => {
                if (info.siteStatus === 3) {
                  authorityFu(1020, '藏品移库', () =>
                    history.push(`/moveStorage_edit/1/null?gId=${id}`)
                  )
                } else {
                  const txtObj = selectObj['藏品库存状态'].find(v => v.value === info.siteStatus)
                  MessageFu.warning(
                    `当前藏品为 ${txtObj ? txtObj.label : '未入库'} 状态，不可 移库`
                  )
                }
              }
            },
            {
              key: '3',
              label: '出库',
              onClick: () => {
                if (info.siteStatus === 3) {
                  authorityFu(1030, '藏品出库', () =>
                    history.push(`/outStorage_edit/1/null?gId=${id}`)
                  )
                } else {
                  const txtObj = selectObj['藏品库存状态'].find(v => v.value === info.siteStatus)
                  MessageFu.warning(
                    `当前藏品为 ${txtObj ? txtObj.label : '未入库'} 状态，不可 出库`
                  )
                }
              }
            }
          ]
        },
        {
          id: 338,
          name: '藏品维护',
          done: true,
          show: true,
          son: [
            {
              key: '1',
              label: '鉴定登记',
              onClick: () =>
                authorityFu(230, '藏品鉴定', () => history.push(`/auth_edit/1/null?gId=${id}`))
            },
            {
              key: '2',
              label: '事故登记',
              onClick: () =>
                authorityFu(510, '事故登记', () => history.push(`/accident_edit/1/null?gId=${id}`))
            },
            {
              key: '3',
              label: '现状登记',
              onClick: () =>
                authorityFu(540, '现状登记', () => history.push(`/actuality_edit/1/null?gId=${id}`))
            },
            {
              key: '4',
              label: '修复登记',
              onClick: () =>
                authorityFu(550, '修复登记', () => history.push(`/repair_edit/1/null?gId=${id}`))
            }
          ]
        }
      ]
    }

    return arr
  }, [id, info])

  const [tabArr1, setTabArr1] = useState<tabArr1Type[]>([])
  const [loding, setLoding] = useState(false)

  const [tabArr2, setTabArr2] = useState<tabArr1Type[]>([])

  const authorityIds = useSelector((state: RootState) => state.A0Layout.authorityIds)

  useEffect(() => {
    const newArr1 = tabArr1Temp.filter(v => authorityIds.includes(v.id))
    if (newArr1.length) {
      let index = 0
      const acId = infoPageIDGet()
      if (acId) {
        const index22 = newArr1.findIndex(c => c.id === acId)
        if (index22 >= 0) index = index22
      }
      newArr1[index].done = newArr1[index].show = true
    }
    setTimeout(() => {
      setLoding(true)
    }, 300)

    setTabArr1(newArr1)
    setTabArr2(tabArr2Temp.filter(v => authorityIds.includes(v.id)))
  }, [authorityIds, tabArr1Temp, tabArr2Temp])

  // 获取标签
  const tagDom = useMemo(() => {
    let dom: any = ''

    if (info.tagDictId) {
      dom = []
      const txt: string = resTagFu(info.tagDictId, '藏品')

      if (txt) {
        const arr = txt.split('；')
        arr.forEach((v, i) => {
          dom.push(
            <Tag key={i} className='GItag'>
              {v}
            </Tag>
          )
        })
      }

      const txt2: string = resTagFu(info.artDictId, '文创')

      if (txt2) {
        const arr = txt2.split('；')
        arr.forEach((v, i) => {
          dom.push(
            <Tag key={v + i} className='GItag2'>
              {v}
            </Tag>
          )
        })
      }
    }
    return dom
  }, [info.artDictId, info.tagDictId])

  // 切换左侧tab
  const cutTabFu = useCallback(
    (id: number) => {
      infoPageIDSet(id)
      setTabArr1(
        tabArr1.map(v => ({
          ...v,
          done: v.id === id && !v.done ? true : v.done,
          show: v.id === id
        }))
      )
    },
    [tabArr1]
  )

  // 藏品状态
  const goodsStatus = useMemo(() => {
    let txt = '草稿'
    const obj = selectObj['藏品入藏状态'].find(v => v.value === info.status)
    if (obj) txt = obj.label
    return txt
  }, [info.status])

  return (
    <div className={styles.ZgoodsInfo}>
      <div className='GITot'>
        <h2>{info.name || ''}</h2>
        {info.id ? (
          <i style={{ color: info.status === 8 ? '#ff4d4f' : '' }}>({goodsStatus})</i>
        ) : null}
        {tagDom}
      </div>
      {info.id ? (
        <>
          <div className='GItab'>
            <div>
              {tabArr1.map(item => (
                <div
                  className={classNames('GItab1', item.show ? 'GItab1Ac' : '')}
                  key={item.id}
                  onClick={() => cutTabFu(item.id)}
                >
                  {item.name}
                </div>
              ))}
            </div>
            {/* 已删除状态隐藏右侧抽屉按钮 */}
            {!info.status || [8, 0].includes(info.status) ? (
              <div></div>
            ) : (
              <div>
                {tabArr2.map(item => (
                  <Dropdown key={item.id} menu={{ items: item.son }} trigger={['click']}>
                    <Button type='primary'>
                      {item.name}
                      <CaretDownOutlined />
                    </Button>
                  </Dropdown>
                ))}
              </div>
            )}
          </div>
          {/* 主体 */}
          <div className='GImain'>
            {tabArr1.length ? (
              <>
                {tabArr1.map(item => (
                  <div key={item.id} hidden={!item.show}>
                    {item.done ? item.Dom : null}
                  </div>
                ))}
              </>
            ) : (
              <div className='GImainNone' hidden={!loding}>
                暂无权限，请联系管理员进行授权
              </div>
            )}
          </div>
        </>
      ) : (
        <div className='GImainNone' hidden={!loding}>
          找不到相关藏品信息
        </div>
      )}
      {/* 藏品编辑弹窗 */}
      {goodInfo.id ? (
        <AddGoods
          info={goodInfo}
          closeFu={() => setGoodInfo({} as GoodsType)}
          isEdit={true}
          succFu={async (val, newObj, oldObj, keyArr) => {
            const res = await D2API_obj['创建订单']()
            if (res.code === 0) {
              const dingDanObj = res.data
              const obj = {
                ...dingDanObj,
                goodIds: newObj.id + '',
                snaps: [
                  {
                    id: null,
                    goodId: newObj.id,
                    orderId: dingDanObj.id,
                    snap: JSON.stringify({
                      new: newObj,
                      old: oldObj,
                      keyArr
                    })
                  }
                ]
              }
              const res2 = await D2API_obj['草稿'](obj)
              if (res2.code === 0) {
                MessageFu.success('藏品修改-' + val + '订单成功')
                history.push(`/edit_edit/2/${dingDanObj.id}`)
              }
            }
          }}
          moduleId={0}
          fileUpInfo={{ myUrl: 'cms/order/edit/son/upload', dirCode: 'goodEditSon' }}
          APIsave={null}
        />
      ) : null}
    </div>
  )
}

const MemoZgoodsInfo = React.memo(ZgoodsInfo)

export default MemoZgoodsInfo
