import { useAjax } from "@/Hook/useAjax"
import { getPackLinkCodeListApi, GetPackLinkCodeListProps, updatePackLinkCodeApi } from "@/services/gameData/roleOperate"
import { Button, Col, DatePicker, Form, Input, message, Modal, Popconfirm, Row, Space } from "antd"
import React, { useEffect, useState } from "react"
import style from '../../components/TableData/index.less'
import moment from "moment"
import Tables from "@/components/Tables"
import ModifyCode from "./modifyCode"
import columnsPosCode from "./tableConfigCode"

interface Props {
    data: any
    visible?: boolean
    onClose?: () => void
}

/**
 * 链接礼包码
 * @param param0 
 * @returns 
 */
const LinkCode: React.FC<Props> = ({ data, visible, onClose }) => {

    /******************************/
    const [form] = Form.useForm()
    const [addCodevisible, setaddCodeVisible] = useState<boolean>(false)
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const [queryFrom, setQueryForm] = useState<GetPackLinkCodeListProps>({ pageNum: 1, pageSize: 20, linkId: data.id })
    const getPackLinkCodeList = useAjax((params) => getPackLinkCodeListApi(params))
    const updatePackLinkCode = useAjax((params) => updatePackLinkCodeApi(params))
    /******************************/

    const onFinish = (data: any) => {
        let oldQueryFrom = JSON.parse(JSON.stringify(queryFrom))
        let params = { ...oldQueryFrom, ...data, pageNum: 1 }
        if (params?.createTime?.length > 1) {
            params.createBeginTime = moment(params.createTime[0]).format('YYYY-MM-DD')
            params.createEndTime = moment(params.createTime[1]).format('YYYY-MM-DD')
        } else {
            delete params?.createBeginTime
            delete params?.createEndTime
        }
        if (params?.updateTime?.length > 1) {
            params.updateBeginTime = moment(params.updateTime[0]).format('YYYY-MM-DD')
            params.updateEndTime = moment(params.updateTime[1]).format('YYYY-MM-DD')
        } else {
            delete params?.updateBeginTime
            delete params?.updateEndTime
        }
        setQueryForm(params)
    }

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


    const handleEnabled = () => {
        updatePackLinkCode.run({ ids: selectedRows.map(item => item.id), linkId: data.id }).then(res => {
            if (res) {
                message.success('删除成功')
                getPackLinkCodeList.refresh()
                setSelectedRows([])
            }
        })
    }

    return <Modal
        title={<Space>
            <strong>{data?.gameName}({data?.codeTypeName}) 链接礼包码</strong>
            <a onClick={() => { setaddCodeVisible(true); }}>新增礼包码</a>
            {selectedRows?.length > 0 && <>
                
                <Popconfirm
                    title="确定删除?"
                    onConfirm={() => handleEnabled()}
                >
                    <a style={{ color: 'red' }}>删除</a>
                </Popconfirm>
            </>}
        </Space>}
        visible={visible}
        onCancel={onClose}
        footer={null}
        width={1000}
    >
        <Space style={{ width: '100%' }} direction="vertical" size={10}>
            <Form layout="inline" className='queryForm' name="basicGameServer" form={form} onFinish={onFinish}>
                <Row gutter={[0, 6]}>
                    <Col><Form.Item name='code'>
                        <Input placeholder="礼包码" allowClear style={{ width: 120 }} />
                    </Form.Item></Col>
                    {/* <Col><Form.Item name='enabled'>
                        <Select
                            showSearch
                            style={{ width: 120 }}
                            allowClear
                            placeholder={'是否可用？'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            <Select.Option value={1}>是</Select.Option>
                            <Select.Option value={0}>否</Select.Option>
                        </Select>
                    </Form.Item></Col> */}
                    <Col><Form.Item name='createTime'>
                        <DatePicker.RangePicker style={{ width: 250 }} placeholder={['创建时间开始', '创建时间结束']} />
                    </Form.Item></Col>
                    <Col><Form.Item name='updateTime'>
                        <DatePicker.RangePicker style={{ width: 250 }} placeholder={['更新时间开始', '更新时间结束']} />
                    </Form.Item></Col>
                    <Col>
                        <Space>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button onClick={() => form.resetFields()}>重置</Button>
                        </Space>
                    </Col>
                </Row>
            </Form>

            <div className={`${style['small']}`}>
                <Tables
                    className={`all_table content_table_body`}
                    bordered
                    sortDirections={['ascend', 'descend', null]}
                    current={queryFrom.pageNum}
                    pageSize={queryFrom.pageSize}
                    columns={columnsPosCode(data.id, () => getPackLinkCodeList.refresh())}
                    dataSource={getPackLinkCodeList?.data?.records}
                    scroll={{ x: 900, y: 600 }}
                    onChange={(pagination: any, filters: any, sortData: any) => {
                        let { current, pageSize } = pagination
                        let newQueryForm = JSON.parse(JSON.stringify(queryFrom))
                        if (sortData && sortData?.order) {
                            newQueryForm['sortType'] = sortData?.order === 'ascend' ? 'asc' : 'desc'
                            newQueryForm['sortFiled'] = sortData?.field
                        } else {
                            delete newQueryForm['sortType']
                            delete newQueryForm['sortFiled']
                        }
                        newQueryForm.pageNum = current
                        newQueryForm.pageSize = pageSize
                        setQueryForm({ ...newQueryForm })
                    }}
                    size="small"
                    total={getPackLinkCodeList?.data?.total}
                    loading={getPackLinkCodeList?.loading}
                    defaultPageSize={20}
                    rowSelection={{
                        selectedRowKeys: selectedRows.map(item => item.id.toString()),
                        onSelect: (record: { id: number }, selected: boolean) => {
                            if (selected) {
                                selectedRows.push({ ...record })
                                setSelectedRows([...selectedRows])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { id: number }) => item.id !== record.id)
                                setSelectedRows([...newSelectAccData])
                            }
                        },
                        onSelectAll: (selected: boolean, selectedRowss: { id: number }[], changeRows: { id: number }[]) => {
                            if (selected) {
                                let newSelectAccData = [...selectedRows]
                                changeRows.forEach((item: { id: number }) => {
                                    let index = newSelectAccData.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index === -1) {
                                        let data: any = { ...item }
                                        newSelectAccData.push(data)
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { id: number }) => {
                                    let index = changeRows.findIndex((ite: { id: number }) => ite.id === item.id)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            }
                        }
                    }}
                />
            </div>
        </Space>

        {/* 新增礼包码 */}
        {addCodevisible && <ModifyCode
            visible={addCodevisible}
            gameId={data.gameId}
            linkId={data.id}
            onChange={() => {
                setaddCodeVisible(false)
                getPackLinkCodeList.refresh()
            }}
            onClose={() => {
                setaddCodeVisible(false)
            }}
        />}
    </Modal>
}


export default React.memo(LinkCode)