import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Tabs } from 'antd'
import AddWarehouseModal from '@/pages/Isystem/I1storageSet/components/AddWarehouseModal'
import TableList from '@/pages/Zother/TableList'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import {
  I1_APIdel,
  I1_APIgetList,
  I1_APIwarehouseDel,
  I1_APIwarehouseList,
  I1_APIwarehouseSimpleList
} from '@/store/action/Isystem/I1storageSet'
import { baseFormData } from '@/pages/Zother/data'
import { MessageFu } from '@/utils/message'
import MyPopconfirm from '@/components/MyPopconfirm'
import { storageSetTableC, warehouseSetTableC } from '@/utils/tableData'
import AddPositionModal from './components/AddPositionModal'

const I1baseFormData = baseFormData()
const wareBaseFormData = baseFormData()

function I1storageSet() {
  const [allWarehouseList, setAllWarehouseList] = useState<any[]>([])
  const [warehouseModalVisible, setWarehouseModalVisible] = useState(false)
  const [warehouseEditData, setWarehouseEditData] = useState<any>(null)
  const [positionModalVisible, setPositionModalVisible] = useState(false)
  const [activeTab, setActiveTab] = useState('position')
  // 从仓库拿数据
  const tableInfo = useSelector((state: RootState) => state.I1storageSet.tableInfo)
  const warehouseTableInfo = useSelector(
    (state: RootState) => state.I1storageSet.warehouseTableInfo
  )
  const warehouseOptions = useMemo(() => {
    return allWarehouseList.map((i: any) => ({
      label: i.name,
      value: i.id
    }))
  }, [allWarehouseList])

  const tableListRef = useRef<any>(null)
  const warehouseTableListRef = useRef<any>(null)

  const getListFu = useCallback(() => {
    tableListRef.current?.getListFu?.()
  }, [])

  const getWarehouseListFu = useCallback(() => {
    warehouseTableListRef.current?.getListFu?.()
  }, [])

  const getAllWarehouseListFu = useCallback(async () => {
    const res = await I1_APIwarehouseSimpleList({
      pageNum: 1,
      pageSize: 9999
    })
    setAllWarehouseList(res.data.records)
  }, [])

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

  const delFu = useCallback(
    async (id: string) => {
      const res = await I1_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功')
        getListFu()
      }
    },
    [getListFu]
  )

  const delWarehouseFu = useCallback(
    async (id: string) => {
      const res = await I1_APIwarehouseDel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功')
        getWarehouseListFu()
      }
    },
    [getWarehouseListFu]
  )

  const storyTableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => (
          <>
            <MyPopconfirm txtK='删除' onConfirm={() => delFu(item.id)} />
          </>
        )
      }
    ]
  }, [delFu])

  const warehouseTableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => (
          <>
            <Button
              type='text'
              size='small'
              onClick={() => {
                setActiveTab('position')
                tableListRef.current?.txtChangeFu(item.id, 'storageId')
                setTimeout(() => {
                  tableListRef.current?.getListFu?.()
                }, 200)
              }}
            >
              查看仓格
            </Button>
            <Button
              type='text'
              size='small'
              onClick={() => {
                setWarehouseEditData(item)
                setWarehouseModalVisible(true)
              }}
            >
              编辑
            </Button>
            {item.name !== '默认库房' && (
              <MyPopconfirm txtK='删除' onConfirm={() => delWarehouseFu(item.id)} />
            )}
          </>
        )
      }
    ]
  }, [delWarehouseFu])

  return (
    <div className={styles.I1storageSet}>
      <div className='pageTitle'>库房设置</div>

      <Tabs
        className='storage-tabs'
        activeKey={activeTab}
        onChange={key => setActiveTab(key)}
        items={[
          {
            key: 'position',
            label: '仓格',
            children: (
              <TableList
                ref={tableListRef}
                baseFormData={I1baseFormData}
                getListAPI={I1_APIgetList}
                pageKey='position'
                tableInfo={tableInfo}
                columnsTemp={storageSetTableC}
                rightBtnWidth={180}
                yHeight={539}
                searchDom={[
                  {
                    type: 'select',
                    key: 'storageId',
                    placeholder: `库房名称`,
                    options: warehouseOptions
                  },
                  {
                    type: 'input',
                    key: 'searchKey',
                    placeholder: `请输入仓位编号`
                  }
                ]}
                storyTableListToprr={({ clickSearch }) => (
                  <>
                    <Button type='primary' onClick={clickSearch}>
                      查询
                    </Button>
                    <Button type='primary' onClick={() => setPositionModalVisible(true)}>
                      新增仓格
                    </Button>
                  </>
                )}
                storyTableLastBtn={storyTableLastBtn}
              />
            )
          },
          {
            key: 'warehouse',
            label: '库房',
            children: (
              <>
                <TableList
                  ref={warehouseTableListRef}
                  baseFormData={wareBaseFormData}
                  getListAPI={I1_APIwarehouseList}
                  pageKey='warehouse'
                  tableInfo={warehouseTableInfo}
                  columnsTemp={warehouseSetTableC}
                  yHeight={539}
                  searchDom={[]}
                  rightBtnWidth={88}
                  storyTableListToprr={() => (
                    <>
                      <Button type='primary' onClick={() => setWarehouseModalVisible(true)}>
                        新增库房
                      </Button>
                    </>
                  )}
                  storyTableLastBtn={warehouseTableLastBtn}
                />
              </>
            )
          }
        ]}
      />

      <AddWarehouseModal
        visible={warehouseModalVisible}
        editData={warehouseEditData}
        onCancel={() => {
          setWarehouseModalVisible(false)
          setWarehouseEditData(null)
        }}
        onSuccess={() => {
          setWarehouseModalVisible(false)
          setWarehouseEditData(null)
          getWarehouseListFu()
        }}
      />

      <AddPositionModal
        visible={positionModalVisible}
        positionOptions={warehouseOptions}
        onCancel={() => {
          setPositionModalVisible(false)
        }}
        onSuccess={() => {
          setPositionModalVisible(false)
          getListFu()
        }}
      />
    </div>
  )
}

const MemoI1storageSet = React.memo(I1storageSet)

export default MemoI1storageSet
