import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Button, Cascader, DatePicker, Input, Select } from 'antd'
import { A3flowItemType, A3flowSearchType, IA3flowListParams } from './types'
import {
  DEFAULT_A3FLOW_PARAMS,
  A3FLOW_PARAM_ROWS,
  A3FLOW_TABLE_COLUMNS,
  BUSINESS_DETAIL_PATH_MAP,
  BUSINESS_DELETE_API_MAP
} from './data'
import styles from './index.module.scss'
import MyTable from '@/components/MyTable'
import { RootState } from '@/store'
import { useDispatch, useSelector } from 'react-redux'
import { A3_APIList } from '@/store/action/A3flow'
import ExportJsonExcel from 'js-export-excel'
import dayjs from 'dayjs'
import { MessageFu } from '@/utils/message'
import { businessTypeObj, statusObj } from '@/utils/tableData'
import history, { btnFlagFu } from '@/utils/history'
import MyPopconfirm from '@/components/MyPopconfirm'

const { RangePicker } = DatePicker

function A3flow() {
  // 从仓库拿数据
  const tableInfo = useSelector((state: RootState) => state.A3flow.tableInfo)
  const [formData, setFormData] = useState({ ...DEFAULT_A3FLOW_PARAMS })
  const formDataRef = useRef({ ...DEFAULT_A3FLOW_PARAMS })
  const dispatch = useDispatch()

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

  // 顶部筛选
  const searchDom = useCallback(
    (arr: A3flowSearchType[]) => {
      return arr.map(item => {
        return (
          <div key={item.name}>
            <span>{item.name}：</span>
            {item.type === '输入框' ? (
              <Input
                placeholder='请输入'
                maxLength={30}
                value={formData[item.key]}
                onChange={e => txtChangeFu(e.target.value, item.key)}
              />
            ) : item.type === '下拉框' ? (
              <Select
                options={item.data}
                placeholder='全部'
                allowClear={true}
                value={formData[item.key as 'num'] ? formData[item.key as 'num'] : null}
                onChange={e => setFormData({ ...formData, [item.key]: e })}
              />
            ) : item.type === '日期选择' ? (
              <RangePicker
                format='YYYY-MM-DD'
                allowClear={true}
                onChange={(e, dateStrings) => setFormData({ ...formData, [item.key]: dateStrings })}
              />
            ) : (
              <Cascader
                options={item.data}
                placeholder='全部'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                value={
                  formData[item.key as 'num']
                    ? (formData[item.key as 'num'] as string).split(',')
                    : []
                }
                onChange={e => setFormData({ ...formData, [item.key]: e ? e.join(',') : '' })}
              />
            )}
          </div>
        )
      })
    },
    [formData, txtChangeFu]
  )

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

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

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

  // 封装发送请求的函数
  const getListFu = useCallback(() => {
    const { date, ...rest } = formDataRef.current
    if (Array.isArray(date) && date.length) {
      // @ts-ignore
      rest.startTime = date[0]
      // @ts-ignore
      rest.endTime = date[1]
    }
    dispatch(A3_APIList(rest))
  }, [dispatch])

  const handleExport = async () => {
    const name = '流程管理' + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

    const res = await A3_APIList(
      {
        ...formDataRef.current,
        pageNum: 1,
        pageSize: 99999
      },
      true
    )

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

      const option = {
        fileName: name,
        datas: [
          {
            sheetData: res.data.records.map((v: A3flowItemType) => ({
              ...v,
              type: Reflect.get(businessTypeObj, v.type) || '（空）',
              status: Reflect.get(statusObj, v.status) || '（空）'
            })),
            sheetName: name,
            sheetFilter: ['type', 'num', 'name', 'deptName', 'userName', 'createTime', 'status'],
            sheetHeader: [
              '业务类型',
              '业务编号',
              '申请名称',
              '发起部门',
              '发起人',
              '发起日期',
              '申请状态'
            ],
            columnWidths: [10, 10, 10, 10, 10, 10, 10]
          }
        ]
      }

      const toExcel = new ExportJsonExcel(option) //new
      toExcel.saveExcel() //保存
    }
  }

  // 点击操作按钮
  const tableBtnFu = useCallback((item: A3flowItemType, key: string) => {
    history.push(`/${BUSINESS_DETAIL_PATH_MAP[item.type]}/${key}/${item.id}`)
  }, [])

  // 点击删除
  const delTableFu = useCallback(
    async (item: A3flowItemType) => {
      const res = await BUSINESS_DELETE_API_MAP[item.type]?.(item.id)
      if (res.code === 0) {
        MessageFu.success('删除成功')
        getListFu()
      }
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          let obj = btnFlagFu(item)
          return !Object.values(obj).some(Boolean) ? (
            '-'
          ) : (
            <>
              {obj['编辑'] ? (
                <Button size='small' type='text' onClick={() => tableBtnFu(item, '2')}>
                  编辑
                </Button>
              ) : null}

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

              {obj['删除'] ? <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item)} /> : null}
            </>
          )
        }
      }
    ]
  }, [delTableFu, tableBtnFu])

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

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

  return (
    <div className={styles.A3flow}>
      <div className='pageTitle'>流程管理</div>

      {/* 第一行 */}
      <div className='C1top'>
        <div className='C1topll C1topllAll'>{searchDom(A3FLOW_PARAM_ROWS)}</div>
      </div>

      {/* 第二行 */}
      <div className='C1top C1top2'>
        <Button type='primary' onClick={handleExport}>
          批量导出
        </Button>
        &emsp;
        <Button type='primary' onClick={clickSearch}>
          查询
        </Button>
        &emsp;
        <Button onClick={resetSelectFu}>重置</Button>
      </div>

      {/* 表格 */}
      <MyTable
        yHeight={580}
        list={tableInfo.list}
        columnsTemp={A3FLOW_TABLE_COLUMNS}
        lastBtn={tableLastBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableInfo.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />
    </div>
  )
}

const MemoA3flow = React.memo(A3flow)

export default MemoA3flow
