import { api_corpUser_allOfUser } from '@/API/global';
import { useAjax } from '@/Hook/useAjax';
import { deleteKeywordApi, enableKeywordApi, getKeywordListApi, GetKeywordListProps } from '@/pages/weComTask/API/chatRecordManage';
import { useSize } from 'ahooks';
import React, { useEffect, useRef, useState } from 'react';
import style from '../../corpUserManage/index.less'
import { App, Button, Card, Pagination, Select, Table } from 'antd';
import SearchBox from '@/pages/weComTask/components/searchBox';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { TableConfig } from './tableConfig';
import AddModify from './AddModify';

const RiskWord: React.FC = () => {

    /*****************************************/
    const { message } = App.useApp()
    const ref = useRef<HTMLDivElement>(null)
    const size = useSize(ref)
    const userIdStr = sessionStorage.getItem('userId');
    const [userId] = useState<number>(userIdStr ? Number(userIdStr) : undefined);
    const [activeCorp, setActiveCorp] = useState<any>()

    const [queryForm, setQueryForm] = useState<GetKeywordListProps>({
        pageNum: 1,
        pageSize: 20
    })
    const [visible, setVisible] = useState<boolean>(false)
    const [initialValues, setInitialValues] = useState<any>({ corpUserDTOList: [{}], keywordJson: [''], replyJson: [[]] })

    const corpUser_allOfUser = useAjax((params) => api_corpUser_allOfUser(params))
    const getKeywordList = useAjax((params) => getKeywordListApi(params))
    const deleteKeyword = useAjax((params) => deleteKeywordApi(params))
    const enableKeyword = useAjax((params) => enableKeywordApi(params))
    /*****************************************/

    useEffect(() => {
        if (userId) {
            corpUser_allOfUser.run(userId)
        }
    }, [userId])

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

    // 编辑
    const edit = (data: any, isCopy?: boolean) => {
        let newValue = JSON.parse(JSON.stringify(data))
        if (newValue.replyJson) {
            newValue.replyJson = newValue.replyJson.map((item: { msgType: any; msgContent: any; }) => {
                let obj: { [x: string]: any } = { mediaType: item.msgType }
                switch (item.msgType) {
                    case 'text':
                        obj["textContent"] = item.msgContent
                        break
                    case 'image':
                        obj["imageUrl"] = item.msgContent
                        break;
                    case 'video':
                        obj["videoUrl"] = item.msgContent
                        break;
                }
                return [obj]
            })
        }
        let params: any = { ...newValue, tagIds: newValue?.tagIds?.map((item: { toString: () => any; }) => item?.toString()) }
        if (isCopy) {
            delete params?.id
        }
        setInitialValues(params)
        setVisible(true)
    }

    /** 删除 */
    const del = (id: number) => {
        deleteKeyword.run([id]).then(res => {
            if (res?.data) {
                message.success('删除成功')
                getKeywordList.refresh()
            }
        })
    }

    const taskPause = (pause: boolean, ids: number[]) => {
        enableKeyword.run({ enabled: pause, ids }).then(res => {
            message.success(pause ? "启用成功" : '禁用成功')
            getKeywordList.refresh()
        })
    }

    return (
        <div className={style.corpUserManage}>
            <div className={style.corpUserManage_bottom} style={{ height: '100%' }}>
                <Card className={style.corpUserList} styles={{ body: { padding: 0, display: 'flex', flexDirection: 'column', height: '100%' } }}>
                    <SearchBox
                        bodyPadding={`16px 16px 12px`}
                        buttons={<>
                            <Button type="primary" onClick={() => getKeywordList.refresh()} icon={<SearchOutlined />}>搜索</Button>
                            <Button type="primary" onClick={() => {
                                setVisible(true)
                            }}><PlusOutlined />新增风险词</Button>
                        </>}
                    >
                        <>
                            <Select
                                style={{ width: 180 }}
                                placeholder="选择企业"
                                value={queryForm?.corpId}
                                showSearch
                                maxTagCount={1}
                                allowClear
                                onChange={(e, option: any) => {
                                    setQueryForm({ ...queryForm, corpId: e, pageNum: 1 })
                                    setActiveCorp(option?.data)
                                }}
                                filterOption={(input: string, option?: { label: string; value: string }) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                                options={corpUser_allOfUser?.data?.data?.map((item: { t1: any }) => ({ label: item.t1?.corpName, value: item.t1?.corpId, data: item }))}
                            />
                            {activeCorp && <Select
                                style={{ minWidth: 125 }}
                                placeholder='企微号'
                                allowClear
                                autoClearSearchValue={false}
                                onChange={(e) => setQueryForm({ ...queryForm, corpUserId: e, pageNum: 1 })}
                                value={queryForm?.corpUserId}
                                filterOption={(input, option) =>
                                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                                }
                                options={activeCorp?.t2?.map((item: any) => ({ label: item.name, value: item.corpUserId }))}
                            />}

                            <Select
                                style={{ width: 150 }}
                                placeholder="启用状态"
                                value={queryForm?.enabled}
                                showSearch
                                allowClear
                                onChange={(e) => {
                                    setQueryForm({ ...queryForm, enabled: e, pageNum: 1 })
                                }}
                                filterOption={(input: string, option?: { label: string; value: string }) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                                options={[{ label: '启用', value: "true" }, { label: '禁用', value: "false" }]}
                            />
                            <Select
                                style={{ minWidth: 125 }}
                                placeholder='风险等级'
                                allowClear
                                autoClearSearchValue={false}
                                onChange={(e) => { setQueryForm({ ...queryForm, riskLevel: e }) }}
                                value={queryForm?.riskLevel}
                                filterOption={(input, option) =>
                                    ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                                }
                                options={[
                                    {
                                        label: '低',
                                        value: 1
                                    },
                                    {
                                        label: '中',
                                        value: 2
                                    },
                                    {
                                        label: '高',
                                        value: 3
                                    }
                                ]}
                            />
                        </>
                    </SearchBox>
                    <div className={style.corpUserList_table} ref={ref}>
                        <Table
                            style={{ marginBottom: 1 }}
                            dataSource={getKeywordList?.data?.data?.records}
                            loading={getKeywordList?.loading}
                            columns={TableConfig(edit, del, taskPause)}
                            scroll={{ x: 1200, y: size?.height && ref.current ? size?.height - 32 : 300 }}
                            rowKey={'id'}
                            bordered
                            size='small'
                            pagination={false}
                        />
                    </div>
                    <div className={style.corpUserList_footer}>
                        <Pagination
                            size="small"
                            total={getKeywordList?.data?.data?.total || 0}
                            showSizeChanger
                            showQuickJumper
                            pageSize={getKeywordList?.data?.data?.size || 20}
                            current={getKeywordList?.data?.data?.current || 1}
                            onChange={(page: number, pageSize: number) => {
                                ref.current?.scrollTo({ top: 0 })
                                setQueryForm({ ...queryForm, pageNum: page, pageSize })
                            }}
                            showTotal={(total: number) => <span style={{ fontSize: 12 }}>共 {total} 条</span>}
                        />
                    </div>
                </Card>
            </div>

            {visible && <AddModify
                corpList={corpUser_allOfUser?.data?.data || []}
                initialValues={initialValues}
                visible={visible}
                onClose={() => {
                    setVisible(false)
                    setInitialValues(undefined)
                }}
                onChange={() => {
                    setVisible(false)
                    setInitialValues(undefined)
                    getKeywordList.refresh()
                }}
            />}
        </div>
    );
};

export default RiskWord;