import { ActionType, BetaSchemaForm, PageContainer, ProFormInstance, ProTable } from "@ant-design/pro-components"
import { columns } from "./tableConfig"
import { useAjax } from "@/Hook/useAjax"
import { useModel } from "@umijs/max"
import { longBookInfoList, longBookInfoChapterContent, longBookInfoBookConfig, longBookInfoConfig, longBookInfoChapterAllList } from "@/services/miniApp/bookManage"
import { useEffect, useMemo, useRef, useState } from "react"
import { Drawer, message } from "antd"
import ReadText from "../components/readText"
import formConfig from "./formConfig"
import ReadBook from "../components/readBook"
const wordCountRanges: any = {
    "": { start: null, end: null }, // 全部
    "0-2": { start: 0, end: 2 * 10000 },
    "2-5": { start: 2 * 10000, end: 5 * 10000 },
    "5-10": { start: 5 * 10000, end: 10 * 10000 },
    "10-20": { start: 10 * 10000, end: 20 * 10000 },
    "20-40": { start: 20 * 10000, end: 40 * 10000 },
    "40-100": { start: 40 * 10000, end: 100 * 10000 },
    "100-150": { start: 100 * 10000, end: 150 * 10000 },
    "150-200": { start: 150 * 10000, end: 200 * 10000 },
    "200-300": { start: 200 * 10000, end: 300 * 10000 },
    "300-0": { start: 300 * 10000, end: null }, // 300万以上
};
type DataItem = {
    name: string;
    state: string;
};
const Page: React.FC = () => {
    let { initialState } = useModel("@@initialState")
    let { state, getLabelAndClassList } = useModel('global')
    let [open, setOpen] = useState<any>(null)//付费配置
    let [editValues, setEditValues] = useState<any>({})
    let paymentType = useState([])
    let [workDirection, setWorkDirection] = useState<any>(null)
    const [openBook, setOpneBook] = useState<any>(null)//阅读小说
    let getList = useAjax((params) => longBookInfoList(params), { type: 'table' })//获取书列表
    let getChapterContent = useAjax((params) => longBookInfoChapterContent(params))//获取章节内容信息
    let getChapterAllList = useAjax((params) => longBookInfoChapterAllList(params))//获取全部章节
    let add = useAjax((params) => longBookInfoBookConfig(params))//新增配置
    let configInfo = useAjax((params) => longBookInfoConfig(params))//获取配置信息
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    // 获取标签和分类
    useEffect(() => {
        getLabelAndClassList({ workDirection })
    }, [workDirection])
    // 接口公共参数
    let publicData = useMemo(() => {
        return {
            miniappId: initialState?.selectApp?.id || "",
            distributorId: initialState?.currentUser?.distributorId,
            appType: initialState?.selectApp?.appType || ""
        }
    }, [initialState?.selectApp, initialState?.currentUser?.distributorId])

    // 看小说列表
    const lookBookList = (params: any) => {
        let { id, pageNum, pageSize } = params
        return getChapterAllList.run({ bookId: id, ...publicData }).then(res => {
            setOpneBook({ list: res.data, ...params })
        })
    }
    // 看小说
    const lookBook = (id: any) => {
        return getChapterContent.run(id).then(res => {
            return res.data
        })
    }
    // 提交表单
    const submit = async (values: any) => {
        if (editValues?.id) {
            values.id = editValues?.id
        }
        if (editValues?.bookId) {
            values.bookId = editValues?.bookId
        }
        add.run({ ...values, ...publicData }).then(res => {
            if (res.code === 200) {
                actionRef?.current?.reload()
                message.success("付费配置成功!")
                closeForm(false)
            }
        })
    }
    // 关闭表单弹窗和重置表单内容
    const closeForm = (b: boolean, values?: any) => {
        if (!b) {
            setEditValues({})
            paymentType[1]([])
            formRef?.current?.resetFields?.()
            setOpen(b)
        } else {
            // 获取书全部章节
            getChapterAllList.run({ bookId: values.bookId, ...publicData }).then(res => {
                if (res.code === 200) {
                    setOpen(b)//弹窗开启
                    if (values) {
                        // 获取书付费配置
                        configInfo.run({ bookId: values.bookId, ...publicData }).then(res => {
                            if (res.code === 200) {
                                let paymentTypeArr = res.data?.paymentType?.map((i: string) => i + '')
                                let data = { ...res.data, paymentType: paymentTypeArr }
                                setEditValues(data)
                                paymentType[1](paymentTypeArr)
                                formRef?.current?.setFieldsValue(data)
                            }
                        })
                    }
                }
            })
        }
    }
    return <PageContainer title={false}
        tabProps={{ type: 'card' }}
    >
        <ProTable<any, any>
            params={publicData}
            actionRef={actionRef}
            headerTitle={"长篇篇小说列表"}
            rowKey={(r) => r.bookId}
            search={{
                labelWidth: 90,
                searchGutter: [10, 15],
            }}
            loading={getChapterAllList?.loading || configInfo?.loading || getList.loading}
            // ghost={true}//去除表格的背景一些配置改变ui
            beforeSearchSubmit={(params) => {//处理搜索数据
                let newParams = Object.entries(params).reduce((acc: any, [key, value]) => {
                    // 过滤掉空值，包括空字符串和 null
                    if (value !== '' && value != null) {
                        acc[key] = value;
                    }
                    if (key === 'wordCount' && value) {
                        let obj = wordCountRanges[value]
                        acc['startWordCount'] = obj.start
                        acc['endWordCount'] = obj.end
                        delete acc[key]
                    }
                    return acc;
                }, {});
                return newParams
            }}
            request={async (params) => {
                return await getList.run(params)
            }}
            columns={columns({ authList: state?.authList, labelList: state.labelList, categoryList: state.categoryList, enumList: state?.enumList, lookBook:lookBookList, closeForm, setWorkDirection })}
        />
        {/* 付费配置 */}
        <BetaSchemaForm<DataItem>
            title={"付费配置"}
            formRef={formRef}
            open={open}
            onOpenChange={(b) => { !b && closeForm(b) }}
            layoutType={"ModalForm"}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
            // grid={true}
            layout='horizontal'
            onFinish={submit}
            columns={formConfig({ enumList: state?.enumList, paymentType, paragraphList: getChapterAllList?.data?.data?.map((item: { chapterInfo: any }) => item.chapterInfo) })}
            loading={add?.loading}
        />
        {/* 阅读小说 */}
        <Drawer
            open={!!openBook}
            placement="right"
            onClose={() => { setOpneBook(null) }}
            footer={null}
            width={'65%'}
            destroyOnClose={true}
            // getContainer={false}
            styles={{ body: { padding: 0 } }}
            closeIcon={false}
            title={<div style={{ fontSize: 20 }}>{openBook?.bookName ? openBook?.bookName : ""}</div>}
        >
            <ReadBook listData={openBook} next={lookBook} />
        </Drawer>
    </PageContainer>

}
export default Page