import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button, Checkbox, InputNumber, Modal, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { D2SlistType } from './D2Sarea'
import { D2_APIaddAdd, D2_APIaddEdit, D2_APIgetAreaList } from '@/store/action/D2storSet'
import TextArea from 'antd/es/input/TextArea'
import { MessageFu } from '@/utils/message'
import { TypeD2listSite } from '../type'
import { cartesianProduct } from './data'

type ArrType = {
  name: string
  num1: null | number
  num2: null | number
  flag: boolean
}

type ArrResType = {
  description: string
  id: number | null
  layer1: number | null
  layer2: number | null
  layer3: number | null
  regionId: number | null
  storageId: number
}

type Props = {
  addObj: TypeD2listSite
  sId: number
  addTableFu: () => void
  closeFu: () => void
}

function D2Sadd({ addObj, sId, addTableFu, closeFu }: Props) {
  useEffect(() => {
    if (addObj.id > 0) {
      setRegionId(addObj.regionId)
      setArr([
        { name: '排架编码', num1: addObj.layer1, num2: null, flag: false },
        { name: '层数编码', num1: addObj.layer2, num2: null, flag: false },
        { name: '层格编码', num1: addObj.layer3, num2: null, flag: false }
      ])
      setDescription(addObj.description)
    }
  }, [addObj])

  // 所有区域的下拉框数据
  const [list, setList] = useState<D2SlistType[]>([])

  const getListFu = useCallback(async () => {
    const res = await D2_APIgetAreaList(sId)
    if (res.code === 0) {
      setList(res.data)
      if (addObj.id < 0 && res.data.length) setRegionId(res.data[0].id)
    }
  }, [addObj.id, sId])

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

  // 区域
  const [regionId, setRegionId] = useState<number | null>(null)

  const [arr, setArr] = useState<ArrType[]>([
    { name: '排架编码', num1: null, num2: null, flag: false },
    { name: '层数编码', num1: null, num2: null, flag: false },
    { name: '层格编码', num1: null, num2: null, flag: false }
  ])

  // 描述
  const [description, setDescription] = useState('')

  // 输入框改变
  const inputChangeFu = useCallback(
    (name: string, key: 'num1' | 'num2' | 'flag', val: number | boolean) => {
      setArr(
        arr.map(v => ({
          ...v,
          [key]: v.name === name ? val : v[key]
        }))
      )
    },
    [arr]
  )

  // 勾选了一个批量
  const isDoTow = useMemo(() => {
    return arr.some(v => v.flag)
  }, [arr])

  // 点击确定
  const isOkBtn = useCallback(async () => {
    let flag = ''
    arr.forEach((v, i) => {
      if (!v.num1) flag = '请输入正整数编码'
      else if (v.flag) {
        // 勾选了批量
        if (!v.num2) flag = '请输入正整数编码'
        else {
          if (v.num2 <= v.num1) flag = `右侧的值需要大于左侧`
          else {
            if (i <= 1) {
              if (v.num2 - v.num1 > 5) flag = `排架/层数右侧值最多只能比左侧大5`
            } else {
              if (v.num2 - v.num1 > 10) flag = `层格右侧值最多只能比左侧大10`
            }
          }
        }
      }
    })
    if (flag) return MessageFu.warning(flag)

    const arrRes: ArrResType[] = []

    let objRes = {} as ArrResType

    if (!arr[0].flag && !arr[1].flag && !arr[2].flag) {
      // 一个都没有勾选
      objRes = {
        description,
        id: addObj.id > 0 ? addObj.id : null,
        layer1: arr[0].num1,
        layer2: arr[1].num1,
        layer3: arr[2].num1,
        regionId,
        storageId: Number(sId)
      }
      arrRes.push(objRes)
    } else {
      // 生成每个元素对应的可能值数组
      const possibleValues = arr.map(element => {
        if (element.flag) {
          const length = element.num2! - element.num1! + 1
          return Array.from({ length }, (_, i) => element.num1! + i)
        } else {
          return [element.num1]
        }
      })

      // 生成组合并转换为目标对象数组
      const combinations = cartesianProduct(possibleValues as any)
      const newArr = combinations.map(([num1, num2, num3]: any) => ({ num1, num2, num3 }))

      newArr.forEach((v: any) => {
        arrRes.push({
          description: '',
          id: null,
          layer1: v.num1,
          layer2: v.num2,
          layer3: v.num3,
          regionId,
          storageId: Number(sId)
        })
      })
    }

    // console.log(123, arrRes)

    // if (1 + 1 === 2) return

    const res = addObj.id > 0 ? await D2_APIaddEdit(objRes) : await D2_APIaddAdd(arrRes)

    if (res.code === 0) {
      MessageFu.success(addObj.id > 0 ? '编辑成功' : '新增成功')
      addTableFu()
      closeFu()
    }
  }, [addObj.id, addTableFu, arr, closeFu, description, regionId, sId])

  return (
    <Modal
      wrapClassName={styles.D2Sarea}
      open={true}
      title={addObj.id > 0 ? '编辑库位' : '新增库位'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='D2Smain'>
        <div className='formBox'>
          <div className='formBox1'>
            <span>* </span>区域：
          </div>
          <div className='formBox2'>
            <Select
              style={{ width: 200 }}
              value={regionId}
              onChange={e => setRegionId(e)}
              options={list.map(v => ({ value: v.id, label: v.name }))}
            />
          </div>
        </div>

        {arr.map((item, index) => (
          <div className='formBox' key={item.name}>
            <div className='formBox1'>
              <span>* </span>
              {item.name}：
            </div>
            <div className='formBox2'>
              <InputNumber
                style={{ width: 140 }}
                min={1}
                max={1000}
                precision={0}
                placeholder='请填入非负整数'
                value={item.num1}
                onChange={e => inputChangeFu(item.name, 'num1', e as number)}
              />

              {item.flag ? (
                <span>
                  {' '}
                  ~{' '}
                  <InputNumber
                    style={{ width: 140 }}
                    min={1}
                    max={1000}
                    precision={0}
                    placeholder='请填入非负整数'
                    value={item.num2}
                    onChange={e => inputChangeFu(item.name, 'num2', e as number)}
                  />
                </span>
              ) : null}
            </div>

            {addObj.id > 0 ? null : (
              <Checkbox
                checked={item.flag}
                onChange={e => inputChangeFu(item.name, 'flag', e.target.checked)}
              >
                批量新增{' '}
                {item.flag ? (
                  <span className='D2Stit'>右侧的值最多比左侧的值大{index <= 1 ? '5' : '10'}</span>
                ) : null}
              </Checkbox>
            )}
          </div>
        ))}

        <div className='formBox formBoxTow' hidden={isDoTow}>
          <div className='formBox1'>库位说明：</div>
          <div className='formBox2'>
            <TextArea
              maxLength={200}
              showCount
              placeholder='请输入内容'
              value={description}
              onChange={e => setDescription(e.target.value)}
            />
          </div>
        </div>

        <div className='D2Sbtn'>
          <Button type='primary' onClick={isOkBtn}>
            提交
          </Button>
          &emsp;
          <MyPopconfirm txtK='取消' onConfirm={closeFu} />
        </div>
      </div>
    </Modal>
  )
}

const MemoD2Sadd = React.memo(D2Sadd)

export default MemoD2Sadd
