
import { useRef, useState, useEffect } from 'react';
import { connect } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProFormText,
    ProFormSegmented,
    ProFormSelect,
    ProForm,
    FormControlRender,
    ProFormDependency,
    ProFormSwitch
} from '@ant-design/pro-components';
import { ConfigProvider, Flex, Space, Modal, message, Image, Row, Col, Switch, Form, Typography } from 'antd';
import { addArticle, updateArticle, listSection, GetArticleDetail } from '@/apis/api';
import { Imageprefix } from '@/constants';
import UploadModel from '@/components/Common/upload';
import DragUpload from '@/components/Common/dragupload';
import RichComponent from '@/components/Common/rich';

const selectfieldNames = { label: 'name', value: 'id' };


const PagesMainInformationArticleCreate: React.FC = ({ dispatch, dictModel, openModel, id }: any) => {
    const formRef = useRef<ProFormInstance>();
    const [openPreview, setOpenPreview] = useState(false);
    const [detail, setDetail] = useState<InformationType.article | null>(null)

    useEffect(() => {
        setOpenPreview(openModel.openModal)
    }, [openModel.openModal])

    const [uploadedFilephotoName, setUploadedFilephotoName] = useState<string>('');
    const handleFileUploadedphoto = (filename: string) => {
        setUploadedFilephotoName(filename);
    };

    const [showUplaod, setShowUplaod] = useState<boolean>(false);
    const [uploadedFileDocName, setUploadedFileDocName] = useState<string>('');
    const handleFileUploadedDoc = (filename: string) => {
        setUploadedFileDocName(filename);
    };


    const [richTxt, setRichTxt] = useState<string | number>(''); // 文章内容

    return (
        <>
            <ConfigProvider
                theme={{
                    token: {
                        colorPrimary: '#4FBE70',
                    } , components: {
                        Segmented: {
                            itemSelectedBg: '#19be6e',
                            itemSelectedColor: '#ffffff'
                        },
                    },
                }}
            >
                <Modal
                    open={openPreview}
                    title={id ? '编辑文章' : '添加文章'}
                    centered
                    maskClosable={false}
                    footer={null}
                    destroyOnClose
                    width={1000}
                    onCancel={() => {
                        dispatch({ type: 'openModel/getOpenModal', payload: false })
                    }}
                >
                    <ProForm<InformationType.article>
                        formRef={formRef}
                        request={async () => {
                            if (id) {
                                let res = await GetArticleDetail({ id: id })
                                return res.data;
                            } else {
                                return {
                                    title: '',
                                    cover_img: '',
                                    doc_url: '',
                                    section_id: null,
                                    content: '',
                                    stick_top: 0,
                                    hot: 0,
                                    author: ''
                                }
                            }
                        }}
                        submitter={{
                            searchConfig: {
                                resetText: '取消',
                                submitText: '保存',
                            },
                            render: (_, dom) => { return <Flex justify='flex-end'> <Space>{dom}</Space></Flex> },
                            onReset: () => {
                                setDetail(null)
                                dispatch({ type: 'openModel/getOpenModal', payload: false })
                            }
                        }}
                        onFinish={async (values) => {
                            values.cover_img = uploadedFilephotoName ? uploadedFilephotoName : '';
                            console.log(values)
                            if (id) {
                                values.id = id;
                                let res = await updateArticle(values)
                                message.success('提交成功')
                                dispatch({ type: 'openModel/getOpenModal', payload: false })
                            } else {
                                let res = await addArticle(values)
                                message.success('提交成功')
                                dispatch({ type: 'openModel/getOpenModal', payload: false })
                            }
                        }}
                    >
                        <ProFormText
                            label="文章标题"
                            name="title"
                            placeholder="请输入文章标题"
                            rules={[{ required: true, message: '请输入文章标题' }]}
                        />

                        <Row gutter={[16, 16]}>
                            {
                                detail ?
                                    <Col span={4}>
                                        <UploadModel multiple={false} form_name="cover_img" image_length={1} uploadTxt="上传封面图" image_type={1} onUploadComplete={handleFileUploadedphoto}></UploadModel>
                                    </Col> : <>
                                        <Col span={4}>
                                            <UploadModel multiple={false} form_name="cover_img" image_length={1} uploadTxt="上传封面图" image_type={1} onUploadComplete={handleFileUploadedphoto}></UploadModel>
                                        </Col>
                                    </>
                            }
                            {
                                detail ?
                                    <Col span={4}>
                                        {uploadedFilephotoName ? <Image src={`${Imageprefix}${uploadedFilephotoName}`} style={{ marginBottom: '16px', width: '100px', height: '100px' }}></Image> : <Image src={`${Imageprefix}${detail?.cover_img}`} style={{ marginTop: '16px', width: '200px', height: '200px' }}></Image>}
                                    </Col> : <>
                                        {uploadedFilephotoName ? <Col span={4}> <Image src={`${Imageprefix}${uploadedFilephotoName}`} style={{ marginTop: '32px', width: '100px', height: '100px' }}></Image> </Col> : ''}
                                    </>
                            }
                        </Row>
                        <ProFormSwitch fieldProps={{
                            checked: showUplaod,
                            checkedChildren: '关闭上传文件',
                            unCheckedChildren: '开启上传文件',
                            onChange: (val) => {
                                setShowUplaod(val)
                            }
                        }} />
                        {
                            showUplaod && <>
                                <DragUpload form_name="doc_url" uploadTxt="上传文件" onUploadComplete={handleFileUploadedDoc}></DragUpload>
                                <Typography.Paragraph copyable>链接：{`${Imageprefix}${uploadedFileDocName}`}</Typography.Paragraph>
                            </>
                        }


                        <ProFormSelect
                            showSearch
                            name="section_id"
                            label="栏目/频道"
                            placeholder="请选择栏目/频道"
                            fieldProps={{
                                fieldNames: selectfieldNames
                            }}
                            request={(keyword) =>
                                listSection({ page: 1, pagesize: 100, keyword: keyword.keyWords }).then(res => {
                                    return res.data.sections;
                                })
                            }
                        />
                        <Row gutter={[16, 16]}>
                            <Col span={24}>
                                <Form.Item
                                    name='content'
                                    label="文章内容"
                                    rules={[{ required: true }]}
                                >
                                    <FormControlRender>
                                        {() => {
                                            return (
                                                <ProFormDependency name={['content']} >
                                                    {({ content }, form) => {
                                                        return (
                                                            <RichComponent placeholder="请输入文章内容" defaultValue={content}
                                                                onChange={(value) => {
                                                                    setRichTxt(value)
                                                                    form.formRef.current.setFieldsValue({
                                                                        content: value
                                                                    })
                                                                }}></RichComponent>
                                                        );
                                                    }}
                                                </ProFormDependency>
                                            );
                                        }}
                                    </FormControlRender>
                                </Form.Item>
                            </Col>
                        </Row>
                        <ProFormSegmented
                            name="stick_top"
                            label="是否置顶"
                            request={async () => [
                                { label: '是', value: 1 },
                                { label: '否', value: 2 }
                            ]}
                            rules={[{ required: true, message: '请选择是否置顶' }]}
                        />
                        <ProFormSegmented
                            name="hot"
                            label="成为热门"
                            request={async () => [
                                { label: '普通', value: 1 },
                                { label: '热门推荐', value: 2 }
                            ]}
                            rules={[{ required: true, message: '请选择是否成为热门' }]}
                        />

                        <ProFormText
                            name="author"
                            label="作者"
                            placeholder="请输入作者"
                        />

                    </ProForm>
                </Modal>
            </ConfigProvider>
        </>
    );
};



export default connect(({ dictModel, openModel }: any) => ({
    dictModel, openModel
}))(PagesMainInformationArticleCreate);