import BreadTit from '@/components/BreadTit'
import { RootState } from '@/store'
import { Button, Input, Pagination, Select, Table } from 'antd'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'
import { UnorderedListOutlined, AppstoreOutlined } from '@ant-design/icons'
import classNames from 'classnames'
import ImageLazy from '@/components/ImageLazy'
import history from '@/utils/history'
import { useLocation } from 'react-router-dom'
import dayjs from 'dayjs'
import ExportJsonExcel from 'js-export-excel'
import { getObject2List } from '@/store/action/object2'
import http from '@/utils/http'
import { Empty } from 'antd'
import { obj3InStorage } from '@/utils/dataChange'
import { MessageFu } from '@/utils/message'
const { Option } = Select
export default function Object2() {
  const dispatch = useDispatch()

  // 从仓库中获取藏品编号名称下拉数据
  const options = useSelector((state: RootState) => state.loginStore.selectAll['藏品编号名称'])

  // 从仓库中获取表格数据（图片展示数据）
  const results = useSelector((state: RootState) => state.object2Store.info2)

  // 封装发送请求的函数
  const getList = () => {
    const data = {
      ...tableSelect,
      pageNum: pageNumRef.current,
      searchType: value
    }
    dispatch(getObject2List(data))
    // console.log("------", data);
  }

  // 获取地址栏参数
  const location = useLocation()

  // 如果有参数 根据参数页码在次发送请求
  useEffect(() => {
    const urlParam = location.state || {}
    if (urlParam.k && urlParam.k !== '1')
      setTableSelect({ ...tableSelect, pageNum: Number(urlParam.k) })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location])

  // 筛选表格的数据
  const [tableSelect, setTableSelect] = useState<any>({
    dictNum: null,
    searchKey: '',
    pageSize: 10,
    pageNum: 1
  })

  // 图片页面和列表页面的切换
  const [cutShow, setCutShow] = useState('cutShow1')

  // 当前图片查看或者表格查看数据统一

  const cutShowRef = useRef('1')

  // 进页面如果 d的值为2 切换到表格显示
  useEffect(() => {
    const urlParam = location.state || {}
    if (urlParam.d && urlParam.d === '2') {
      cutShowRef.current = '2'
      window.setTimeout(() => {
        setCutShow('cutShow2')
      }, 20)
    }
  }, [location.state])

  const cutShowFu = useCallback((val: string) => {
    cutShowRef.current = val === 'cutShow1' ? '1' : '2'
    setCutShow(val)
  }, [])

  // 当前页码统一
  const pageNumRef = useRef(1)
  useEffect(() => {
    pageNumRef.current = tableSelect.pageNum
  }, [tableSelect.pageNum])

  // 防止返回的时候发送了2次请求来对应页码
  const getListRef = useRef(-1)

  useEffect(() => {
    clearTimeout(getListRef.current)
    getListRef.current = window.setTimeout(() => {
      getList()
    }, 100)

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tableSelect])

  // 藏品来源下拉框改变
  const handleChange = (val: string) => {
    setTableSelect({ ...tableSelect, dictNum: val, pageNum: 1 })
  }

  // 搜索输入框下拉
  const [value, setValue] = useState('num')
  const valueChangeFu = (val: string) => {
    if (tableSelect.searchKey) {
      // 根据输入框的值重新发送请求
      setTableSelect({ ...tableSelect, searchType: val })
    }

    setValue(val)
  }
  const nameTime = useRef(-1)
  const nameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    clearTimeout(nameTime.current)
    nameTime.current = window.setTimeout(() => {
      setTableSelect({ ...tableSelect, searchKey: e.target.value, pageNum: 1 })
    }, 500)
  }

  // 关于表格的数据
  const paginationChange = (pageNum: number, pageSize: number) => {
    setTableSelect({ ...tableSelect, pageNum, pageSize })
  }

  const columns = useMemo(() => {
    return [
      {
        title: '缩略图',
        render: (item: any) => <ImageLazy width={120} height={70} src={item.thumb} />
      },
      {
        title: '藏品编号名称',
        dataIndex: 'dictNum'
      },
      {
        title: '藏品编号',
        render: (item: any) => (item.num ? item.num : '-')
      },
      {
        title: '藏品名称',
        dataIndex: 'name'
      },
      {
        title: '年代',
        dataIndex: 'dictAge'
      },
      {
        title: '质地',
        dataIndex: 'dictTexture'
      },
      {
        title: '展示状态',
        render: (item: any) => (item.display ? '是' : '否')
      },
      {
        title: '状态',
        dataIndex: 'storageStatusTxt'
      },
      {
        title: '操作',
        render: (item: any) => (
          <>
            <Button
              type='text'
              danger
              onClick={() =>
                history.push(
                  `/object/2/look?k=${pageNumRef.current}&d=${cutShowRef.current}&id=${item.id}`
                )
              }
            >
              查看
            </Button>
          </>
        )
      }
    ]
  }, [])

  // 点击导出
  const deriveFu = useCallback(async () => {
    if (results.list.length === 0) return MessageFu.warning('当前搜索条件没有数据!')
    const name = dayjs(new Date()).format('YYYYMMDDHHmmss')
    const res = await http.post('cms/ledger/pageList', {
      ...tableSelect,
      pageSize: 9999,
      searchType: value
    })
    const sheetData = res.data.records
    sheetData.forEach((v: any) => {
      if (v.size && v.size.length) {
        const sizeArr = v.size.split(',')
        v.sizeRes = `(通长)${sizeArr[0]}cm；(通宽)${sizeArr[1]}cm；(通高)${sizeArr[2]}cm`
      }
      v.qualityRes = '-'
      if (v.quality && v.quality.length) {
        const qualityArr = v.quality.split(',')
        v.qualityRes = qualityArr[0] + qualityArr[1]
      }
      v.namePrimitive = v.namePrimitive ? v.namePrimitive : '-'
      v.num = v.num ? v.num : '-'
      v.ageSpecific = v.ageSpecific ? v.ageSpecific : '-'
      v.repair = v.repair ? v.repair : '-'
      v.checkInYear = v.checkInYear ? v.checkInYear : '-'
      v.author = v.author ? v.author : '-'
      v.vision = v.vision ? v.vision : '-'
      v.onFile = v.onFile ? v.onFile : '-'
      v.description = v.description ? v.description : '-'
      v.remark = v.remark ? v.remark : '-'
      v.storageAncestorName = v.storageAncestor ? obj3InStorage(v.storageAncestor) : '-'
      v.outLocation = v.outLocation ? v.outLocation : '-'
      v.display = v.display ? '是' : '否'
      v.imgName = v.id + '_' + v.name
    })
    const option = {
      fileName: name,
      datas: [
        {
          sheetData,
          sheetName: name,
          sheetFilter: [
            'name',
            'imgName',
            'namePrimitive',
            'dictNum',
            'num',
            'dictAge',
            'dictTexture',
            'ageSpecific',
            'dictGoodType',
            'pcs',
            'dictLevel',
            'sizeRes',
            'sizeSpecific',
            'dictQualityScope',
            'qualityRes',
            'complete',
            'repair',
            'dictCheckInScope',
            'checkInYear',
            'author',
            'vision',
            'onFile',
            'description',
            'remark',
            'storageAncestorName',
            'outLocation',
            'display'
          ],
          sheetHeader: [
            '藏品名称',
            '图片名字',
            '原名',
            '藏品编号名称',
            '藏品编号',
            '年代',
            '文物质地',
            '具体年代',
            '文物类别',
            '实际数量',
            '文物级别',
            '外形尺寸',
            '具体尺寸',
            '质量范围',
            '具体质量',
            '完残程度',
            '保存状态',
            '入藏时间范围',
            '入藏年度',
            '著者',
            '版本',
            '存卷',
            '来源说明',
            '备注',
            '入库位置',
            '出库位置',
            '展示状态'
          ],
          columnWidths: [
            10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
            10, 10, 10, 10
          ]
        }
      ]
    }

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

    if (window.confirm('是否下载所有封面图?')) {
      setDownShow(true)

      try {
        const res: any = await http.get('cms/ledger/download', { timeout: 0 })

        if (res.code === 0) {
          const downloadLink = document.createElement('a')
          downloadLink.href = res.data // 压缩包地址
          downloadLink.download = '藏品总账图片.zip' // 设置下载文件名
          document.body.appendChild(downloadLink)
          downloadLink.click()
          document.body.removeChild(downloadLink)

          setDownShow(false)
        }
      } catch (error) {
        setDownShow(false)
      }
    } else {
    }
  }, [results.list, tableSelect, value])

  const [downShow, setDownShow] = useState(false)

  return (
    <div className={styles.Object2}>
      <div className='breadTit'>
        <BreadTit>
          <div className='breadTitRow active'>藏品总账</div>
        </BreadTit>
      </div>
      <div className='objectSonMain'>
        {/* 顶部搜索和筛选 */}
        <div className='searchBox'>
          <div className='row'>
            <span>藏品编号名称：</span>
            <Select
              placeholder='请选择'
              allowClear
              style={{ width: 150 }}
              value={tableSelect.dictNum}
              onChange={handleChange}
              options={options.map((v: any) => ({
                label: v.name,
                value: v.name
              }))}
            />
          </div>
          <div className='row'>
            <span>搜索：</span>
            <Select style={{ width: 100 }} value={value} onChange={val => valueChangeFu(val)}>
              <Option value='num'>藏品编号</Option>
              <Option value='name'>藏品名称</Option>
              <Option value='age'>藏品年代</Option>
              <Option value='texture'>藏品质地</Option>
              {/* num:藏品编号 */}
            </Select>
            <Input
              maxLength={10}
              style={{ width: 150 }}
              placeholder='请输入'
              allowClear
              onChange={e => nameChange(e)}
            />
          </div>
          <div className='row'>
            <Button onClick={deriveFu}>导出</Button>
          </div>
          <div className='row'>
            <div
              onClick={() => cutShowFu('cutShow1')}
              className={classNames('cutShow', cutShow === 'cutShow1' ? 'active' : '')}
            >
              <AppstoreOutlined />
            </div>
            <div
              onClick={() => cutShowFu('cutShow2')}
              className={classNames('cutShow', 'cutShow2', cutShow === 'cutShow2' ? 'active' : '')}
            >
              <UnorderedListOutlined />
            </div>
          </div>
        </div>
        {/* 图片展示列表 */}
        <div className='imgList' hidden={cutShow !== 'cutShow1'}>
          {results.list.length ? (
            results.list.map((v: any) => (
              <div
                title={v.name + ' ' + v.num}
                onClick={() =>
                  history.push(
                    `/object/2/look?k=${pageNumRef.current}&d=${cutShowRef.current}&id=${v.id}`
                  )
                }
                key={v.id}
                className='imgListRow'
              >
                <ImageLazy noLook={true} width={236} height={200} src={v.thumb} />
                <p>
                  {v.name} {v.num}
                </p>
              </div>
            ))
          ) : (
            <div className='imgListNone'>
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            </div>
          )}
          {}
        </div>

        {/* 表格展示列表 */}
        <div className='tableBox' hidden={cutShow !== 'cutShow2'}>
          <Table
            scroll={{ y: 450 }}
            dataSource={results.list}
            columns={columns}
            rowKey='id'
            pagination={false}
          />
        </div>

        {/* 从表格里面拆出来的分页 */}
        <div className='pageBox' hidden={!results.total}>
          <Pagination
            showQuickJumper
            showSizeChanger
            current={tableSelect.pageNum}
            pageSize={tableSelect.pageSize}
            onChange={paginationChange}
            total={results.total}
          />
          &emsp;共 {results.total} 条数据
        </div>
      </div>

      {/* 下载所有图片的遮罩 */}
      <div className='downImgBox' hidden={!downShow}>
        压缩文件中,请稍等
      </div>
    </div>
  )
}
