import { useAjax } from "@/Hook/useAjax";
import { getLicenseAppListApi, GetLicenseAppListProps } from "@/pages/weComTask/API/weChatApiLicense";
import SearchBox from "@/pages/weComTask/components/searchBox";
import { Button, Card, DatePicker, Input, Select, Table, Tag } from "antd";
import { useEffect, useState } from "react";
import { SearchOutlined } from "@ant-design/icons";
import dayJs from "dayjs";
import { copy } from "@/utils/utils";
import SyncApp from "./syncApp";
import EditCallUser from "./editCallUser";


/**
 * 企业许可状态
 * @returns 
 */
const Enterprise: React.FC = () => {

    /***********************************/
    const [queryParams, setQueryParams] = useState<GetLicenseAppListProps>({ pageNum: 1, pageSize: 20 })
    const [oldQueryParams, setOldQueryParams] = useState<GetLicenseAppListProps>({ pageNum: 1, pageSize: 20 })
    const [selectedRows, setselectedRows] = useState<any[]>([])
    const [visible, setVisible] = useState<boolean>(false)

    const getLicenseAppList = useAjax((params) => getLicenseAppListApi(params))
    /***********************************/

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


    return <Card>
        <SearchBox
            bodyPadding={`0 0 10px`}
            buttons={<>
                <Button type="primary" onClick={() => {
                    setQueryParams({ ...oldQueryParams, pageNum: 1, pageSize: queryParams.pageSize })
                }} loading={getLicenseAppList.loading} icon={<SearchOutlined />}>搜索</Button>
                <Button disabled={selectedRows?.length === 0} onClick={() => setVisible(true)}>修改应用信息更新通知人员</Button>
                <Button disabled={selectedRows?.length === 0} danger onClick={() => setselectedRows([])}>清除选择</Button>
            </>}
        >
            <>
                <Input
                    placeholder="企业名称"
                    style={{ width: 120 }}
                    allowClear
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, corpName: e.target.value })}
                    value={oldQueryParams?.corpName}
                />
                <Select
                    allowClear
                    placeholder="购买状态"
                    showSearch
                    options={[{ label: '已购买', value: 1 }, { label: '未购买', value: 0 }]}
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    style={{ width: 80 }}
                    value={oldQueryParams?.bugStatus}
                    onChange={(e) => setOldQueryParams({ ...oldQueryParams, bugStatus: e })}
                />
                <DatePicker.RangePicker
                    placeholder={['试用到期开始日期', '试用到期结束日期']}
                    onChange={(e, date) => { setOldQueryParams({ ...oldQueryParams, expiredStart: date[0], expiredEnd: date[1] }) }}
                    allowClear
                    value={oldQueryParams?.expiredStart ? [dayJs(oldQueryParams?.expiredStart), dayJs(oldQueryParams?.expiredEnd)] : undefined}
                />
                <DatePicker.RangePicker
                    placeholder={['拦截校验开始日期', '拦截校验结束日期']}
                    onChange={(e, date) => { setOldQueryParams({ ...oldQueryParams, licenseCheckStart: date[0], licenseCheckEnd: date[1] }) }}
                    allowClear
                    value={oldQueryParams?.licenseCheckStart ? [dayJs(oldQueryParams?.licenseCheckStart), dayJs(oldQueryParams?.licenseCheckEnd)] : undefined}
                />
            </>
        </SearchBox>

        {/* 表 */}
        <Table
            style={{ marginTop: 10 }}
            dataSource={getLicenseAppList?.data?.data?.records}
            loading={getLicenseAppList?.loading}
            bordered
            columns={[
                {
                    title: '操作',
                    dataIndex: 'cz',
                    key: 'cz',
                    align: 'center',
                    width: 90,
                    render: (_, record: any) => {
                        return <SyncApp corpId={record.corpId} onChange={getLicenseAppList?.refresh} />
                    }
                },
                {
                    title: '企业名称',
                    dataIndex: 'corpName',
                    key: 'corpName',
                    width: 200,
                    ellipsis: true,
                    render: (text) => <a onClick={() => copy(text)}>{text}</a>
                },
                {
                    title: '企业ID',
                    dataIndex: 'corpId',
                    key: 'corpId',
                    width: 280,
                    ellipsis: true,
                },
                {
                    title: '状态',
                    dataIndex: 'licenseStatus',
                    key: 'licenseStatus',
                    width: 120,
                    align: 'center',
                    render: (text) => text ? <Tag color="green">已开启状态检查</Tag> : <Tag color="red">未开启状态检查</Tag>
                },
                {
                    title: '试用期已使用天数',
                    dataIndex: 'dayPassed',
                    key: 'dayPassed',
                    width: 60,
                    align: 'center',
                    render: (text) => <span style={text > 85 ? { color: 'red' } : {}}>{text}</span>
                },
                {
                    title: '购买状态',
                    dataIndex: 'bugStatus',
                    key: 'bugStatus',
                    width: 70,
                    align: 'center',
                    render: (text) => text ? <Tag color="green">已购买</Tag> : <Tag color="red">未购买</Tag>
                },
                {
                    title: '接口许可试用开始时间',
                    dataIndex: 'startTime',
                    key: 'startTime',
                    width: 135,
                    align: 'center',
                    ellipsis: true,
                    render: (text) => text || '--'
                },
                {
                    title: '接口许可试用到期时间',
                    dataIndex: 'endTime',
                    key: 'endTime',
                    width: 135,
                    align: 'center',
                    ellipsis: true,
                    sorter: true,
                    render: (text) => text || '--'
                },
                {
                    title: '接口开启拦截校验时间',
                    dataIndex: 'licenseCheckTime',
                    key: 'licenseCheckTime',
                    width: 135,
                    align: 'center',
                    ellipsis: true,
                    sorter: true,
                    render: (text) => text || '--'
                },
                {
                    title: '到期通知人员',
                    dataIndex: 'userList',
                    key: 'userList',
                    ellipsis: true,
                    render: (text) => text?.map(item => item.name)?.join('、') || '--'
                }
            ]}
            scroll={{ x: 1000 }}
            rowKey={'corpId'}
            size='small'
            pagination={{
                total: getLicenseAppList?.data?.data?.total,
                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                showSizeChanger: true,
                showLessItems: true,
                defaultCurrent: 1,
                defaultPageSize: 20,//默认初始的每页条数
                current: getLicenseAppList?.data?.data?.current || 1,
                pageSize: getLicenseAppList?.data?.data?.size || 20,
            }}
            onChange={(pagination, _, sortData: any) => {
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryParams))
                let newOldQueryParams = JSON.parse(JSON.stringify(oldQueryParams))
                if (sortData && sortData?.order) {
                    newQueryForm['sortAsc'] = sortData?.order === 'ascend' ? true : false
                    newQueryForm['sortFiled'] = sortData?.field
                } else {
                    delete newQueryForm['sortAsc']
                    delete newQueryForm['sortFiled']
                }
                newQueryForm.pageNum = current || newQueryForm.pageNum
                newQueryForm.pageSize = pageSize || newQueryForm.pageSize
                setQueryParams({ ...newQueryForm })
                setOldQueryParams({ ...newOldQueryParams })
            }}
            rowSelection={{
                selectedRowKeys: selectedRows?.map((item: any) => item?.corpId),
                onSelect: (record: { corpId: string }, selected: boolean) => {
                    let newData = JSON.parse(JSON.stringify(selectedRows))
                    if (selected) {
                        newData.push({ ...record })
                    } else {
                        newData = newData.filter((item: { corpId: string }) => item.corpId !== record.corpId)
                    }
                    setselectedRows(newData)
                },
                onSelectAll: (selected: boolean, _: { corpId: string }[], changeRows: { corpId: string }[]) => {
                    let newData = JSON.parse(JSON.stringify(selectedRows || '[]'))
                    if (selected) {
                        changeRows.forEach((item: { corpId: string }) => {
                            const index = newData.findIndex((ite: { corpId: string }) => ite.corpId === item.corpId)
                            if (index === -1) {
                                newData.push(item)
                            }
                        })
                    } else {
                        const newSelectAccData = newData.filter((item: { corpId: string }) => {
                            const index = changeRows.findIndex((ite: { corpId: string }) => ite.corpId === item.corpId)
                            if (index !== -1) {
                                return false
                            } else {
                                return true
                            }
                        })
                        newData = newSelectAccData
                    }
                    setselectedRows(newData)
                }
            }}
        />

        {/* 编辑呼叫用户 */}
        {visible && <EditCallUser
            selectedRows={selectedRows}
            visible={visible}
            onClose={() => setVisible(false)}
            onChange={() => {
                setselectedRows([])
                setVisible(false)
                getLicenseAppList.refresh()
            }}
        />}
    </Card>
}


export default Enterprise