import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { Col, Divider, FormInstance, message, Modal, Row } from "antd";
import { useRef, useState } from "react";
import ProForm, { ProFormDatePicker, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from "@ant-design/pro-form";
import { handeGetCOUPONDetail, handeGetWECHATAPPSIGNList } from "@/pages/travelMember/service";
import session from "@/utils/session";
import { handleDeleteCOUPON, handleGetCOOPSHOP_RULEList, handleSynchroCOUPONService } from "../../service";
import { uploadPicture } from "@/services/picture";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import ModalFooter from "@/pages/travelMember/scenicSpotConfig/component/modalFooter";
import { handleSetlogSave } from "@/utils/format";
import moment from 'moment'


const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('请上传JPEG、jpg、png格式的图片文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

type DetailProps = {
    showDetail: boolean
    currentRow: any
    currentUser: any
    parentRef?: any
    setShowDetail: any
    setCurrentRow: any
    readonly?: boolean  // 判断是不是只读
}
const CardInfo = ({ showDetail, currentRow, currentUser, parentRef, setShowDetail, setCurrentRow, readonly }: DetailProps) => {
    const { confirm } = Modal;
    // 表单数据
    const ModalFormRef = useRef<FormInstance>();
    // 卡券详情
    const [couponDetail, setCouponDetail] = useState<any>()
    // 小程序列表数据
    const [wxMinList, setWxMinList] = useState<any>([])
    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    // 悬浮框 按钮加载的属性
    const [modalLoading, setModalLoading] = useState<boolean>(false)


    // 预览上传后的图片
    const handlePreview = async () => {
        setFileList(fileList)
        setImagePreviewVisible(true)
    };


    // 删除的方法
    const handleDeleteShopRule = async (id: any) => {
        const req: any = {
            COUPONId: id
        }
        const data = await handleDeleteCOUPON(req)
        console.log('datadatadatadata', data);
        if (data.Result_Code === 100) {
            handleSetlogSave(`删除【${couponDetail?.COUPON_NAME || "-"}(${id})】卡券`)
            message.success(data.Result_Desc)
            if (parentRef) {
                parentRef.current?.reload()
            }
            ModalFormRef?.current?.resetFields()
            setCurrentRow(null)
            setShowDetail(false)
            setFileList([])
        } else {
            message.error(data.Result_Desc)
        }
    }

    // 同步的方法
    const handleSynchroCOUPON = async (res: any) => {
        let req: any = {}
        let minDetail: any = {}
        if (wxMinList && wxMinList.length > 0 && res.WECHATAPPSIGN_ID) {

            let filterObj: any = wxMinList.filter((n: any) => n.WECHATAPPSIGN_ID === res.WECHATAPPSIGN_ID)

            if (filterObj && filterObj.length > 0) {
                let obj = filterObj[0]
                minDetail = {
                    WECHATAPPSIGN_ID: obj.WECHATAPPSIGN_ID,
                    WECHATAPPSIGN_NAME: obj.WECHATAPPSIGN_NAME,
                    WECHATAPP_APPID: obj.WECHATAPP_APPID
                }
            }
        }

        if (currentRow?.COUPON_ID) {
            req = {
                ...couponDetail,
                ...res,
                END_TIME: moment(res.END_TIME).format("YYYY-MM-DD"),
                START_TIME: moment(res.START_TIME).format("YYYY-MM-DD"),
                VALID_END_TIME: moment(res.VALID_END_TIME).format("YYYY-MM-DD"),
                VALID_START_TIME: moment(res.VALID_START_TIME).format("YYYY-MM-DD"),
                UPDATE_STAFF_ID: currentUser?.ID,
                UPDATE_STAFF_NAME: currentUser?.Name,
                UPDATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                COUPON_IMAGEURL: fileList && fileList.length > 0 ? fileList[0].url : "",
                ...minDetail
            }
        } else {
            req = {
                ...res,
                END_TIME: moment(res.END_TIME).format("YYYY-MM-DD"),
                START_TIME: moment(res.START_TIME).format("YYYY-MM-DD"),
                VALID_END_TIME: moment(res.VALID_END_TIME).format("YYYY-MM-DD"),
                VALID_START_TIME: moment(res.VALID_START_TIME).format("YYYY-MM-DD"),
                COUPON_IMAGEURL: fileList && fileList.length > 0 ? fileList[0].url : "",
                CREATE_STAFF_ID: currentUser?.ID,
                CREATE_STAFF_NAME: currentUser?.Name,
                CREATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                ...minDetail
            }
        }

        console.log('reqreqreqreq', req);

        const data = await handleSynchroCOUPONService(req)
        console.log('datadatadatadata', data);
        if (data.Result_Code === 100) {
            handleSetlogSave(`${currentRow?.COUPON_ID ? '更新' : '新增'}【${data.Result_Data.COUPON_NAME}】卡券`)
            message.success(data.Result_Desc)
            ModalFormRef?.current?.resetFields()
            setCurrentRow(undefined)
            setShowDetail(false)
            if (parentRef) {
                parentRef.current?.reload()
            }
        } else {
            message.error(data.Result_Desc)
        }
    }

    return (
        <div>
            <Modal
                open={showDetail}
                className={"CardInformationManager"}
                onCancel={() => {
                    ModalFormRef?.current?.resetFields()
                    setCurrentRow(null)
                    setShowDetail(false)
                    setFileList([])
                }}
                confirmLoading={modalLoading}
                width={1400}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                destroyOnClose
                title={currentRow?.COUPON_ID ? currentRow?.COUPON_NAME : "新增卡券"}
                onOk={() => {
                    ModalFormRef?.current?.validateFields().then(async (res) => {
                        await handleSynchroCOUPON(res)
                    })
                }}
                footer={readonly ? false : <ModalFooter
                    confirmLoading={modalLoading}
                    hideDelete={!currentRow?.COUPON_ID}
                    handleDelete={async () => {
                        await handleDeleteShopRule(currentRow?.COUPON_ID)
                    }}
                    handleCancel={() => {
                        ModalFormRef?.current?.resetFields()
                        setCurrentRow(null)
                        setShowDetail(false)
                        setFileList([])
                    }}
                    handleOK={() => {
                        ModalFormRef?.current?.validateFields().then(async (res) => {
                            setModalLoading(true)
                            await handleSynchroCOUPON(res)
                            setModalLoading(false)
                        })
                    }}

                />}
            >
                <div className="CardInformationManagerModalContent" >
                    <ProForm formRef={ModalFormRef} layout={'horizontal'} submitter={false} labelCol={{ style: { width: 80 } }}
                        request={async () => {
                            if (currentRow?.COUPON_ID) {
                                const req: any = {
                                    COUPONId: currentRow?.COUPON_ID
                                }
                                const data = await handeGetCOUPONDetail(req)
                                setCouponDetail(data)
                                return data
                            } else {
                                return {}
                            }
                        }}

                    >
                        <Divider orientation="left">基本信息</Divider>

                        <Row gutter={8}>
                            <Col span={16}>
                                <ProFormSelect
                                    label={"发券业主"}
                                    name={"OWNERUNIT_ID"}
                                    options={[
                                        { label: currentUser?.OwnerUnitName, value: currentUser?.OwnerUnitId }
                                    ]}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择发券业主'
                                        }
                                    ]}
                                    disabled={currentRow?.COUPON_ID}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"卡券类型"}
                                    name={"COUPON_TYPE"}
                                    request={() => {
                                        const COUPONTYPEList = session.get('COUPONTYPEList')
                                        return COUPONTYPEList
                                    }}
                                    // options={COUPONTYPEList}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择卡券类型'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    label={"卡券名称"}
                                    name={"COUPON_NAME"}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入卡券名称'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    label={"卡券成本"}
                                    name={"COST_AMOUNT"}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"发售即用"}
                                    name={"CATEGORY_RULE_ID"}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择发售类型'
                                        }
                                    ]}
                                    options={[
                                        { label: '是', value: 1 },
                                        { label: '否', value: 0 },
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <Row>
                                    <Col span={12}>
                                        <ProFormText
                                            label={"购买满:"}
                                            name={"WITH_AMOUNT"}
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请输入满足条件'
                                                }
                                            ]}
                                            readonly={readonly}
                                        />
                                    </Col>

                                    <Col span={12}>
                                        <ProFormText
                                            label={"减:"}
                                            name={"USED_AMOUNT"}
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请输入减免金额'
                                                }
                                            ]}
                                            readonly={readonly}
                                        />
                                    </Col>
                                </Row>
                            </Col>
                            <Col span={8}>
                                <ProFormDatePicker
                                    width="lg"
                                    label={"活动时间"}
                                    name={"START_TIME"}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择活动时间'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormDatePicker
                                    width="lg"
                                    label={"截止时间"}
                                    name={"END_TIME"}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择截止时间'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    label={"发放数量"}
                                    name={"COUPON_QUOTA"}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入发放数量'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"消费模式"}
                                    name={"PAY_METHOD"}
                                    options={[
                                        { label: "直接领取", value: 1000 },
                                        { label: "积分兑换", value: 2000 },
                                    ]}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择消费模式'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    label={"积分兑换"}
                                    name={"COUPON_POINT"}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={24}>
                                <ProFormTextArea
                                    label={"使用说明"}
                                    name={"COUPON_INSTRUCTIONS"}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入使用说明'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                        </Row>

                        <Divider orientation="left">基本规则</Divider>
                        <Row gutter={8}>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"适用门店"}
                                    name={"COOPSHOP_RULE_ID"}
                                    request={async () => {
                                        const req: any = {
                                            SearchParameter: {
                                                OWNERUNIT_ID: 911,
                                                ISVALID: 1
                                            },
                                            PageIndex: 1,
                                            PageSize: 999999
                                        }

                                        const data = await handleGetCOOPSHOP_RULEList(req)
                                        let list: any = []
                                        console.log('data', data);
                                        if (data && data.length > 0) {
                                            data.forEach((item: any) => {
                                                list.push({ label: item.COOPSHOP_RULE_NAME, value: item.COOPSHOP_RULE_ID })
                                            })
                                        }
                                        // setCOOPSHOPRULEIDOPTIONS(list)
                                        return list
                                    }}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择适用门店'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"使用期限"}
                                    name={"VALID_TYPE"}
                                    options={[
                                        { label: "固定时间段", value: 1000 },
                                        { label: "固定天数", value: 2000 },
                                    ]}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择使用期限'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <Row gutter={16}>
                                    <Col span={12}>
                                        <ProFormDatePicker
                                            label={"有效日期"}
                                            name={"VALID_START_TIME"}
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请选择有效开始日期'
                                                }
                                            ]}
                                            readonly={readonly}
                                        />
                                    </Col>
                                    <Col span={12}>
                                        <ProFormDatePicker
                                            label={""}
                                            name={"VALID_END_TIME"}
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请选择有效结束日期'
                                                }
                                            ]}
                                            readonly={readonly}
                                        />
                                    </Col>
                                </Row>

                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"允许叠加"}
                                    name={"OVERLAY"}
                                    options={[
                                        { label: "否", value: 0 },
                                        { label: "是", value: 1 },
                                    ]}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择叠加规则'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"限领数量"}
                                    name={"LIMIT_COUNT"}
                                    options={[
                                        { label: "不限量", value: -1 },
                                        { label: "1", value: 1 },
                                        { label: "2", value: 2 },
                                        { label: "3", value: 3 },
                                        { label: "4", value: 4 },
                                        { label: "5", value: 5 },
                                        { label: "6", value: 6 },
                                        { label: "7", value: 7 },
                                        { label: "8", value: 8 },
                                        { label: "9", value: 9 },
                                        { label: "10", value: 10 },
                                    ]}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择限领数量'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"每日限领"}
                                    name={"LIMIT_COUNT_PERDAY"}
                                    options={[
                                        { label: "不限量", value: -1 },
                                        { label: "1", value: 1 },
                                        { label: "2", value: 2 },
                                        { label: "3", value: 3 },
                                        { label: "4", value: 4 },
                                        { label: "5", value: 5 },
                                        { label: "6", value: 6 },
                                        { label: "7", value: 7 },
                                        { label: "8", value: 8 },
                                        { label: "9", value: 9 },
                                        { label: "10", value: 10 },
                                    ]}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择每日限领'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                        </Row>

                        <Divider orientation="left">上架信息</Divider>
                        <Row gutter={8}>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"小程序"}
                                    name={"WECHATAPPSIGN_ID"}
                                    request={async () => {
                                        const req: any = {
                                            SearchParameter: {
                                                OWNERUNIT_ID: 911,
                                            }
                                        }
                                        const data = await handeGetWECHATAPPSIGNList(req)
                                        console.log('datadatadatadata', data);
                                        setWxMinList(data || [])
                                        let list: any = []
                                        if (data && data.length > 0) {
                                            data.forEach((item: any) => {
                                                list.push({ label: item.WECHATAPPSIGN_NAME, value: item.WECHATAPPSIGN_ID })
                                            })
                                        }
                                        return list
                                    }}
                                    // options={[
                                    //     { label: "彩云驿", value: 37 },
                                    //     { label: "彩云驿出行", value: 38 },
                                    // ]}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择小程序'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"是否有效"}
                                    name={"COUPON_ISVALID"}
                                    options={[
                                        { label: "否", value: 0 },
                                        { label: "是", value: 1 },
                                    ]}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择是否有效'
                                        }
                                    ]}
                                    readonly={readonly}
                                />
                            </Col>
                        </Row>

                        <Divider orientation="left">详情介绍</Divider>
                        <Row>
                            <Col span={24}>
                                <ProFormTextArea
                                    label={"详情介绍"}
                                    name={"COUPON_DESC"}
                                    readonly={readonly}
                                />
                            </Col>
                            <Col span={24}>
                                <ProFormTextArea
                                    label={"适用门店"}
                                    name={"COOPSHOP_DESC"}
                                    readonly={readonly}
                                />
                            </Col>
                        </Row>

                        <Divider orientation="left">卡券图标</Divider>
                        <Row>
                            <Col span={24}>
                                <ProFormUploadButton
                                    label={"卡券图标"}
                                    name={"COUPON_IMAGEURL"}
                                    fileList={fileList}
                                    listType="picture-card"
                                    accept="image/*"
                                    fieldProps={{
                                        beforeUpload,
                                        maxCount: 1,
                                        onPreview: handlePreview,
                                        customRequest: async (info) => {
                                            const formData = new FormData();
                                            formData.append('files', info.file);
                                            formData.append('TableType', '1208');
                                            formData.append('ImageName', typeof info.file !== 'string' ? info.file?.name : '');
                                            if (info.filename) {
                                                const success = await uploadPicture(formData)
                                                if (success) {
                                                    const list = [{
                                                        // uid: `${success.ImageId}`, // 注意，这个uid一定不能少，否则上传失败
                                                        name: success.Result_Data.ImageName,
                                                        // status: 'done',
                                                        url: success.Result_Data.ImageUrl, // url 是展示在页面上的绝对链接
                                                        // imgUrl: success.ImagePath  // + success.ImageUrl,
                                                    }]
                                                    setFileList(list)
                                                }
                                            } else {
                                                message.error("您上传的图片不存在.")
                                            }
                                        },
                                        onChange: async (info: any) => {
                                            if (info.file.status === 'removed') {
                                                confirm({
                                                    title: '确认删除该图片吗？',
                                                    icon: <ExclamationCircleOutlined rev={undefined} />,
                                                    async onOk() {
                                                        setFileList([])
                                                    }
                                                });
                                            }
                                        }
                                    }}
                                    disabled={readonly}
                                />
                            </Col>
                        </Row>
                    </ProForm>
                </div>
            </Modal>
        </div>
    )
}

export default connect(({ user, }: ConnectState) => ({
    currentUser: user.currentUser,
}))(CardInfo);
