import { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { selectObj } from '@/utils/dataChange'
import { useParams } from 'react-router-dom'
import { Button } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import { useInfo } from '../InfoContext'
import Z3upFiles from '@/components/Z3upFiles'
import { API_objType } from '@/store/action/Dmanage/D1register'
import { editPageToTopFu } from '@/utils/authority'
import { FileUpInfoType } from '../data'
import EditInput from '../EditInput'
import SelectGoods from '../SelectGoods'
import { GoodsType, sgBaseFormDataGood, sgTopSelectDomGood } from '../SonGoodsList/data'
import { goodsSonTableC } from '@/utils/tableData'
import ImageLazy from '@/components/ImageLazy'
import { openLink } from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'
import { API_getFileListByIds } from '@/store/action/Cledger/C4file'
import { API_getGoodsInfo } from '@/store/action/Cledger/C1ledger'

export const pageKeyTxtObj = {
  1: '新增',
  2: '编辑',
  3: '审批',
  4: '查看'
}

export const auditBtnArr = [
  { value: 1, label: '同意' },
  { value: 2, label: '不同意' }
]

type Props = {
  // 顶部信息录入
  rowArr: any[]
  // 页面字段
  pageTxt: string
  // api
  APIobj: API_objType
  // 上传附件的信息
  fileUpInfo: FileUpInfoType
  // 第二个模块
  moreDom?: {
    txt: string
    API: any
    domList: any[]
    tit?: string
    myUrl?: string
    dirCode?: string
  }
}

function EditTop({ rowArr, pageTxt, APIobj, fileUpInfo, moreDom }: Props) {
  const { info, setInfoFu, snaps, setSnapsFu, timeKey, auditInfo, setAuditInfoFu, setEditObjFu } =
    useInfo()

  // 从藏品详情进来的-获取藏品详情
  const getGoodsInfoFu = useCallback(
    async (id: number) => {
      const res = await API_getGoodsInfo(id)
      if (res.code === 0) {
        setSnapsFu([{ ...res.data, idTemp: res.data.id }])
      }
    },
    [setSnapsFu]
  )
  useEffect(() => {
    const urlAll = window.location.href
    if (urlAll.includes('?gId=')) {
      const gId = urlAll.split('?gId=')[1]
      getGoodsInfoFu(Number(gId))
    }
  }, [getGoodsInfoFu])

  const { key, id } = useParams<any>()
  // key:1 新增 2编辑 3审批 4查看

  const isLook = useMemo(() => {
    return ['3', '4'].includes(key)
  }, [key])

  // 创建订单
  const createFu = useCallback(async () => {
    const res = await APIobj['创建订单']()
    if (res.code === 0) {
      setInfoFu(res.data)

      // 从盘点过来---回显数据
      const urlAll = window.location.href
      if (urlAll.includes('?pNum=')) {
        const txt = urlAll.split('?pNum=')[1]
        const arr = txt.split(',')
        const goodId = Number(arr[1])

        const res2 = await API_getGoodsInfo(goodId)
        if (res2.code === 0) {
          setSnapsFu([{ ...res2.data, idTemp: res2.data.id }])
          const obj: any = { oderNum: arr[0] }
          setInfoFu(obj, true)
        }
      }
    }
  }, [APIobj, setInfoFu, setSnapsFu])

  // 获取详情
  const getInfoFu = useCallback(
    async (id: number) => {
      const res = await APIobj['获取详情'](id)
      if (res.code === 0) {
        // 回到顶部
        editPageToTopFu()

        const data = res.data
        setInfoFu(data)

        // 设置有关藏品的信息
        // 藏品清单快照信息id对比
        let arrTemp: any = []

        const snapsTemp = data.snaps || []
        snapsTemp.forEach(async (v: any, i: number) => {
          // console.log('ssssss', v)

          const obj = JSON.parse(v.snap || '{}')

          const flag = v.pageType === 'clue' && !v.clueId
          if (obj.id == null || obj.isNew || flag)
            obj.id = ['藏品登记', '藏品入馆'].includes(pageTxt) ? v.goodId : Date.now() + i

          obj.idTemp = obj.id

          if (v.siteId != null) {
            obj.siteId = v.siteId ?? obj.siteId
          }

          arrTemp.push(obj)

          // 第二个模块的信息回显
          if (moreDom && moreDom.domList && moreDom.domList.length && i === 0) {
            let obj2: any = {}
            moreDom.domList.forEach((item: any) => {
              obj2[item.key] = obj[item.key]
            })

            setInfoFu(obj2, true)
            // 设置第二个模块的附件
            if (obj.fileIds2) {
              const res22 = await API_getFileListByIds(
                obj.fileIds2.split(',').map((v: string) => Number(v))
              )
              if (res22.code === 0) {
                setInfoFu({ ...data, files2: res22.data })
              }
            }
          }
        })

        // console.log('-------', arrTemp)
        if (pageTxt === '藏品修改') {
          if (arrTemp[0] && arrTemp[0].old) {
            const editObj = arrTemp[0].old
            setSnapsFu([{ ...editObj, idTemp: editObj.id }])
            setEditObjFu(arrTemp[0])
          }
        } else setSnapsFu(arrTemp.filter((v: any) => v.idTemp))
      }
    },
    [APIobj, moreDom, pageTxt, setEditObjFu, setInfoFu, setSnapsFu]
  )

  useEffect(() => {
    if (key === '1') createFu()
    else getInfoFu(id)
  }, [createFu, getInfoFu, id, key, timeKey])

  // 页面最上部文字
  const pageKeyTxt = useMemo(() => {
    return Reflect.get(pageKeyTxtObj, key)
  }, [key])

  // 订单申请状态
  const statusTxt = useMemo(() => {
    let txt = ''
    const obj = selectObj['订单审批状态'].find(v => v.value === info.status)

    // 新增的时候看不到状态
    if (key !== '1' && obj) txt = obj.label
    return txt
  }, [info.status, key])

  // 选择单个藏品
  const [selectShow, setSelectShow] = useState(false)

  return (
    <div className={styles.EditTop}>
      <div className='pageTitle'>
        {pageTxt}-{pageKeyTxt}
      </div>

      {info.id ? (
        <>
          {key === '3' ? (
            <>
              <div className='EdTit'>
                <div>审批信息</div>
              </div>
              <div className='Edtop1'>
                <div className='Edtop1row Edtop1rowFull'>
                  <div className='Edtop1ll'>
                    <span>* </span>审批结果：
                  </div>
                  <div className='Edtop1rr'>
                    {auditBtnArr.map(btn => (
                      <Button
                        key={btn.value}
                        type={btn.value === auditInfo.status ? 'primary' : 'default'}
                        onClick={() => setAuditInfoFu('status', btn.value)}
                      >
                        {btn.label}
                      </Button>
                    ))}
                  </div>
                </div>

                <div className='Edtop1row Edtop1rowFull'>
                  <div className='Edtop1ll'>审批意见：</div>
                  <div className='Edtop1rr'>
                    <TextArea
                      placeholder='请输入'
                      value={auditInfo.rtfOpinion}
                      onChange={e => setAuditInfoFu('rtfOpinion', e.target.value)}
                      maxLength={500}
                      showCount
                    />
                  </div>
                </div>
              </div>
            </>
          ) : null}

          <div className='EdTit'>
            <div>
              申请信息
              {statusTxt ? (
                <Button className='EdTitBtn' type='dashed'>
                  {statusTxt}
                </Button>
              ) : null}
            </div>
          </div>
          <div className='Edtop1'>
            {rowArr.map((item, index) => (
              <EditInput key={index} item={item} isLook={isLook} />
            ))}

            {/* 附件 */}
            <div className='Edtop1row Edtop1rowFull'>
              <div className='Edtop1ll'>附件：</div>
              <div className='Edtop1rr'>
                <Z3upFiles isLook={isLook} {...fileUpInfo} />
              </div>
            </div>
          </div>

          {/* 第二个模块 */}
          {moreDom ? (
            <>
              <div className='EdTit'>
                <div>{moreDom.txt}</div>
              </div>
              <div className='Edtop1'>
                <div className='Edtop1row Edtop1rowFull'>
                  <div className='Edtop1ll'>
                    <span>* </span>
                    {moreDom.tit || '关联藏品'}：
                  </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 : (
                          <MyPopconfirm txtK='删除' onConfirm={() => setSnapsFu([])} />
                        )}
                      </div>
                    </div>
                  ) : isLook ? (
                    '（空）'
                  ) : (
                    <div className='Edtop1rr'>
                      <Button
                        type='primary'
                        onClick={() => {
                          setSelectShow(true)
                        }}
                      >
                        选择藏品
                      </Button>
                    </div>
                  )}
                </div>

                {moreDom.domList.map((item, index) => (
                  <EditInput key={index} item={item} isLook={isLook} isTow={true} />
                ))}

                {/* 附件 */}
                <div className='Edtop1row Edtop1rowFull'>
                  <div className='Edtop1ll'>附件：</div>
                  <div className='Edtop1rr'>
                    <Z3upFiles
                      isLook={isLook}
                      myUrl={moreDom.myUrl || fileUpInfo.myUrl}
                      dirCode={moreDom.dirCode || fileUpInfo.dirCode}
                      filesKey='files2'
                    />
                  </div>
                </div>
              </div>
            </>
          ) : null}
        </>
      ) : null}

      {/* 选择单个藏品 */}
      {selectShow && moreDom ? (
        <SelectGoods
          myType='藏品'
          isOne={true}
          API_getList={moreDom.API}
          closeFu={() => setSelectShow(false)}
          baseFormData={sgBaseFormDataGood}
          topSelectDom={sgTopSelectDomGood}
          columnsTemp={goodsSonTableC(true)}
          oldCheckArr={snaps}
          dataResFu={data => {
            // 需要过滤掉已经有id的-不替换数据，没有id的替换数据 因为数据可能已经在另外一个弹窗更新了
            const nowIds = snaps.map(v => v.id)
            const dataRes: GoodsType[] = data.map((v, i) => {
              v.idTemp = v.id + 'goood'
              // 优先使用已存在的snap数据，否则使用新数据
              const item = nowIds.includes(v.id) ? snaps[i] : v
              return item
            })
            // console.log('--------', dataRes)

            setSnapsFu(dataRes)
          }}
        />
      ) : null}
    </div>
  )
}

export default EditTop
