import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { selectObj } from '@/utils/select'
import { Button, DatePicker, Input, Select } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { C22baseFormData, C22InputKeyType, C22tableBtnFu } from './data'
import { C6_APIgetList, C6_APIrevocation } from '@/store/action/C6edit'
import store, { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import dayjs from 'dayjs'
import { C6tableC, statusObj } from '@/utils/tableData'
import MyTable from '@/components/MyTable'
import classNames from 'classnames'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'
import { FourAPI_revocation } from '@/store/action/FourAll'
import history from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
import C22revamp from './C22revamp'
const { RangePicker } = DatePicker

function C22goodEdit() {
  const dispatch = useDispatch()

  const [formData, setFormData] = useState(C22baseFormData)
  const formDataRef = useRef(C22baseFormData)
  const formDataOldRef = useRef(C22baseFormData)

  useEffect(() => {
    formDataRef.current = formData
  }, [formData])

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(0)

  // 点击搜索
  const clickSearch = useCallback(() => {
    setFormData({ ...formData, pageNum: 1 })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [formData])

  // 时间选择器改变
  const timeChange = useCallback(
    (date: any, dateString: any) => {
      let startTime = ''
      let endTime = ''
      if (dateString[0] && dateString[1]) {
        startTime = dateString[0] + ' 00:00:00'
        endTime = dateString[1] + ' 23:59:59'
      }
      setFormData({ ...formData, startTime, endTime })
    },
    [formData]
  )

  // 封装发送请求的函数
  const getListFu = useCallback(() => {
    formDataOldRef.current = { ...formDataRef.current }
    dispatch(C6_APIgetList(formDataRef.current))
  }, [dispatch])

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: C22InputKeyType) => {
      setFormData({
        ...formData,
        [key]: txt
      })
    },
    [formData]
  )

  // 从仓库中获取数据
  const tableInfo = useSelector((state: RootState) => state.C6edit.tableInfo)

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setFormData(C22baseFormData)
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [])

  // 页码变化
  const paginationChange = useCallback(
    (pageNum: number, pageSize: number) => {
      setFormData({ ...formData, pageNum, pageSize })
      setTimeout(() => {
        setTimeKey(Date.now())
      }, 50)
    },
    [formData]
  )

  // 点击撤回
  const revocationFu = useCallback(
    async (id: number, type: string) => {
      const res = type === 'DJ' ? await FourAPI_revocation('3', id) : await C6_APIrevocation(id)
      if (res.code === 0) {
        MessageFu.success('撤回成功')
        getListFu()
      }
    },
    [getListFu]
  )

  // 点击编辑
  const editBtnFu = useCallback((id: number, type: string, goodId: string) => {
    if (type === 'DJ') history.push(`/register?id=${id}`)
    else setIsEdit({ goodId, id })
  }, [])

  // 点击 查看4 审批3
  const tableBtnFu = useCallback((id: number, key: '3' | '4', type: string) => {
    let url = type === 'DJ' ? `/register_edit/${key}/${id}?mId=350` : `/goodEdit_edit/${key}/${id}`
    history.push(url)
  }, [])

  const lastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        width: 200,
        render: (item: FourTableType) => {
          let obj = C22tableBtnFu(item)
          return !Object.values(obj).some(Boolean) ? (
            '-'
          ) : (
            <>
              {obj['编辑'] ? (
                <Button
                  size='small'
                  type='text'
                  onClick={() => editBtnFu(item.id, item.type, item.goodsIds)}
                >
                  编辑
                </Button>
              ) : null}
              {obj['审批'] ? (
                <Button
                  size='small'
                  type='text'
                  onClick={() => tableBtnFu(item.id, '3', item.type)}
                >
                  审批
                </Button>
              ) : null}

              {obj['查看'] ? (
                <Button
                  size='small'
                  type='text'
                  onClick={() => tableBtnFu(item.id, '4', item.type)}
                >
                  查看
                </Button>
              ) : null}

              {obj['撤回'] ? (
                <MyPopconfirm
                  txtK='撤回'
                  onConfirm={() => revocationFu(item.id, item.type)}
                  Dom={
                    <Button size='small' type='text' danger>
                      撤回
                    </Button>
                  }
                />
              ) : null}
            </>
          )
        }
      }
    ]
  }, [editBtnFu, revocationFu, tableBtnFu])

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

  // 打开侧边栏
  const [cathet, setCathet] = useState(0)

  const startBtn = useMemo(() => {
    return [
      {
        title: '藏品编号',
        render: (item: FourTableType) => {
          return (
            <span
              onClick={() => setCathet(Number(item.goodsIds))}
              className={classNames('D1GtNum', item.id === cathet ? 'D1GtNumAc' : '')}
            >
              {item.goodsNum || '（空）'}
            </span>
          )
        }
      }
    ]
  }, [cathet])

  // 点击导出
  const deriveFu = useCallback(async () => {
    const res = await C6_APIgetList(
      {
        ...formDataOldRef.current,
        pageNum: 1,
        pageSize: 99999
      },
      true
    )

    if (res.code === 0) {
      if (res.data.records.length <= 0) return MessageFu.warning('当前搜索条件没有数据!')

      store.dispatch({
        type: 'layout/exInfo',
        payload: {
          name: '藏品编辑',
          show: true,
          arr: [
            { key: 'goodsNum', txt: '藏品编号' },
            { key: 'goodsName', txt: '藏品名称' },
            { key: 'num', txt: '业务单号' },
            { key: 'typeName', txt: '编辑类型' },
            { key: 'deptName', txt: '发起部门' },
            { key: 'creatorName', txt: '发起人' },
            { key: 'createTime', txt: '发起日期' },
            { key: 'status', txt: '申请状态' }
          ],
          data: res.data.records.map((v: FourTableType) => ({
            ...v,
            status: statusObj[v.status as 1]
          }))
        }
      })
    }
  }, [])

  // 点击藏品编辑的编辑按钮（修改）
  const [isEdit, setIsEdit] = useState({} as { goodId: string; id: number })

  return (
    <div className={styles.C22goodEdit}>
      <div className='pageTitle'>藏品编辑</div>
      <div className='C22top'>
        <div className='C22topll'>
          <div>
            <span>藏品编号：</span>
            <Input
              placeholder='请输入藏品编号'
              maxLength={30}
              value={formData.goodsNum}
              onChange={e => txtChangeFu(e.target.value, 'goodsNum')}
            />
          </div>

          <div>
            <span>藏品名称：</span>
            <Input
              placeholder='请输入藏品名称'
              maxLength={30}
              value={formData.goodsName}
              onChange={e => txtChangeFu(e.target.value, 'goodsName')}
            />
          </div>

          <div>
            <span>业务单号：</span>
            <Input
              placeholder='请输入业务单号'
              maxLength={30}
              value={formData.num}
              onChange={e => txtChangeFu(e.target.value, 'num')}
            />
          </div>
          <div>
            <span>发起部门：</span>
            <Input
              placeholder='请输入发起部门'
              maxLength={30}
              value={formData.deptName}
              onChange={e => txtChangeFu(e.target.value, 'deptName')}
            />
          </div>
          <div>
            <span>发起人：</span>
            <Input
              placeholder='请输入发起人'
              maxLength={30}
              value={formData.userName}
              onChange={e => txtChangeFu(e.target.value, 'userName')}
            />
          </div>
        </div>
        <div className='C22toprr'>
          <Button type='primary' onClick={deriveFu}>
            批量导出
          </Button>
        </div>
      </div>

      <div className='C22top'>
        <div className='C22topll'>
          <div>
            <span>编辑类型：</span>
            <Select
              allowClear={true}
              placeholder='全部'
              style={{ width: 175 }}
              value={formData.type ? formData.type : null}
              onChange={e => setFormData({ ...formData, type: e })}
              options={[
                { value: 'DJ', label: '藏品登记' },
                { value: 'BJ', label: '藏品编辑' }
              ]}
            />
          </div>
          <div>
            <span>发起日期范围：</span>
            <RangePicker
              value={
                formData.startTime ? [dayjs(formData.startTime), dayjs(formData.endTime)] : null
              }
              onChange={timeChange}
            />
          </div>
          <div>
            <span>申请状态：</span>
            <Select
              allowClear={true}
              placeholder='全部'
              style={{ width: 175 }}
              value={formData.status ? formData.status : null}
              onChange={e => setFormData({ ...formData, status: e })}
              options={selectObj['申请状态'].filter(v => v.label !== '待盘点')}
            />
          </div>

          <div>
            <span>选择角色：</span>
            <Select
              allowClear={true}
              style={{ width: 175 }}
              placeholder='全部'
              options={selectObj['角色']}
              // fieldNames={{ value: 'id', label: 'roleName' }}
              value={formData.userType ? formData.userType : null}
              onChange={e => setFormData({ ...formData, userType: e })}
            />
          </div>
        </div>
        <div className='B1toprr'>
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          &emsp;<Button onClick={resetSelectFu}>重置</Button>
        </div>
      </div>

      {/* 表格 */}
      <MyTable
        emptyText={true}
        yHeight={610}
        list={tableInfo.list}
        columnsTemp={C6tableC}
        startBtn={startBtn}
        lastBtn={lastBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableInfo.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />

      {/* 打开侧边栏 */}
      <Y1cathet sId={cathet} menuId={350} closeFu={() => setCathet(0)} />

      {isEdit.id ? (
        <div className='C22revampBox'>
          <C22revamp
            upTableFu={getListFu}
            goodsId={Number(isEdit.goodId)}
            sId={isEdit.id}
            closeFu={() => setIsEdit({} as { goodId: string; id: number })}
            type='编辑'
          />
        </div>
      ) : null}
    </div>
  )
}

const MemoC22goodEdit = React.memo(C22goodEdit)

export default MemoC22goodEdit
