import React, { useCallback, useEffect, useState } from 'react'
import Tables from '@/components/Tables'
import HeaderForm from '@/components/Formitem'
import { Card, Modal, message, Button, Space, Upload, Drawer } from 'antd'
import columns from './tableConfig'
import columnsRoi from './tableConfigRoi'
import config from './headerConfig'
import formConfig from './formConfig'
import formConfigRoi from './formConfigRoi'
import { addWorks, deleteWorks, editWorks, editbookParams, getBookList, allBook, setConfigTypeApi, getBooktypeList, setChannelApi, importExcle, downLoadTem, exportExcle, bookRatioList, getBookAll, addRatio, deleteRatio } from '@/services/operating/book'
import { useAjax } from '@/Hook/useAjax'
import { DownloadOutlined, FormOutlined, UploadOutlined } from '@ant-design/icons'
import { RcCustomRequestOptions } from 'antd/lib/upload/interface'
import { useAccess } from 'umi'

const Book: React.FC = () => {
    const [queryFrom, setQueryFrom] = useState<{ bookName?: string, status?: string, platformId?: string, typeId?: number | string, pageNum: number, pageSize: number }>({ pageNum: 1, pageSize: 20 })
    const [visible, setVisible] = useState(false)//弹窗
    const [visibleRoi, setVisibleRoi] = useState(false)// 新增or修改ROI弹窗
    const [roiVisible, setRoiVisible] = useState(false)//书籍卡点roi
    const [title, setTitle] = useState<string>('')//model标题
    const [platform, setPlatform] = useState<any[]>([])//平台信息
    const [bookify, setBookify] = useState<any[]>([])//分类信息
    const [book, setBook] = useState<any[]>([])//所有书
    const [defaultProps, setDefaultProps] = useState<editbookParams | {}>({})//默认值
    const [defaultRoiProps, setDefaultRoiProps] = useState<{ bookId: number, nodePrice: number, effectDay: string, overDay: string, type: string } | {}>({
        bookId: undefined,
        nodePrice: undefined,
        effectDay: undefined,
        overDay: undefined,
        type: undefined
    })//默认值
    const [submit, setSubmit] = useState<() => Promise<any>>()//存放formsubmit
    const callack = useCallback((fnc: () => Promise<any>) => { setSubmit(fnc) }, [])//form回调映射submit
    const [btnLoding, setBtnLoding] = useState<boolean>(false)//按钮loding
    const [btnRoiLoding, setBtnRoiLoding] = useState<boolean>(false)//按钮loding
    const [btnUploadLoding, setBtnUploadLoding] = useState<boolean>(false)//按钮loding
    const addWorksUse = useAjax((params: any) => addWorks(params))//添加请求
    const delData = useAjax((id: number) => deleteWorks(id))//删除请求
    const delDataRoi = useAjax((id: number) => deleteRatio(id))//删除请求
    const editData = useAjax((params: any) => editWorks(params))//编辑请求
    const getBookData = useAjax((params: { bookName?: string, status?: string, platformId?: string, pageNum: number, pageSize: number }) => getBookList(params))//搜索列表
    const allBookUse = useAjax(() => allBook())//添加请求
    const getBookify = useAjax(() => getBooktypeList())//搜索列表
    const setChannel = useAjax((params: { bookId: number, channel: string | null }) => setChannelApi(params))//搜索列表
    const setConfigType = useAjax((params: { bookId: number, typeId: number | null }) => setConfigTypeApi(params))//搜索列表
    const excleImport = useAjax((data: FormDataEntryValue) => importExcle(data), { msgNmae: "导入" })//搜索列表
    const excleExport = useAjax((data: any) => exportExcle(data), { formatResult: true })//导出
    const temDownLoad = useAjax(() => downLoadTem(), { formatResult: true })//模板下载
    const getBookRatioList = useAjax((params: { bookId?: number, pageNum: number, pageSize: number }) => bookRatioList(params))//ROI列表
    const [roiQueryFrom, setRoiQueryFrom] = useState<{ bookId?: number, pageNum: number, pageSize: number }>({ bookId: undefined, pageNum: 1, pageSize: 20 }) // ROI列表参数
    const [ratioData, setRatioData] = useState<any[]>([])//ROI数据
    const [ratio, setRatio] = useState<any>({})//ROI第一条数据数据
    const allBookData = useAjax(() => getBookAll())//添加请求
    const addRatioData = useAjax((params: { bookId: number, nodePrice: number, effectDay: string, overDay: string, type: string }) => addRatio(params))//添加请求
    const access = useAccess()
    /**显示 */
    let showModal = useCallback(() => {
        setTitle('添加')//设置标题
        setVisible(true)//开启弹窗
    }, [])
    /**隐藏 */
    let hideModal = useCallback(() => {
        setDefaultProps({})//清空默认值
        setTitle('')//清空标题
        setVisible(false)//关闭弹窗
    }, [])
    /**ROI修改or新增显示 */
    let showRoiModal = useCallback(() => {
        setVisibleRoi(true)//开启弹窗
    }, [])
    /**ROI修改or新增隐藏 */
    let hideRoiModal = useCallback(() => {
        setDefaultRoiProps({
            bookId: undefined,
            nodePrice: undefined,
            // ratio: undefined,
            effectDay: undefined,
            overDay: undefined,
            type: undefined
        })//清空默认值
        setVisibleRoi(false)//关闭弹窗
    }, [])
    /**ROI显示 */
    let showDrawer = useCallback((bookId: number) => {
        setRatioData([])
        setRoiQueryFrom({ ...roiQueryFrom, bookId })
        setDefaultRoiProps({ ...defaultRoiProps, bookId: bookId })
        setRoiVisible(true)//开启弹窗
    }, [])
    /**ROI隐藏 */
    let hideDrawer = useCallback(() => {
        setRoiVisible(false)
    }, [])
    /** 时间格式化 */
    let formatDate = (cellValue: any) => {
        if (cellValue == null || cellValue == "") return "";
        var date = new Date(cellValue)
        var year = date.getFullYear()
        var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
        var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
        var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        return year + '' + month + '' + day + '' + hours + '' + minutes + '' + seconds
    }
    let downloadFile = (data: any, type: any, fileName: string) => {
        let blob = new Blob([data], { type: `application/${type};charset=utf-8` });
        let downloadElement = document.createElement('a');
        let href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = fileName;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
    }
    /** 导出 */
    let excleExportHandle = useCallback(() => {
        exportExcle(queryFrom).then(res=>{
            downloadFile(res, 'octet-stream', formatDate(new Date()) + ".xlsx")
        })
    }, [queryFrom])
    /** 模板下载 */
    let downloadtem = useCallback(async () => {
        downLoadTem().then(res=>{
            downloadFile(res, 'octet-stream', formatDate(new Date()) + ".xlsx")
        })
    }, [])
    /**头部搜索 */
    let headerSeek = useCallback((bookName: string) => {
        if (bookName) {
            setQueryFrom({ ...queryFrom, bookName, pageNum: 1 })
        } else {
            setQueryFrom({ ...queryFrom, bookName: "", pageNum: 1 })
        }
    }, [queryFrom])
    let headerSeekType = useCallback((status: string) => {
        if (status) { // status
            setQueryFrom({ ...queryFrom, status, pageNum: 1 })
        } else {
            let data = { ...queryFrom }
            delete data.status
            setQueryFrom({ ...queryFrom, pageNum: 1 })
        }
    }, [queryFrom])
    let headerPlatform = useCallback((platformId: string) => {
        if (platformId) {
            setQueryFrom({ ...queryFrom, platformId, pageNum: 1 })
        } else {
            setQueryFrom({ ...queryFrom, platformId: "", pageNum: 1 })
        }
    }, [queryFrom])
    let handleTypeId = useCallback((id: number) => {
        setQueryFrom({ ...queryFrom, typeId: id ? id : "", pageNum: 1 })
    }, [queryFrom])
    /**新增请求 */
    let handleOk = useCallback(() => {
        (submit as () => Promise<any>)().then(res => {
            if (res) {
                setBtnLoding(true);
                let id = (defaultProps as editbookParams).id
                if (id) {
                    let def = (defaultProps as editbookParams)
                    let query = {
                        id,
                        platformId: def?.platformId,
                        status: def?.status,
                        author: def?.author ? def?.author : "",
                        bookName: def?.bookName ? def.bookName : "",
                        protagonist: def.protagonist ? def.protagonist : "",
                        typeId: def.typeId ? def.typeId : "",
                        channel: def.channel ? def.channel : "",
                        wordCount: def.wordCount ? def.wordCount : "",
                        source: def.source ? def.source : "",
                        nodePrice: def.nodePrice ? def.nodePrice : "",
                        ratio: def.ratio ? def.ratio : "",
                        remark: def.remark ? def.remark : ""
                    }
                    editData.run({ ...query, ...res }).then(r => {
                        setBtnLoding(false)
                        getBookData.run(queryFrom)
                        hideModal()
                        message.success('编辑成功', 2)
                    })
                } else {
                    addWorksUse.run(res).then(res => {
                        setBtnLoding(false)
                        getBookData.run(queryFrom)
                        hideModal()
                        message.success('添加成功', 2)
                    })
                }
            }

        })
    }, [submit])

    let handleRoiOk = useCallback(() => {
        (submit as () => Promise<any>)().then(res => {
            if (res) {
                let { nodePrice } = res
                setBtnRoiLoding(true)
                addRatioData.run({ ...res, nodePrice: nodePrice }).then(res => {
                    setBtnRoiLoding(false)
                    getBookData.run(queryFrom)
                    setRoiQueryFrom({ ...roiQueryFrom, pageNum: 1, pageSize: 20 })
                    hideRoiModal()
                    message.success('添加编辑成功', 2)
                })
            }
        })
    }, [submit])

    /**编辑 */
    let edit = useCallback((props: { id: number, platformName: string, remark: string }) => {
        setDefaultProps(props)
        setTitle('编辑')
        setVisible(true)
    }, [title, defaultProps, visible])
    /** roi编辑/修改 */
    let editRoi = useCallback(() => {
        if (Object.keys(ratio).length > 0) {
            let { nodePrice } = ratio
            setDefaultRoiProps({ ...ratio, nodePrice: nodePrice ? Number(nodePrice) : undefined })
        } else {
            setDefaultRoiProps({ ...defaultRoiProps, effectDay: new Date })
        }
        showRoiModal()
    }, [defaultRoiProps, ratio])
    /**删除 */
    let delRoi = useCallback((id: number) => {
        delDataRoi.run(id).then(res => {
            if (res) {
                getBookData.run(queryFrom)
                setRoiQueryFrom({ ...roiQueryFrom, pageNum: 1, pageSize: 20 })
                message.success('删除成功', 2)
            }
        })
    }, [roiQueryFrom])
    /**删除 */
    let del = useCallback((id: number) => {
        delData.run(id).then(res => {
            if (res) {
                getBookData.run(queryFrom)
                message.success('删除成功', 2)
            }
        })
    }, [])

    /**分页 */
    let pageChange = useCallback((page: string | number, pageSize?: string | number) => {
        let query = { pageNum: page as number, pageSize: pageSize as number }
        setQueryFrom({ ...queryFrom, ...query })
        // getBookData.run({ ...queryFrom, ...query })
    }, [queryFrom])
    /**ROI分页 */
    let pageRoiChange = useCallback((page: string | number, pageSize?: string | number) => {
        let query = { pageNum: page as string, pageSize: pageSize as string }
        getBookRatioList.run({ ...roiQueryFrom, ...query }).then(res => {
            let records = res?.records.map((item: any, index: number) => {
                if (page == 1 && index === 0) {
                    setRatio(item)
                    item.index = "ok"
                } else {
                    item.index = "no"
                }
                return item
            })
            setRatioData(records)
        })
    }, [ratio, ratioData])
    //副作用执行
    useEffect(() => {
        allBookUse.run().then(res => {
            res = res?.map((item: any) => {
                item.value = item.id + ""
                item.text = item.platformName
                return item
            })
            setPlatform(res)
        })
        getBookify.run().then(res => {
            res = res?.map((item: any) => {
                item.value = item.id + ""
                item.text = item.name
                return item
            })
            setBookify(res)
        })
        allBookData.run().then(res => {
            res = res?.map((item: any) => {
                item.value = item.id
                item.text = item.bookName
                return item
            })
            setBook(res)
        })
    }, [])
    useEffect(() => {
        if ('bookId' in roiQueryFrom && roiQueryFrom?.bookId) {
            getBookRatioList.run(roiQueryFrom).then(res => {
                setRatio({})
                let { pageNum } = roiQueryFrom
                let records = res?.records.map((item: any, index: number) => {
                    if (pageNum === 1 && index === 0) {
                        setRatio(item)
                        item.index = "ok"
                    } else {
                        item.index = "no"
                    }
                    return item
                })
                setRatioData(records)
            })
        }
    }, [roiQueryFrom])
    useEffect(() => {
        getBookData.run(queryFrom)
    }, [queryFrom])


    const setData = (bookId: number, value: any, type: '1' | "2") => {
        if (type === '1') {
            setChannel.run({ bookId, channel: value }).then(res => {
                getBookData.refresh()
            })
        } else {
            setConfigType.run({ bookId, typeId: value }).then(res => {
                getBookData.refresh()
            })
        }
    }

    return <Card>
        <HeaderForm formConfig={config(showModal, headerSeek, headerSeekType, headerPlatform, platform, access, bookify, handleTypeId)} flow='row' />
        <Space style={{ marginBottom: "10px" }}>
            <Button type='primary' onClick={downloadtem}>模板下载</Button>
            {access['小说导入'] && <Upload
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                action=""
                listType="text"
                onChange={() => { }}
                multiple={true}
                showUploadList={false}
                customRequest={(options: RcCustomRequestOptions) => {
                    setBtnUploadLoding(true)
                    let formData = new FormData();
                    formData.append("file", options.file);
                    excleImport.run(formData).then(res => {
                        getBookData.run(queryFrom)
                        setBtnUploadLoding(false)
                    }).catch(() => {
                        setBtnUploadLoding(false)
                    })
                }}
            ><Button type='primary' icon={<UploadOutlined />} loading={btnUploadLoding} >导入</Button></Upload>}
            <Button type='primary' onClick={excleExportHandle}><DownloadOutlined />导出</Button>
        </Space>

        <Tables
            columns={columns(edit, del, showDrawer, access, setData, bookify)}
            dataSource={getBookData?.data?.records}
            total={getBookData?.data?.total}
            pageChange={pageChange}
            sizeChange={pageChange}
            size="small"
            bordered
            loading={getBookData?.loading}
        />
        <Modal
            title={`${title}书籍`}
            visible={visible}
            okText="确认"
            cancelText="取消"
            onCancel={hideModal}
            onOk={handleOk}
            confirmLoading={btnLoding}
            destroyOnClose={true}
            width={550}
        >
            <HeaderForm formConfig={formConfig(platform, bookify, access)} flow='row' getFormSubmit={callack} defaultProps={defaultProps} labelCol={{ span: 24 }} ew />
        </Modal>
        <Drawer
            title="书籍卡点管理"
            placement="right"
            closable={false}
            onClose={hideDrawer}
            visible={roiVisible}
            width={700}
        >
            <div>
                <Button type='primary' onClick={editRoi} style={{ marginBottom: '10px' }}><FormOutlined />新增/编辑</Button>
                <Tables
                    columns={columnsRoi(delRoi)}
                    dataSource={ratioData}
                    total={getBookRatioList?.data?.total}
                    pageChange={pageRoiChange}
                    sizeChange={pageRoiChange}
                    size="small"
                    bordered
                    loading={getBookRatioList?.loading}
                />
            </div>
        </Drawer>

        <Modal
            title="新增/编辑书籍卡点"
            visible={visibleRoi}
            okText="确认"
            cancelText="取消"
            onCancel={hideRoiModal}
            onOk={handleRoiOk}
            confirmLoading={btnRoiLoding}
            destroyOnClose={true}
            width={350}
        >
            <HeaderForm formConfig={formConfigRoi(book)} flow='row' getFormSubmit={callack} defaultProps={defaultRoiProps} labelCol={{ span: 24 }} ew />
        </Modal>
    </Card>
}

export default Book