import useNewToken from "@/Hook/useNewToken"
import { App, Button, Card, Col, Input, Row, Select, Tabs } from "antd"
import { useEffect, useState } from "react"
import SearchBox from "../../components/searchBox"
import style from './index.less'
import SelectTag from "./selectTag"
import Right from "./right"
import Left from "./left"
import AddEditSc from "./addEditSc"
import { inject, observer } from "mobx-react"
import { toJS } from "mobx"
import { delMsgTemplateApi, getTemplateListApi, GetTemplateListProps, MEDIATYPE } from "../../API/weMaterial/weMaterial"
import { ExclamationCircleFilled } from '@ant-design/icons';
import { useAjax } from "@/Hook/useAjax"
import { PlusOutlined } from '@ant-design/icons';
import { randomString } from "@/utils/utils"

/**
 * 素材管理
 * @returns 
 */
function WeMaterial(props: { store: any }) {

    const globaStoreData = toJS(props.store.data)

    /***********************/
    const { token } = useNewToken()
    const { message, modal } = App.useApp();
    const [queryForm, setQueryForm] = useState<GetTemplateListProps>({ pageNum: 1, pageSize: 20, isPersonal: '1' })
    const [data, setData] = useState<any[]>([])
    const [selectData, setSelectData] = useState<any>({})
    const [scShow, setScShow] = useState<boolean>(false)  // 素材新增修改控制
    const [copyData, setCopyData] = useState<any>()

    const getTemplateList = useAjax((params) => getTemplateListApi(params))
    const delMsgTemplate = useAjax((params) => delMsgTemplateApi(params))
    /***********************/

    useEffect(() => {
        getList()
    }, [queryForm])

    const getList = () => {
        getTemplateList.run(queryForm).then(res => {
            if (res) {
                if (queryForm.pageNum === 1) {
                    setData(res?.data?.records)
                    if (!(selectData && res?.data?.records?.find((item: any) => item.id == selectData.id))) {
                        setSelectData(res?.data?.records[0])
                    }
                } else {
                    setData(data.concat(res?.data?.records))
                }
            }
        })
    }

    // 下一页
    const loadMoreData = () => {
        setQueryForm({ ...queryForm, pageNum: queryForm.pageNum + 1 })
    }

    // 删除
    const del = (id: number, name: string) => {
        modal.confirm({
            title: '确定删除?',
            icon: <ExclamationCircleFilled />,
            content: `是否确定删除 [${name}] 素材模板`,
            okType: 'danger',
            onOk() {
                delMsgTemplate.run(id).then(res => {
                    message.success('删除成功')
                    let newData = data?.filter(item => item.id !== id)
                    if (selectData.id === id) {
                        setSelectData(newData[0])
                    }
                    setData(newData)
                })
            }
        });
    }

    return <Card
        title={<Tabs
            activeKey={queryForm.isPersonal}
            items={[{
                key: '1',
                label: `个人素材库`,
            }, {
                key: '0',
                label: `公共素材库`,
            }]}
            onChange={(e) => { setQueryForm({ ...queryForm, isPersonal: e as any, pageNum: 1, pageSize: 20 }) }}
        />}
        styles={{ body: { padding: 0 } }}
    >
        <Row className={style.weMaterial}>
            <Col flex='auto' className={style.weMaterial_left} >
                <SearchBox buttons={<>
                    <Button icon={<PlusOutlined />} type='primary' onClick={() => setScShow(true)}>新建素材</Button>
                    {scShow && <AddEditSc
                        value={copyData}
                        visible={scShow}
                        isPersonal={queryForm.isPersonal}
                        onClose={() => {
                            setScShow(false)
                            setCopyData(undefined)
                        }}
                        onChange={() => {
                            if (queryForm.pageNum === 1) {
                                getList()
                            } else {
                                setQueryForm({ ...queryForm, pageNum: 1, pageSize: 20 });
                            }
                            setScShow(false)
                            setCopyData(undefined)
                        }} />}
                </>}>
                    <>
                        <Input.Search placeholder="请输入关键字" allowClear onSearch={(e) => { setQueryForm({ ...queryForm, mediaTitle: e, pageNum: 1, pageSize: 20 }); }} />
                        <Select placeholder='请选择类型' allowClear style={{ width: 80 }} value={queryForm?.mediaType} onChange={(e) => { setQueryForm({ ...queryForm, mediaType: e, pageNum: 1, pageSize: 20 }); }}>
                            {Object.keys(MEDIATYPE).map(key => <Select.Option value={key} key={key}>{MEDIATYPE[key as keyof typeof MEDIATYPE]}</Select.Option>)}
                        </Select>
                        <SelectTag value={queryForm?.mediaTagId} onChange={(id) => { setQueryForm({ ...queryForm, mediaTagId: id, pageNum: 1, pageSize: 20 }); }} />
                    </>
                </SearchBox>
                <Left
                    del={del}
                    copy={(data: any) => {
                        setCopyData({
                            mediaTitle: data?.mediaTitle + '副本' + randomString(true, 2, 5),
                            mediaTagIds: data?.mediaTagIds ? data?.mediaTagIds?.map((id: string, index: number) => ({ tagId: id, tagName: data.mediaTagNames[index] })) : [],
                            mediaContentDTOList: data.corpMediaContentVOList
                        })
                        setScShow(true)
                    }}
                    selectData={selectData}
                    setSelectData={setSelectData}
                    token={token}
                    data={data}
                    onChange={(value) => setSelectData(value)}
                    loading={getTemplateList.loading}
                    loadMore={loadMoreData}
                    setQueryForm={setQueryForm}
                    total={data?.length || 0} />
            </Col>
            {!globaStoreData?.isMobile && <Right
                del={del}
                dataList={data}
                onChange={() => {
                    if (queryForm.pageNum === 1) {
                        getList()
                    } else {
                        setQueryForm({ ...queryForm, pageNum: 1, pageSize: 20 });
                    }
                }}
                token={token}
                value={selectData}
            />}
        </Row>
    </Card>
}

export default inject('store')(observer((props: any) => WeMaterial({ store: props.store.globaStore })))