import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import EditTop from '@/pages/Zother/EditTop'
import EditBtn from '@/pages/Zother/EditBtn'
import { InfoProvider, useInfo } from '@/pages/Zother/InfoContext'
import SonGoodsList from '@/pages/Zother/SonGoodsList'
import FileArchive from '@/pages/Zother/FileArchive'
import { getDictFu, selectObj } from '@/utils/dataChange'
import {
  D4_APIgetClueList,
  D4API_downloadFiles,
  D4API_obj
} from '@/store/action/Dmanage/D4resource'
import ResourceDownLog from './ResourceDownLog'
import { Button, Checkbox } from 'antd'
import { useParams } from 'react-router-dom'
import { baseURL } from '@/utils/http'
import { MessageFu } from '@/utils/message'

const rowArr = [
  {
    name: `资源使用`,
    type: 'txt'
  },
  {
    name: `使用日期`,
    must: true,
    key: ['dateStart', 'dateEnd'],
    modeKey: 'dateMode',
    type: 'DatePicker2'
  },
  {
    name: '申请编号',
    must: true,
    key: 'num',
    type: 'Input',
    noNull: true //不允许输入空格
  },
  {
    name: '申请类型',
    key: 'dictIdApply',
    type: 'Cascader',
    options: getDictFu('资源使用')
  },
  {
    name: '事由说明',
    full: true,
    key: 'reason',
    type: 'TextArea'
  },
  {
    name: '备注',
    full: true,
    key: 'remark',
    type: 'TextArea'
  }
]

function D4editContent() {
  const { info, snaps } = useInfo() as { info: any; snaps: any[] }
  const { key } = useParams<any>()
  const [resourceType, setResourceType] = useState<string[]>(
    key === '1' ? selectObj['附件类型'].map((v: any) => v.value) : []
  )
  const canEdit = useMemo(() => ['1', '2'].includes(key), [key])
  const isOk = useMemo(() => info.status === 4, [info.status])
  const [showDownLog, setShowDownLog] = useState(false)

  const handleResourceTypeChange = useCallback((val: string[]) => {
    setResourceType(val)
  }, [])

  const getExtraData = () => {
    return {
      snapType: resourceType.join(',')
    }
  }

  useEffect(() => {
    if (!info.snapType) return
    setResourceType(info.snapType.split(','))
  }, [info.snapType])

  const handleDownloadAll = useCallback(async () => {
    const ids = snaps.map(v => v.id).filter(Boolean)
    if (!ids.length) {
      MessageFu.warning('暂无藏品可下载')
      return
    }
    const res: any = await D4API_downloadFiles(ids)
    if (res?.code === 0 && res?.data) {
      const path = res.data as string
      const fullUrl = path.startsWith('http') ? path : `${baseURL}${path}`
      window.open(fullUrl)
    }
  }, [snaps])

  return (
    <div className={styles.D4edit} id='editBox'>
      <div className='editMain'>
        {/* 顶部 */}
        <EditTop
          pageTxt='申请信息'
          rowArr={rowArr}
          APIobj={D4API_obj}
          fileUpInfo={{ myUrl: 'cms/order/resource/upload', dirCode: 'resource' }}
        />

        <div className='D4editResource'>
          <div>
            <p className='D4editResourceTitle'>资源类型</p>
            <Checkbox.Group
              disabled={!canEdit}
              options={selectObj['附件类型']}
              value={resourceType}
              onChange={handleResourceTypeChange}
            />
          </div>
          {isOk && (
            <div>
              <Button onClick={() => setShowDownLog(true)}>查看下载记录</Button>
              <Button onClick={handleDownloadAll}>下载全部资源</Button>
            </div>
          )}
        </div>

        {/* 藏品清单 */}
        <SonGoodsList
          fileUpInfo={{ myUrl: 'cms/order/resource/son/upload', dirCode: 'resourceGoods' }}
          selectApi={D4_APIgetClueList}
          addShow={false}
          isClueSelect={false}
          btnTxt='选择藏品'
          customTableLastBtn={
            isOk
              ? item => (
                  <Button
                    size='small'
                    type='text'
                    onClick={async () => {
                      const res: any = await D4API_downloadFiles([item.id])
                      if (res?.code === 0 && res?.data) {
                        const path = res.data as string
                        const fullUrl = path.startsWith('http') ? path : `${baseURL}${path}`
                        window.open(fullUrl)
                      }
                    }}
                  >
                    下载资源
                  </Button>
                )
              : undefined
          }
        />

        {/* 附件归档 */}
        <FileArchive />

        {showDownLog && (
          <ResourceDownLog
            ids={snaps.map(v => v.id).filter(Boolean)}
            closeFu={() => setShowDownLog(false)}
          />
        )}

        {/* 底部按钮 */}
        <EditBtn
          path='/resource'
          APIobj={D4API_obj}
          checkListTxt='请添加藏品'
          getExtraData={getExtraData}
        />
      </div>
    </div>
  )
}

function D4edit() {
  return (
    <InfoProvider>
      <D4editContent />
    </InfoProvider>
  )
}

const MemoD4edit = React.memo(D4edit)

export default MemoD4edit
