import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Modal, Table } from 'antd'
import {
  D2_APIareaDelCheck,
  D2_APIareaDels,
  D2_APIareaEdit,
  D2_APIgetAreaList
} from '@/store/action/D2storSet'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { D2checkDuplicate } from './data'

type Props = {
  sId: number
  closeFu: () => void
  succFu: () => void
}

export type D2SlistType = {
  id: string
  name: string
  description: string
  parentId: number
}

function D2Sarea({ sId, closeFu, succFu }: Props) {
  const [list, setList] = useState<D2SlistType[]>([])

  const getListFu = useCallback(async () => {
    const res = await D2_APIgetAreaList(sId)
    if (res.code === 0) {
      setList(res.data)
    }
  }, [sId])

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

  // 点击新增
  const addTable = useCallback(() => {
    setList([...list, { id: `new${Date.now()}`, name: '', description: '', parentId: sId }])
  }, [list, sId])

  // 输入框变化
  const inputChangeFu = useCallback(
    (id: string, val: string, key: 'name' | 'description') => {
      // let valRes = key === 'name' ? val.toUpperCase() : val
      let valRes = val.trim()

      const newList = list.map(v => ({
        ...v,
        [key]: v.id === id ? valRes : v[key]
      }))
      setList(newList)
    },
    [list]
  )

  // 存在数据库中的id为number(true) 新增的为string
  const idFlagFu = useCallback((id: string) => {
    return typeof id === 'number'
  }, [])

  // 把存在数据库中的列表删除id记下来
  const delIds = useRef<string[]>([])

  // 点击删除
  const delByIdFu = useCallback(
    async (id: string) => {
      if (idFlagFu(id)) {
        // 在数据库中了，需要检查
        const res = await D2_APIareaDelCheck(id)
        if (res.code === 0) {
          if (res.data) {
            MessageFu.warning('该区域存在关联库位，无法删除')
          } else {
            // 假删除
            setList(list.filter(v => v.id !== id))
            // id存起来 点提交的时候真删除
            delIds.current.push(id)
          }
        }
      } else {
        // 没有在数据库中，直接删除
        setList(list.filter(v => v.id !== id))
      }
    },
    [idFlagFu, list]
  )

  const columns = useMemo(() => {
    return [
      {
        title: '区域名称',
        render: (item: D2SlistType) => (
          <Input
            placeholder='请输入内容'
            maxLength={30}
            showCount
            value={item.name}
            onChange={e => inputChangeFu(item.id, e.target.value, 'name')}
          />
        )
      },
      {
        title: '区域说明',
        render: (item: D2SlistType) => (
          <Input
            placeholder='请输入内容'
            maxLength={30}
            showCount
            value={item.description}
            onChange={e => inputChangeFu(item.id, e.target.value, 'description')}
          />
        )
      },

      {
        title: '操作',
        width: 100,
        render: (item: D2SlistType) => (
          <MyPopconfirm txtK='删除' onConfirm={() => delByIdFu(item.id)} />
        )
      }
    ]
  }, [delByIdFu, inputChangeFu])

  // 点击提交
  const isOkBtn = useCallback(async () => {
    if (list.some(v => !v.name)) {
      MessageFu.warning('区域名称不能为空')
    } else {
      const res = await D2_APIareaEdit(
        list.map(v => ({
          id: idFlagFu(v.id) ? v.id : null,
          description: v.description,
          name: v.name,
          parentId: Number(v.parentId)
        }))
      )
      if (res.code === 0) {
        if (delIds.current.length) {
          const res2 = await D2_APIareaDels(delIds.current)
          if (res2.code === 0) {
            MessageFu.success('提交成功')
            succFu()
            closeFu()
          }
        } else {
          MessageFu.success('提交成功')
          succFu()
          closeFu()
        }
      }
    }
  }, [closeFu, idFlagFu, list, succFu])

  return (
    <Modal
      wrapClassName={styles.D2Sarea}
      open={true}
      title={
        <div className='D2Stop'>
          区域设置
          <Button type='primary' onClick={addTable}>
            新增
          </Button>
        </div>
      }
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='D2Smain'>
        <Table
          scroll={{ y: 500 }}
          dataSource={list}
          columns={columns}
          rowKey='id'
          pagination={false}
          size='small'
        />

        <div className='D2Sbtn'>
          <Button type='primary' onClick={isOkBtn} disabled={D2checkDuplicate(list).length > 0}>
            提交
          </Button>
          &emsp;
          <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          <p hidden={D2checkDuplicate(list).length === 0}>
            区域名称重复{' '}
            {D2checkDuplicate(list).map(v => (
              <span key={v}>{v}&emsp;</span>
            ))}
          </p>
        </div>
      </div>
    </Modal>
  )
}

const MemoD2Sarea = React.memo(D2Sarea)

export default MemoD2Sarea
