import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button, InputNumber, Modal } from 'antd'
import MyTable from '@/components/MyTable'
import MyPopconfirm from '@/components/MyPopconfirm'
import { C1GoodType } from '@/pages/A3_ledger/C1ledger/type'
import { D4_APIauditSnap, D4_APIcheckSiteNum } from '@/store/action/D4impStor'
import { MessageFu } from '@/utils/message'
import history from '@/utils/history'

// 2个数字数组比较是否有重复的值
const findFirstCommon = (a: number[], b: number[]) => a.find(item => new Set(b).has(item)) || null

export type D4checkArrType = {
  goodsId: number // 文物id
  id: number //自己的id
  orderId: number // 订单id
  siteNum: number // 库位号
  snap: string //快照数据
}

type Props = {
  closeFu: () => void
  listTemp: D4checkArrType[]
  storageId: number
  waiSiteNumArr: number[]
  type: '入库' | '移库'
}

function D4check({ closeFu, listTemp, storageId, waiSiteNumArr, type }: Props) {
  const [tableList, setTableList] = useState<C1GoodType[]>([])

  useEffect(() => {
    setTableList(listTemp.map(v => JSON.parse(v.snap)))
  }, [listTemp])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: (
          <div>
            <span style={{ color: '#ff4d4f' }}> * </span>藏品分库号
          </div>
        ),
        render: (item: any) => (
          <InputNumber
            style={{ width: 200 }}
            min={1}
            max={99999999}
            precision={0}
            value={item.siteNum}
            onChange={e =>
              setTableList(
                tableList.map(v => ({
                  ...v,
                  siteNum: v.id === item.id ? e : v.siteNum
                }))
              )
            }
            placeholder='请输入'
          />
        )
      },
      {
        title: '名称',
        render: (item: any) => item.name || '（空）'
      }
    ]
  }, [tableList])

  // 点击确定
  const btnOk = useCallback(async () => {
    const siteNums = tableList.map(v => v.siteNum!)

    const errNum = findFirstCommon(siteNums, waiSiteNumArr)

    if (errNum) return MessageFu.warning(`分库号${errNum}重复`)

    const res1 = await D4_APIcheckSiteNum(
      {
        siteNums,
        storageId
      },
      type
    )
    if (res1.code === 0) {
      if (res1.data.length) MessageFu.warning(`分库号${res1.data}重复`)
      else {
        const snaps: D4checkArrType[] = []
        listTemp.forEach((v, i) => {
          const obj22 = tableList[i]

          snaps.push({
            goodsId: v.goodsId,
            id: v.id,
            orderId: v.orderId,
            siteNum: obj22.siteNum!,
            snap: JSON.stringify(obj22)
          })
        })

        const obj = {
          id: listTemp[0].orderId,
          snaps
        }

        const res2 = await D4_APIauditSnap(obj)
        if (res2.code === 0) {
          closeFu()
          MessageFu.success('审批成功')
          // 跳详情页
          history.push(`/impStor_edit/4/${listTemp[0].orderId}`)
        }
      }
    }
  }, [closeFu, listTemp, storageId, tableList, type, waiSiteNumArr])

  return (
    <Modal
      wrapClassName={styles.D4check}
      destroyOnClose
      open={true}
      title='以下分库号已存在，为保障分库号的唯一性，需重新填写：'
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='D4Cmain'>
        {/* 表格 */}
        <MyTable
          classKey='D4check'
          list={tableList}
          columnsTemp={[
            ['txt', '藏品编号', 'num'],
            ['txt', '编号类型', 'numName']
          ]}
          lastBtn={tableLastBtn}
          pagingInfo={false}
        />
      </div>

      <div className='D4Cbtn'>
        <Button type='primary' disabled={tableList.some(v => !v.siteNum)} onClick={btnOk}>
          提交
        </Button>
        &emsp;
        <MyPopconfirm txtK='取消' onConfirm={closeFu} />
      </div>
    </Modal>
  )
}

const MemoD4check = React.memo(D4check)

export default MemoD4check
