import { useAjax } from "@/Hook/useAjax"
import { appAccountConfig, getAppAccountConfig, tencentAdAccountDoAuth, tencentAdAccountToAuth } from "@/services/miniApp/adBack"
import { BetaSchemaForm, PageContainer, ProCard, ProForm, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText } from "@ant-design/pro-components"
import { history, useModel } from "@umijs/max"
import { Button, Divider, message, Space } from "antd"
import { useEffect, useRef, useState } from "react"
import formConfig from "./formConfig"
import { searchToObj } from "@/utils"

function Auth() {
    let { getEnum } = useModel('global')
    let { initialState } = useModel("@@initialState")
    let [key, setKey] = useState<any>()
    let [isEdit, setIsEdit] = useState(false)
    const [readonly, setReadonly] = useState(false);
    const formRef = useRef<ProFormInstance>();
    let TencentAdAccountToAuth = useAjax((params) => tencentAdAccountToAuth(params))//获取授权地址
    let TencentAdAccountDoAuth = useAjax((params) => tencentAdAccountDoAuth(params))//开始授权
    let GetAppAccountConfig = useAjax((params) => getAppAccountConfig(params))//获取回传配置
    let AppAccountConfig = useAjax((params) => appAccountConfig(params))//设置配置
    // 获取广告回传列表
    useEffect(() => {
        // 授权回调
        if (history.location.search) {
            let obj = searchToObj(history.location.search)
            if (obj?.state && obj?.authorization_code) {
                TencentAdAccountDoAuth.run({
                    "state": obj.state,
                    "authorizationCode": obj.authorization_code,
                    "callbackPage": "https://testdistribution.zanxiangwl.com/miniApp/adBack"
                }).then(res => {
                    if (res.code === 200) {
                        message.success("授权成功")
                    }
                   setTimeout(()=>{
                    history.push("/miniApp/adBack")
                   },1000)
                })
            }
        }
        getConfig()
    }, [])
    //获取回传配置
    const getConfig = () => {
        GetAppAccountConfig.run({ appType: initialState?.selectApp?.appType, appId: initialState?.selectApp?.id })
    }
    // 授权
    const auth = () => {
        TencentAdAccountToAuth.run({
            appType: initialState?.selectApp?.appType,
            appId: initialState?.selectApp?.id,
            advertisingChannel: key,
            callbackPage: "https://testdistribution.zanxiangwl.com/miniApp/adBack"
        }).then(res => {
            if (res.code === 200) {
                window.open(res.data)
            }
        })
    }
    // submit
    const submit = async (values: any) => {
        // 遍历 firstBackRate 数组，并将 backRate 转换为字符串
        if (values.firstBackRate) {
            values.firstBackRate = values.firstBackRate.map((item: any) => {
                if (Array.isArray(item.backRate)) {
                    item.backRate = item.backRate.join(":"); // 转换数组为 'min:max' 字符串
                }
                return item;
            });
        }
        if (values.otherBackRate) {
            values.otherBackRate = values.otherBackRate.map((item: any) => {
                if (Array.isArray(item.backRate)) {
                    item.backRate = item.backRate.join(":"); // 转换数组为 'min:max' 字符串
                }
                return item;
            });
        }
        if (values.markUpBackRate) {
            values.markUpBackRate = values.markUpBackRate.map((item: any) => {
                if (Array.isArray(item.backRate)) {
                    item.backRate = item.backRate.join(":"); // 转换数组为 'min:max' 字符串
                }
                return item;
            });
        }
        // 打印转换后的数据
        console.log("处理后的表单数据: ", values);
        AppAccountConfig.run({
            appType: initialState?.selectApp?.appType,
            appId: initialState?.selectApp?.id,
            advertisingChannel: key,
            policyType: 1,
            policyContentOfDefault: values
        }).then(res => {
            if (res.code === 200) {
                message.success("配置成功！")
                GetAppAccountConfig.refresh()
                setIsEdit(false)
            }
        })
    }
    // lock or edit
    const edit = () => {
        setIsEdit(true)
        if (GetAppAccountConfig?.data?.data[key]?.distributorAppAdBackPolicy?.policyContentOfDefault) {
            setTimeout(() => {
                formRef?.current?.setFieldsValue(GetAppAccountConfig?.data?.data[key]?.distributorAppAdBackPolicy?.policyContentOfDefault)
            }, 100)
        }
    }
    return <PageContainer
        tabList={getEnum("ADVERTISING_CHANNEL", "arr")?.map((item: { label: any; key: any }, index: number) => {
            if (index === 0 && !key) {
                setKey(item.key)
            }
            return { tab: item.label, key: item.key }
        })}
        tabProps={{
            type: 'card',
            hideAdd: true,
            onChange: (e) => setKey(e),
        }}
    >
        <ProCard direction="column" ghost gutter={8} loading={GetAppAccountConfig?.loading} >
            <ProCard
                bordered
                title="归因设置"
                actions={
                    !GetAppAccountConfig?.data?.data[key]?.tencentAdAccount && <Space style={{ margin: 20 }}> <Button type="primary" onClick={auth}>授权</Button></Space>
                }
            >
                <div>
                    <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 100, display: 'inline-block', textAlign: 'right' }}>归因方式：</span>
                        <span style={{ color: "#999" }}>数据源ID</span>
                    </div>
                    <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 100, display: 'inline-block', textAlign: 'right' }}>数据源类型：</span>
                        <span style={{ color: "#999" }}>{getEnum("TENCENT_USER_ACTION_TYPE", 'map').get(GetAppAccountConfig?.data?.data[key]?.tencentAdAccount?.userActionSets?.type) || "-"}</span>
                    </div>
                    <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 100, display: 'inline-block', textAlign: 'right' }}>数据源ID：</span>
                        <span style={{ color: "#999" }}>{GetAppAccountConfig?.data?.data[key]?.tencentAdAccount?.userActionSets?.userActionSetId || "-"}</span>
                    </div>
                    <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 100, display: 'inline-block', textAlign: 'right' }}>已授权账号ID：</span>
                        <span style={{ color: "#999" }}> {GetAppAccountConfig?.data?.data[key]?.tencentAdAccount?.userActionSets?.accountId || "-"}</span>
                    </div>
                    {GetAppAccountConfig?.data?.data[key]?.tencentAdAccount && <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 100, display: 'inline-block', textAlign: 'right' }}>授权：</span>
                        <span style={{ color: "#999" }}> <Button type="primary" onClick={auth} size="small" danger>更换授权</Button></span>
                    </div>}
                </div>
            </ProCard>
            <ProCard
                bordered
                title="回传设置"
                tooltip="回传“下单”“付费”两个行为事件，直投小程序链路额外支持“注册”（纯新+染色回流用户进入小程序）事件回传。"
                actions={<Space style={{ margin: 20 }}>
                    <Button type="primary" onClick={edit}>编辑</Button>
                </Space>}
            >
                <div>
                    <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 200, display: 'inline-block', textAlign: 'right' }}>回传类型：</span>
                        <span style={{ color: "#999" }}> {getEnum("CALLBACK_TYPE", "map")?.get(GetAppAccountConfig?.data?.data[key]?.distributorAppAdBackPolicy?.policyContentOfDefault?.backUnit) || "-"}</span>
                    </div>
                    <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 200, display: 'inline-block', textAlign: 'right' }}>VIP回传策略：</span>
                        <span style={{ color: "#999" }}>{getEnum("VIP_CALLBACK", "map")?.get(GetAppAccountConfig?.data?.data[key]?.distributorAppAdBackPolicy?.policyContentOfDefault?.vipOrderBackType) || "-"}</span>
                    </div>
                    <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 200, display: 'inline-block', textAlign: 'right' }}>是否补单：</span>
                        <span style={{ color: "#999" }}>{new Map([true, false].map(key => [key, key ? "是" : "否"])).get(GetAppAccountConfig?.data?.data[key]?.distributorAppAdBackPolicy?.policyContentOfDefault?.markUpOrder) || "-"}</span>
                    </div>
                    <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 200, display: 'inline-block', textAlign: 'right' }}>单用户最大回传订单数：</span>
                        <span style={{ color: "#999" }}>     {GetAppAccountConfig?.data?.data[key]?.distributorAppAdBackPolicy?.policyContentOfDefault?.maxBackCountOfUser || "-"}</span>
                    </div>
                    <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 200, display: 'inline-block', textAlign: 'right' }}>注册充值回传的最大间隔时间：</span>
                        <span style={{ color: "#999" }}>     {GetAppAccountConfig?.data?.data[key]?.distributorAppAdBackPolicy?.policyContentOfDefault?.regPayIntervalTime ? GetAppAccountConfig?.data?.data[key]?.distributorAppAdBackPolicy?.policyContentOfDefault?.regPayIntervalTime + "分钟" : "-"}</span>
                    </div>
                    {GetAppAccountConfig?.data?.data[key]?.distributorAppAdBackPolicy?.policyContentOfDefault && <div style={{ marginBottom: 5 }}>
                        <span style={{ width: 200, display: 'inline-block', textAlign: 'right' }}>更多内容：</span>
                        <span style={{ color: "#999" }}><Button size='small' type='link' onClick={() => { setReadonly(true); edit() }}>查看</Button></span>
                    </div>}
                </div>
            </ProCard>
        </ProCard>
        {/* 回传配置 */}
        <BetaSchemaForm<any>
            title={"回传策略配置"}
            formRef={formRef}
            open={isEdit}
            onOpenChange={(b) => {
                if (!b) {
                    setIsEdit(b)
                    setReadonly(false)
                }
            }}
            layoutType={"ModalForm"}
            labelCol={{ span: 24 }}
            colProps={{ span: 8 }}
            grid={true}
            layout="vertical"
            onFinish={submit}
            columns={formConfig()}
            submitter={readonly ? false : { render: (props, dom) => [...dom] }}
            modalProps={{
                destroyOnClose: true
            }}
        />
    </PageContainer>
}

export default Auth