import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import styles from './index.module.scss'
import EditTop from '@/pages/Zother/EditTop'
import EditBtn from '@/pages/Zother/EditBtn'
import { InfoProvider, useInfo } from '@/pages/Zother/InfoContext'
import { F1_APIgetStorageList } from '@/store/action/Fstorehouse/F1inStorage'
import { Button, Select, Space } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import FileArchive from '@/pages/Zother/FileArchive'
import { F5API_obj } from '@/store/action/Fstorehouse/F5staff'
import { getDictFu } from '@/utils/dataChange'
import encodeStr, { getStaffDisplayPapers, getStaffDisplayPhone } from '@/utils/pass'
import MyTable from '@/components/MyTable'
import { StaffModal } from './components'

const rowArr = [
  {
    name: `人员出入库`,
    type: 'txt'
  },
  {
    name: `出入日期`,
    must: true,
    key: 'date',
    type: 'DatePicker'
  },
  {
    name: '申请编号',
    must: true,
    key: 'num',
    type: 'Input',
    noNull: true //不允许输入空格
  },
  {
    name: '申请类型',
    key: 'dictIdApply',
    type: 'Cascader',
    options: getDictFu('人员出入库')
  },
  {
    name: '事由说明',
    full: true,
    key: 'reason',
    type: 'TextArea'
  },
  {
    name: '备注',
    full: true,
    key: 'remark',
    type: 'TextArea'
  }
]

function F5editContent() {
  const { info, setSnapsFu, snaps } = useInfo() as {
    info: any
    setSnapsFu: (snaps: any[]) => void
    snaps: any[]
  }
  const { key } = useParams<any>()
  const canEdit = useMemo(() => ['1', '2'].includes(key), [key])
  const [selectStorage, setSelectStorage] = useState<any>(null)
  const [allWarehouseList, setAllWarehouseList] = useState<any[]>([])
  const warehouseOptions = useMemo(() => {
    return allWarehouseList.map((i: any) => ({
      label: i.name,
      value: i.id,
      managerUser: i.managerUser
    }))
  }, [allWarehouseList])

  const handleStorageChange = useCallback(async (value: string, option: any) => {
    setSelectStorage(option)
  }, [])

  const getStorageList = useCallback(async () => {
    const res = await F1_APIgetStorageList()
    setAllWarehouseList(res.data.records)
  }, [])

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

  const [staffModalOpen, setStaffModalOpen] = useState(false)
  const [editingStaff, setEditingStaff] = useState<any>(null)
  const staffList = snaps

  const openAddStaff = useCallback(() => {
    setEditingStaff(null)
    setStaffModalOpen(true)
  }, [])

  const openEditStaff = useCallback((item: any) => {
    setEditingStaff(item)
    setStaffModalOpen(true)
  }, [])

  const handleStaffModalOk = useCallback(
    (values: { name: string; papers: string; phone: string; unit: string }) => {
      const staffItem = {
        name: values.name,
        papers: encodeStr(values.papers),
        phone: encodeStr(values.phone),
        unit: values.unit
      }
      if (editingStaff) {
        const next = staffList.map((v: any) =>
          (v.idTemp ?? v.id) === (editingStaff.idTemp ?? editingStaff.id)
            ? { ...v, ...staffItem }
            : v
        )
        setSnapsFu(next as any)
      } else {
        setSnapsFu([...staffList, { ...staffItem, idTemp: Date.now() }] as any)
      }
      setStaffModalOpen(false)
    },
    [editingStaff, staffList, setSnapsFu]
  )

  const handleDeleteStaff = useCallback(
    (item: any) => {
      setSnapsFu(
        staffList.filter((v: any) => (v.idTemp ?? v.id) !== (item.idTemp ?? item.id)) as any
      )
    },
    [staffList, setSnapsFu]
  )

  const verifyBackFu = (info: any) => {
    if (!selectStorage) return { flag: true, txt: '请选择相关库房' }
    if (!staffList.length) return { flag: true, txt: '请添加人员' }
    return { flag: false, txt: '' }
  }

  const getExtraData = (info: any, snaps: any[]) => {
    const snapsArr = snaps.map((v: any) => ({
      orderId: info.id,
      snap: JSON.stringify({
        name: v.name,
        papers: v.papers,
        phone: v.phone,
        unit: v.unit
      })
    }))
    return {
      storageId: selectStorage?.value ?? undefined,
      snaps: snapsArr
    }
  }

  useEffect(() => {
    if (!info?.storageId || !allWarehouseList.length) return
    const opt = warehouseOptions.find((o: any) => o.value === info.storageId)
    if (opt) {
      setSelectStorage(opt)
    }
  }, [info?.storageId, allWarehouseList.length, warehouseOptions])

  return (
    <div className={styles.F5edit} id='editBox'>
      <div className='editMain'>
        <EditTop
          pageTxt='人员出入库'
          rowArr={rowArr}
          APIobj={F5API_obj}
          fileUpInfo={{ myUrl: 'cms/orderSite/user/upload', dirCode: 'staff' }}
        />

        <div className='F5editStorage'>
          <p className='F5editStorageTitle'>*相关库房</p>
          <Select
            style={{ width: 200 }}
            options={warehouseOptions}
            placeholder='请选择'
            value={selectStorage?.value}
            onChange={handleStorageChange}
            disabled={!canEdit}
          />
        </div>

        <div className='F5editStorage' style={{ flexDirection: 'column' }}>
          <div className='F5editStorageTitleBox'>
            <p className='F5editStorageTitle'>人员信息</p>
            <Button type='primary' onClick={openAddStaff} disabled={!canEdit}>
              新增人员
            </Button>
          </div>
          <MyTable
            classKey='F5staff'
            list={staffList}
            columnsTemp={[
              ['txt', '姓名', 'name'],
              ['custom', '证件信息', (item: any) => getStaffDisplayPapers(item.papers)],
              ['custom', '联系方式', (item: any) => getStaffDisplayPhone(item.phone)],
              ['txt', '所在单位', 'unit']
            ]}
            lastBtn={
              canEdit
                ? [
                    {
                      title: '操作',
                      render: (item: any) => (
                        <Space>
                          <Button size='small' type='link' onClick={() => openEditStaff(item)}>
                            编辑
                          </Button>
                          <MyPopconfirm
                            txtK='删除'
                            onConfirm={() => handleDeleteStaff(item)}
                            Dom={
                              <Button size='small' type='link' danger>
                                删除
                              </Button>
                            }
                          />
                        </Space>
                      )
                    }
                  ]
                : []
            }
            pagingInfo={false}
            rowKey='idTemp'
          />
        </div>

        <StaffModal
          open={staffModalOpen}
          editingStaff={editingStaff}
          onOk={handleStaffModalOk}
          onCancel={() => {
            setStaffModalOpen(false)
            setEditingStaff(null)
          }}
        />

        {/* 附件归档 */}
        <FileArchive />

        {/* 底部按钮 */}
        <EditBtn
          path='/staff'
          APIobj={F5API_obj}
          checkListTxt='请添加人员'
          verifyBackFu={verifyBackFu}
          getExtraData={getExtraData}
        />
      </div>
    </div>
  )
}

function F5edit() {
  return (
    <InfoProvider>
      <F5editContent />
    </InfoProvider>
  )
}

const MemoF5edit = React.memo(F5edit)

export default MemoF5edit
