import React, { useMemo, useState, useEffect, useCallback } from 'react'
import styles from './index.module.scss'
import { selectObj } from '@/utils/dataChange'
import history from '@/utils/history'
import { MessageFu } from '@/utils/message'
import { authorityFu, tableListAuditBtnFu } from '@/utils/authority'
import TableList from '@/pages/Zother/TableList'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import { API_getGoodsList, API_getGoodsListAll } from '@/store/action/Abench/A3flow'
import { baseFormData } from '@/pages/Zother/data'
import { flowCenterTableC } from '@/utils/tableData'
import { Button, Modal, Radio, Checkbox } from 'antd'
import { exportExcelFile } from '@/utils/xlsxExport'
import tabLeftArr from '@/pages/Layout/data'
import { GI5tableType } from '@/pages/ZgoodsInfo/data'

const ExportModal = ({
  open,
  availableYears,
  onConfirm,
  onCancel
}: {
  open: boolean
  availableYears: (number | string)[]
  onConfirm: (exportType: number, years: (number | string)[]) => void
  onCancel: () => void
}) => {
  const [exportValue, setExportValue] = useState<number>(1)
  const [selectedYears, setSelectedYears] = useState<(number | string)[]>([])

  const onExportTypeChange = (e: any) => {
    setExportValue(e.target.value)
  }

  return (
    <Modal
      title='数据导出'
      open={open}
      onOk={() => onConfirm(exportValue, selectedYears)}
      onCancel={onCancel}
      okText='导出'
      cancelText='取消'
    >
      <span style={{ marginBottom: 16 }}>导出范围：</span>

      <Radio.Group
        onChange={onExportTypeChange}
        value={exportValue}
        options={[
          { value: 1, label: '所有年份' },
          { value: 2, label: '按年份' }
        ]}
      />

      {exportValue === 2 && (
        <div style={{ marginTop: 24 }}>
          <Checkbox.Group
            style={{ flexDirection: 'column', gap: '5px' }}
            options={availableYears.map(year => ({
              label: `${year}年`,
              value: year
            }))}
            value={selectedYears}
            onChange={checkedValues => setSelectedYears(checkedValues as (number | string)[])}
          />
          <div style={{ opacity: '0.5', marginTop: '10px' }}>上述年份为藏品制档日期所在年份</div>
        </div>
      )}
    </Modal>
  )
}
function A3flow() {
  const tableInfo = useSelector((state: RootState) => state.A3flow.tableInfo)
  const [allData, setAllData] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [availableYears, setAvailableYears] = useState<any>([])
  const [list, setList] = useState<any[]>([])
  const showModal = async () => {
    setIsModalOpen(true)
    const res = await API_getGoodsListAll()
    setAllData(res.data.records)
    //获取年份信息
    const years = Array.from(
      new Set(
        res.data.records
          .map((item: any) => item.createTime?.slice(0, 4))
          .filter(Boolean) as string[]
      )
    ).sort((a, b) => Number(b) - Number(a))
    setAvailableYears(years)
  }

  const dataExport = async (exportType: number = 1, years: (number | string)[] = []) => {
    // 根据导出范围筛选数据：
    // exportType === 1：所有年份，不做筛选
    // exportType === 2：按年份，只保留所选年份的数据
    const filteredData =
      exportType === 2 && years.length
        ? allData.filter((item: any) => {
            if (!item.createTime) return false
            const yearStr = item.createTime.slice(0, 4)
            return years.includes(yearStr)
          })
        : allData

    const listData = filteredData.map((item: any) => {
      let applyTypeText = '（空）'
      const obj = list.find((v: any) => v.value === item.type)
      if (obj) applyTypeText = obj.label
      let applyStatusText = '（空）'
      const obj2 = selectObj['藏品入库申请状态'].find((v: any) => v.value === item.status)
      if (obj2) applyStatusText = obj2.label
      return {
        申请类型: applyTypeText,
        申请编号: item.num,
        发起部门: item.deptName,
        发起人: item.creatorName,
        发起日期: item.date,
        申请状态: applyStatusText
      }
    })
    // console.log(listData)
    exportExcelFile(listData, [100, 100, 120, 100, 140, 100], '流程中心数据')
    setIsModalOpen(false)
  }

  useEffect(() => {
    const arr: any[] = []
    tabLeftArr.forEach(v1 => {
      v1.son.forEach(v2 => {
        if (v2.pageType) arr.push({ path: v2.path, value: v2.pageType, label: v2.name, id: v2.id })
      })
    })

    setList(arr)
  }, [])

  const staBtn = useMemo(() => {
    return [
      {
        title: '申请类型',
        render: (item: GI5tableType) => {
          let txt = '（空）'
          const obj = list.find(v => v.value === item.type)
          if (obj) txt = obj.label
          return txt
        }
      }
    ]
  }, [list])

  const A3topSearch = useMemo(
    () => [
      {
        type: 'select',
        key: 'type',
        placeholder: '业务类型',
        options: list
      },
      {
        type: 'input',
        key: 'searchKey',
        placeholder: `请输入申请编号、发起人`
      },
      {
        type: 'time',
        key: ['startTime', 'endTime'],
        placeholder: ['发起日期开始', '发起日期结束']
      },
      {
        type: 'select',
        key: 'status',
        placeholder: '申请状态',
        options: selectObj['藏品入库申请状态']
      }
    ],
    [list]
  )

  // 故事管理/藏品总账定制右侧内容
  const storyTableListToprr = ({
    clickSearch,
    resetSelectFu
  }: {
    clickSearch: () => void
    resetSelectFu: () => void
  }) => {
    return (
      <>
        <Button type='primary' onClick={showModal}>
          数据导出
        </Button>
        <ExportModal
          open={isModalOpen}
          availableYears={availableYears}
          onConfirm={dataExport}
          onCancel={() => setIsModalOpen(false)}
        />
        <Button type='primary' onClick={clickSearch}>
          查询
        </Button>
        <Button onClick={resetSelectFu}>重置</Button>
      </>
    )
  }

  const btnFu = useCallback((pageKey: '3' | '4', obj: any, id: number) => {
    if (obj) {
      authorityFu(obj.id, obj.label, () => history.push(`${obj.path}_edit/${pageKey}/${id}`))
    } else MessageFu.warning('申请类型错误')
  }, [])

  // 故事管理/藏品总账定制右侧操作按钮
  const storyTableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          const obj = list.find(v => v.value === item.type)
          return (
            <>
              <Button size='small' type='text' onClick={() => btnFu('4', obj, item.id)}>
                查看
              </Button>

              {tableListAuditBtnFu(item) ? (
                <Button size='small' type='text' onClick={() => btnFu('3', obj, item.id)}>
                  审批
                </Button>
              ) : null}
            </>
          )
        }
      }
    ]
  }, [btnFu, list])

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

      <TableList
        baseFormData={baseFormData}
        getListAPI={API_getGoodsList}
        pageKey='A3flow'
        tableInfo={tableInfo}
        columnsTemp={flowCenterTableC}
        rightBtnWidth={240}
        leftRowWidth={'20%'}
        yHeight={592}
        staBtn={staBtn}
        searchDom={A3topSearch}
        storyTableListToprr={storyTableListToprr}
        storyTableLastBtn={storyTableLastBtn}
      />
    </div>
  )
}

const MemoA3flow = React.memo(A3flow)

export default MemoA3flow
