import { Form, message, Modal, Select, Transfer } from "antd"
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import { getAccountAllListApi } from "@/services/launchAdq/adAuthorize"
import { useAjax } from "@/Hook/useAjax"
import { authAccountAssetsGroupAccountApi, batchAuthAccountAssetsGroupAccountApi, getConversionInfoApi } from "@/services/adqV3/global"
import { GOAL_ROAS_ENUM, OPTIMIZATIONGOAL_ENUM } from "../../tencentAdPutIn/const"
import { useDebounce } from "ahooks"

interface Props {
    authType: 'material' | 'conversion'
    // 主账户
    authMainAccountId: string
    // 主账户ID
    accountAssetsGroupId: number
    // 已选账户
    selectedAccountIdList: string[]
    // 主体名称
    corporationName: string,
    // 主体编号
    corporationLicence: string
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}
const AddSubAccount: React.FC<Props> = ({ authType, authMainAccountId, accountAssetsGroupId, selectedAccountIdList = [], corporationName, corporationLicence, visible, onClose, onChange }) => {

    /************************************/
    const [form] = Form.useForm()
    const [tableData, setTableData] = useState<any[]>([])//table数据
    const [value, setValue] = useState<string>();
    const keywords = useDebounce(value, { wait: 300 });

    const getAccountAllList = useAjax(() => getAccountAllListApi())
    const authAccountAssetsGroupAccount = useAjax((params) => authAccountAssetsGroupAccountApi(params))
    const batchAuthAccountAssetsGroupAccount = useAjax((params) => batchAuthAccountAssetsGroupAccountApi(params))
    const getConversionInfo = useAjax((params) => getConversionInfoApi(params))
    /************************************/

    useEffect(() => {
        if (authType === 'conversion') {
            getConversionInfo.run({ accountId: authMainAccountId, pageNum: 1, pageSize: 20, keywords }).then(res => {
                setTableData(res?.records?.filter((item: { ownerId: string }) => item.ownerId === authMainAccountId)?.map((item: { conversionName: string; optimizationGoal: string; deepBehaviorOptimizationGoal: string; deepWorthOptimizationGoal: string, conversionId: number, createSourceType: string }) => {
                    const deepGoal = item?.deepBehaviorOptimizationGoal ? OPTIMIZATIONGOAL_ENUM[item?.deepBehaviorOptimizationGoal as keyof typeof OPTIMIZATIONGOAL_ENUM] : item?.deepWorthOptimizationGoal ? GOAL_ROAS_ENUM[item?.deepWorthOptimizationGoal as keyof typeof GOAL_ROAS_ENUM] : null
                    const cType = item?.createSourceType === 'SELF_CREATED' ? '自建转化' : item?.createSourceType === 'PLATFORM' ? '平台类转化' : ''
                    return {
                        label: item.conversionName + `（优化目标：${OPTIMIZATIONGOAL_ENUM[item?.optimizationGoal as keyof typeof OPTIMIZATIONGOAL_ENUM]}${deepGoal ? '/深度优化目标：' + deepGoal : ''}/上报类型：${cType}）`, //+ '_' + (item?.deepBehaviorOptimizationGoal ? OPTIMIZATIONGOAL_ENUM[item?.deepBehaviorOptimizationGoal as keyof typeof OPTIMIZATIONGOAL_ENUM] : item?.deepWorthOptimizationGoal ? GOAL_ROAS_ENUM[item?.deepWorthOptimizationGoal as keyof typeof GOAL_ROAS_ENUM] : null) + '_' + item?.createSourceType === 'SELF_CREATED' ? '自建转化' : item?.createSourceType === 'PLATFORM' ? '平台类转化' : '',
                        value: item.conversionId + "$" + item.conversionName,
                        name: item.conversionName
                    }
                }) || [])
            })
        }
    }, [authType, keywords])
    

    const handleSearch = (keywords?: string) => {
        setValue(keywords)
    };

    useEffect(() => {
        getAccountAllList.run()
    }, [])

    const handleOk = () => {
        form.validateFields().then(valid => {
            console.log(valid)
            let params = { ...valid, accountAssetsGroupId: accountAssetsGroupId }
            if (authType === 'conversion') {
                if (valid.assetId?.length) {
                    params.assetsDTOS = valid.assetId.map((conversion: string) => {
                        const [assetId, assetName] = conversion.split('$')
                        return { assetId, assetName }
                    })
                    delete valid.assetId
                    delete params.assetId
                }
                batchAuthAccountAssetsGroupAccount.run(params).then(res => {
                    console.log(res)
                    if (res) {
                        message.success('授权成功')
                        onChange?.()
                    }
                })
            } else {
                authAccountAssetsGroupAccount.run(params).then(res => {
                    console.log(res)
                    if (res) {
                        message.success('授权成功')
                        onChange?.()
                    }
                })
            }
        })
    }

    return <Modal
        title={<strong>{authMainAccountId} 授权子账户（<span style={{ color: 'red', fontSize: 12 }}>主体：{corporationName}</span>）</strong>}
        open={visible}
        onCancel={onClose}
        className="modalResetCss"
        onOk={handleOk}
        confirmLoading={authAccountAssetsGroupAccount.loading || batchAuthAccountAssetsGroupAccount.loading}
    >
        <Form
            name="basicAddSub"
            form={form}
            layout='vertical'
            autoComplete="off"
        >
            {authType === 'conversion' && <Form.Item label={<strong>授权资产</strong>} name="assetId" rules={[{ required: true, message: '请授权资产!' }]}>
                <Select
                    placeholder="请选择授权资产"
                    allowClear
                    showSearch
                    mode="multiple"
                    maxTagCount={5}
                    loading={getConversionInfo.loading}
                    options={tableData}
                    showArrow={false}
                    filterOption={false}
                    onSearch={handleSearch}
                    searchValue={value}
                    dropdownMatchSelectWidth={false}
                />
            </Form.Item>}
            <Form.Item label={<strong>请选择账户</strong>} name="accountId" rules={[{ required: true, message: '请选择账户!' }]} valuePropName="targetKeys">
                <Transfer
                    showSearch
                    filterOption={(inputValue: string, option: any) => {
                        let newInput: string[] = inputValue ? inputValue?.split(/[,，\n\s]+/ig).filter((item: any) => item) : []
                        return newInput?.some(val => option!.title?.toString().toLowerCase()?.includes(val))
                    }}
                    dataSource={getAccountAllList?.data?.filter((item: { accountId: string, corporationLicence: string }) => item.accountId != authMainAccountId && item.corporationLicence === corporationLicence)?.map((item: { accountId: any }) => ({ title: item.accountId, key: item.accountId, disabled: selectedAccountIdList?.includes(item.accountId) }))}
                    titles={['所有', '已选']}
                    oneWay
                    listStyle={{
                        height: 450,
                        width: 222
                    }}
                    render={item => <span>{item.title}</span>}
                    pagination
                />
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(AddSubAccount)