import Tables from '@/components/Tables'
import { useAjax } from '@/Hook/useAjax'
import { exportAutoLinkExcle, importLinkExcle, selectLinks } from '@/services/operating/link'
import { downloadFile } from '@/utils/downloadFile'
import { DownloadOutlined, UploadOutlined } from '@ant-design/icons'
import { Button, Card, Drawer, message, Popover, Select, Space, Tooltip, Upload } from 'antd'

import { RcCustomRequestOptions } from 'antd/lib/upload/interface'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import columns from './tableConfig'
import detailsColumns from './detailsTableConfig'
import platformText from './platformText'
import style from './index.less'
enum LinkType {
    '数据',
    '推广链接',
    '自定义活动',
    '赠币活动',
    '常规活动链接',
    '模板充值活动链接',
    '模板直赠活动链接',
    '模板消耗活动连接'
}
enum Platform {
    '花生' = '花生',
    '阅文' = '阅文',
    '阳光' = '阳光',
    '文鼎' = '文鼎',
    '掌中云' = '掌中云',
}
enum PlatformName {
    '花生推广链接' = '花生Link',
    '花生活动链接' = '花生Active',
    '阳光推广链接' = '阳光Link',
    '阳光活动链接' = '阳光Active',
    '阅文推广链接' = '阅文Link',
    '阅文活动链接' = '阅文Active'
}
const name = {
    '花生': '花生自动建链接导入模板 .xlsx',
    '阅文': '阅文自动建链接导入模板.xlsx',
    '阳光': '阳光自动建链接导入模板.xlsx',
    '文鼎': '文鼎自动建链接导入模板.xlsx',
    '掌中云': '掌中云自动建链接导入模板.xlsx'
}

