import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { changGetFu, getTokenInfo } from '@/utils/storage'
import history, { aduitBtnRoleFu, resubmitBtnRoleFu } from '@/utils/history'
import { authorityFu } from '@/utils/authority'
import { Button, DatePicker, Input, Select } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { RouterTypeRow } from '@/types'
import { getUserInfoByIdAPI } from '@/store/action/Z1user'
import A1setStock from './A1setStock'
import { A1_APIgetlist } from '@/store/action/A1workbench'
import { A1fromDataBase, A1TableBtnArr } from './data'
import { B1listType } from '../B1ledger/data'
import { statusSelect } from '@/utils/select'
import MyTable from '@/components/MyTable'
import tabLeftArr from '../Layout/data'
import { A1tableC } from '@/utils/tableData'
import { MessageFu } from '@/utils/message'
import A0addGoods from '../A0addGoods'
import MyPopconfirm from '@/components/MyPopconfirm'
import { API_getGoodsInfo } from '@/store/action/B1ledger'
import { B4_APIresubmit } from '@/store/action/B4delete'
const { RangePicker } = DatePicker

const userInfo = getTokenInfo().user || {}

function A1workbench() {
  // 设置常用功能
  const userRolePermissions = useSelector((state: RootState) => state.A0Layout.userRolePermissions)
  const [stockShow, setStockShow] = useState(false)
  const [stockList, setStockList] = useState<RouterTypeRow[]>([])

  const gettStockFu = useCallback(async () => {
    const res = await getUserInfoByIdAPI(userInfo.id)
    if (res.code === 0) {
      // 设置常用功能
      if (res.data.permRtf) {
        setStockList(JSON.parse(res.data.permRtf || '[]'))
      } else setStockList(userRolePermissions)
    }
  }, [userRolePermissions])

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

  const stockListRes = useMemo(() => {
    return stockList.filter(v => v.name !== '工作台' && v.authority)
  }, [stockList])

  // --------------列表表格相关-----------------------

  const dispatch = useDispatch()

  const [formData, setFormData] = useState(A1fromDataBase)

  const getListFu = useCallback(async () => {
    dispatch(A1_APIgetlist(formData))
  }, [dispatch, formData])

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

  // 输入框改变
  const timeRef = useRef(-1)
  const txtChangeFu = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, key: 'num') => {
      clearTimeout(timeRef.current)
      timeRef.current = window.setTimeout(() => {
        setFormData({
          ...formData,
          [key]: e.target.value,
          pageNum: 1
        })
      }, 500)
    },
    [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, pageNum: 1 })
    },
    [formData]
  )

  // 从仓库拿数据
  const tableInfo = useSelector((state: RootState) => state.A1workbench.tableInfo)

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

  // 业务类型拿出来
  const pageType = useMemo(() => {
    const arr: RouterTypeRow[] = []
    tabLeftArr.forEach(v1 => {
      v1.son.forEach(v2 => {
        if (v2.pageType) arr.push(v2)
      })
    })
    return arr
  }, [])

  const dataChange = useCallback(
    (item: B1listType) => {
      const obj = pageType.find(v => v.pageType === item.type)
      return obj
    },
    [pageType]
  )

  // 各按钮的操作逻辑

  // 藏品登记、修改（isEditresubmit）重新提交
  const [editId, setEditId] = useState({ orderId: 0, goodsId: 0, isEditresubmit: false })

  // 藏品删除点击重新提交
  const resubmitFu = useCallback(async (item: B1listType) => {
    // 先拿详情
    const res1 = await API_getGoodsInfo(item.goodIds)
    if (res1.code === 0) {
      const obj = res1.data
      const res2 = await B4_APIresubmit(item.id, obj)
      if (res2.code === 0) {
        MessageFu.success('重新提交成功')
        history.push(`delete_look/3/${item.id}`)
      }
    }
  }, [])

  // 点击查看和审批
  const btnLookAuditFu = useCallback(
    (item: B1listType, pageKey: 2 | 3 | 4) => {
      const pathBase = pageType.find(v => v.pageType === item.type)
      if (pathBase) {
        authorityFu(pathBase.id, `您没有${pathBase.name}页面权限`, () => {
          // 重新提交部分模块和其他逻辑不同
          if (pageKey === 2) {
            // 藏品登记、修改
            if (['DJ', 'XG'].includes(item.type)) {
              setEditId({
                orderId: item.id,
                goodsId: Number(item.goodIds),
                isEditresubmit: item.type === 'XG'
              })
              return
            }
          }

          history.push(`${pathBase.path}_look/${pageKey}/${item.id}`)
        })
      } else MessageFu.warning(`数据type ${item.type} 错误`)
    },
    [pageType]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: B1listType) => {
          return (
            <>
              <Button size='small' type='text' onClick={() => btnLookAuditFu(item, 3)}>
                查看
              </Button>

              {resubmitBtnRoleFu(item) ? (
                item.type === 'SC' ? (
                  <MyPopconfirm
                    txtK='重新提交'
                    onConfirm={() => resubmitFu(item)}
                    Dom={
                      <Button size='small' type='text'>
                        重新提交
                      </Button>
                    }
                  />
                ) : (
                  <Button size='small' type='text' onClick={() => btnLookAuditFu(item, 2)}>
                    重新提交
                  </Button>
                )
              ) : null}

              {aduitBtnRoleFu(item) ? (
                <Button size='small' type='text' onClick={() => btnLookAuditFu(item, 4)}>
                  审批
                </Button>
              ) : null}
            </>
          )
        }
      }
    ]
  }, [btnLookAuditFu, resubmitFu])

  return (
    <div className={styles.A1workbench}>
      <div className='pageTitle'>工作台</div>

      <div className='A1top'>
        <div className='A1top1'>
          <div className='A1tit'>常用功能</div>

          <div className='A1rowBox'>
            {stockListRes.length
              ? stockListRes.map((v, i) => (
                  <div
                    key={i}
                    className='A1row'
                    onClick={() =>
                      authorityFu(v.id, `您没有${v.name}页面权限`, () => {
                        history.push(v.path)
                      })
                    }
                  >
                    <div>
                      <img className='A1rowImg1' src={`./myData/${v.id}.png`} alt='' />
                      <img className='A1rowImg2' src={`./myData/${v.id}Ac.png`} alt='' />
                    </div>
                    {v.name}
                  </div>
                ))
              : null}
          </div>

          <Button className='A1rowBoxBtn' type='text' onClick={() => setStockShow(true)}>
            [设置]
          </Button>
        </div>
        <div className='A1top2'>
          <div className='A1tit'>最近使用</div>

          <div className='A1top2RR'>
            {changGetFu().length ? (
              changGetFu().map((v, i) => (
                <div
                  key={i}
                  className='A1row'
                  onClick={() =>
                    authorityFu(v.id, `您没有${v.name}页面权限`, () => {
                      history.push(v.path)
                    })
                  }
                >
                  <div>
                    <img className='A1rowImg1' src={`./myData/${v.id}.png`} alt='' />
                    <img className='A1rowImg2' src={`./myData/${v.id}Ac.png`} alt='' />
                  </div>
                  {v.name}
                </div>
              ))
            ) : (
              <div className='A1rowNo'>暂无信息</div>
            )}
          </div>
        </div>
      </div>

      <div className='A1table'>
        <div className='A1tabTop'>
          <div>
            {A1TableBtnArr.map(v => (
              <Button
                key={v.key}
                type={v.key === formData.auditType ? 'primary' : 'default'}
                onClick={() => setFormData({ ...formData, auditType: v.key, pageNum: 1 })}
              >
                {v.name}
              </Button>
            ))}
          </div>
          <div>
            <Select
              allowClear
              style={{ width: 200 }}
              placeholder='业务类型'
              options={pageType.map(v => ({ value: v.pageType, label: v.name }))}
              value={formData.type}
              onChange={e => setFormData({ ...formData, type: e, pageNum: 1 })}
            />
            &emsp;
            <Input
              placeholder='业务编号'
              maxLength={30}
              showCount
              allowClear
              onChange={e => txtChangeFu(e, 'num')}
              style={{ width: 200 }}
            />
            &emsp;
            <RangePicker
              placeholder={['发起日期起', '发起日期终']}
              style={{ width: 240 }}
              onChange={timeChange}
            />
            &emsp;
            <Select
              allowClear
              style={{ width: 200 }}
              placeholder='申请状态'
              options={statusSelect}
              value={formData.status}
              onChange={e => setFormData({ ...formData, status: e, pageNum: 1 })}
            />
          </div>
        </div>
        {/* 表格 */}
        <MyTable
          // yHeight={370}
          list={tableInfo.list}
          staBtn={[
            {
              title: '业务类型',
              render: (item: B1listType) => {
                const obj = dataChange(item)

                return obj ? obj.name : '（空）'
              }
            }
          ]}
          columnsTemp={A1tableC}
          lastBtn={tableLastBtn}
          pageNum={formData.pageNum}
          pageSize={formData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
        />
      </div>

      {/* 设置常用功能 */}
      {stockShow ? (
        <A1setStock
          sId={userInfo.id}
          arr={stockList}
          closeFu={() => setStockShow(false)}
          succFu={gettStockFu}
        />
      ) : null}

      {/* 藏品登记重新提交 */}
      {editId.goodsId ? (
        <A0addGoods
          sId={editId.goodsId}
          orderId={editId.orderId}
          closeFu={() => setEditId({ orderId: 0, goodsId: 0, isEditresubmit: false })}
          isEditresubmit={editId.isEditresubmit}
        />
      ) : null}
    </div>
  )
}

const MemoA1workbench = React.memo(A1workbench)

export default MemoA1workbench