function Automation() {
    const [platformName, setPlatformName] = useState<string>('花生')
    const [btnUploadLoding, setBtnUploadLoding] = useState<boolean>(false)//按钮loding
    const downLoad = useAjax((params) => exportAutoLinkExcle(params), { formatResult: true })//模板下载
    const upLoad = useAjax((params) => importLinkExcle(params), { formatResult: true })//模板下载
    const list = useAjax((params) => selectLinks(params), { formatResult: true })//模板下载
    const [visible, setVisible] = useState<boolean>(false)//详情弹窗
    const [data, setData] = useState<any>([])//详情数据
    const [bfData, setBfData] = useState<any>([])//备份详情数据用在筛选
    //导出
    const onExportLinkExcle = useCallback((platformName: string) => {
        downLoad.run({ platformName }).then((res) => {
            downloadFile(res, 'vnd.openxmlformats-officedocument.spreadsheetml.sheet', `${platformName}自动建链接导入模板.xlsx`)
        })
    }, [])
    //平台数组
    const tabList = useMemo(() => {
        let arr: any = []
        Object.keys(Platform).map((item) => {
            arr.push({ key: item, tab: Platform[item] })
        })
        return arr
    }, [Platform])
    //获取列表
    const getList = useCallback((props: { pageSize?: number, pageNum?: number, createStatus?: any }) => {
        let { pageSize = 20, pageNum = 1, createStatus } = props
        let obj = { platformName, pageSize, pageNum }
        if (createStatus) {
            obj['createStatus'] = createStatus
        }
        list.run(obj)
    }, [platformName])
    //查询
    const pageChange = useCallback((props: any) => {
        const { pageSize = 20, current = 1, createStatus } = props
        getList({ pageNum: current, pageSize, createStatus })
    }, [])
    //查询详情状态
    const statusChange = useCallback((value) => {
        let newData = JSON.parse(JSON.stringify(data))
        if (value) {
            newData['autoLinkReocrds'] = data?.autoLinkReocrds?.filter((item: { createStatus: any }) => item.createStatus == value)
        } else {
            newData['autoLinkReocrds'] = data?.autoLinkReocrds
        }
        setBfData(newData)
    }, [data, bfData])
    //查看详情
    const see = useCallback((props) => {
        setVisible(true)
        setData(props)
        setBfData(props)
        console.log(props)
    }, [])
    //首次或切换tab获取列表
    useEffect(() => {
        getList({})
    }, [platformName])
    console.log(platformText[platformName])
    return <div>
        <Card
            style={{ width: '100%' }}
            title={'自动化任务'}
            tabList={tabList}
            onTabChange={key => {
                setPlatformName(key)//设置平台id
                // setCreatLinkType(`${Platform[key]}Link`)
            }}
            size='small'
            tabProps={{ size: 'small', type: "card" }}
            tabBarExtraContent={
                <Space>
                    <Popover
                        content={
                            <div className={style.platformText}>
                                {platformText[platformName]}
                            </div>
                        }
                        title={<h1 style={{ textAlign: 'center' }}>{platformName}字段描述</h1>}
                        placement='bottom'
                    >
                        <Button type='dashed' danger>平台导入注意项</Button>
                    </Popover>
                    <Select
                        showSearch
                        placeholder='状态查询'
                        filterOption={(input, option) =>
                            option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        style={{ width: 130 }}
                        onChange={(value) => { value && pageChange({ createStatus: value }) }}
                        allowClear
                    >
                        <Select.Option value='0'>导入excel成功</Select.Option>
                        <Select.Option value='1'>创建中</Select.Option>
                        <Select.Option value='2'>部分成功</Select.Option>
                        <Select.Option value='3'>全部成功</Select.Option>
                        <Select.Option value='-1'>创建失败</Select.Option>
                        <Select.Option value='-2'>全部失败</Select.Option>
                    </Select>
                    <Button onClick={() => { getList({}) }} type='primary' loading={list?.loading}>刷新</Button>
                    {/* <Button onClick={() => onExportLinkExcle(platformName)} type='dashed'><DownloadOutlined />下载自动化模板</Button> */}
                    <Button type='dashed'><DownloadOutlined />
                        <a href={`http://oss.zanxiangnet.com/zx-system/file/excel/${name[platformName]}`}>下载自动化模板</a>
                    </Button>
                <Upload
                    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    action=""
                    listType="text"
                    onChange={() => { }}
                    multiple={true}
                    showUploadList={false}
                    customRequest={(options: RcCustomRequestOptions) => {
                        setBtnUploadLoding(true)
                        let formData = new FormData();
                        formData.append("file", options.file);
                        upLoad.run({ data: formData, platformName }).then(res => {
                            setBtnUploadLoding(false)
                            if (res) {
                                message.success('导入成功')
                                list.refresh()
                            }
                        }).catch(() => {
                            setBtnUploadLoding(false)
                        })
                    }}
                ><Button type='primary' icon={<UploadOutlined />} loading={btnUploadLoding}>导入模板批量创建</Button></Upload>
                </Space>
            }
        >
            <Tables
            dataSource={list?.data?.data?.records}
            columns={columns(platformName, see)}
            bordered
            size='small'
            rowClassName={(data: any) => {
                if (data['createStatus'] === -2 || data['createStatus'] === -1) {
                    return 'table_row_red'
                }
                if (data['createStatus'] === 2) {
                    return 'table_row_yellow'
                }
                return ''
            }}
            // pageChange={pageChange}
            // sizeChange={pageChange}
            total={list?.data?.data?.total}
            onChange={pageChange}
        />
        </Card>
    {/* 详情弹窗 */ }
    <Drawer
        title={<div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Space>
                <span>{data?.fileName}</span>
                <a href={data?.excelLink}>导出Excel</a>
            </Space>
            <Select
                showSearch
                placeholder='状态查询'
                filterOption={(input, option) =>
                    option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                style={{ width: 130 }}
                onChange={(value) => { statusChange(value) }}
                allowClear
            >
                <Select.Option value={'0'}>创建</Select.Option>
                <Select.Option value={'1'}>创建中</Select.Option>
                <Select.Option value={'2'}>创建成功</Select.Option>
                <Select.Option value={'-1'}>创建链接失败</Select.Option>
                <Select.Option value={'-2'}>创建客服消息失败</Select.Option>
            </Select>
        </div>}
        placement={'top'}
        closable={false}
        onClose={() => { setVisible(false) }}
        visible={visible}
        height={500}
    >
        <Tables
            dataSource={bfData?.autoLinkReocrds}
            columns={detailsColumns(platformName)}
            bordered
            size='small'
            scroll={{ x: 3000 }}
            rowClassName={(data: any) => {
                console.log(data['createStatus'])
                if (data['createStatus'] === -1 || data['createStatus'] === -2) {
                    return 'table_row_red'
                }
                return ''
            }}
        />
    </Drawer>
    </div >
}

export default Automation