import { useState, useEffect } from 'react'
import './RefunModal.css'
import { Form, Button, Upload, message, Input, Modal, Table, Empty } from 'antd';
import type { TableColumnsType } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { uploadImageUrl, DevUserId, get, post } from "../../util/AjaxUtils.ts";
// import { getMenuActive } from '../../util/cache.ts'
import { useDispatch } from 'react-redux'
const { Search } = Input;
const { TextArea } = Input;
interface DataType {
    key: React.Key;
    projName: string;
    projContext: string;
    gmtCreate: string;
    projId: string
}

export default function RefunModal(props: any) {
    const columns: TableColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 80,
            render: (_text, _record, index) => (page - 1) * 20 + index + 1, // 显示序号，从1开始
        },
        {
            title: '项目名称',
            dataIndex: 'projName',
            align: 'center',

            render: (text: string) => <>{text}</>,
        },
        {
            title: '编号',
            dataIndex: 'projContext',
            align: 'center',


        },
        {
            title: '创建时间',
            dataIndex: 'gmtCreate',
            align: 'center',

        },
    ];


    const [messageApi, contextHolder] = message.useMessage();
    // 上传附件
    const [refunArray, setRefunArray] = useState<string[]>([]);
    // const [selectedReason, setSelectedReason] = useState(''); //选择原因

    // const handleReasonChange = (value: any) => {
    //     setSelectedReason(value);
    // };
    // 获取当前选择类型
    // const type = getMenuActive()
    const dispath = useDispatch()
    // 选择项目得临时name
    const [newprojName, setnewprojName] = useState('')
    // 选择项目得name
    const [projName, setProjName] = useState('')
    // 选择得项目临时id
    const [newprojId, setnewProjId] = useState('')
    // 选择 项目的id
    const [projId, setProjId] = useState('')
    //默认选择得项目
    const [selectedRowKeys, setselectedRowKeys] = useState<string[]>([])
    // 分页
    const [page, setPage] = useState(1)
    const [total, setTotal] = useState(0)
    // 搜索关键字
    const [keywords, setKeywords] = useState('')
    const [refunDataArray, setRefunDataArray] = useState<any[]>([]) //未退款项目数组
    // 选择项目弹窗
    const [projModal, setProjModal] = useState(false)
    const [isDisabled, setIsDisabled] = useState(false) //提交按钮是否禁用
    const [form] = Form.useForm<any>();

    // 关键字搜索
    const handleSearch = (value: string) => {
        setKeywords(value)
    }
    const handleChange = (e: any) => {
        if (e.target.value == '') {
            setKeywords('')
        }
    }
    // 提交表单
    const onFinish = (values: any) => {
        // console.log('Form values:', values);
        post<any>({
            messageApi,
            url: `/api/proj/refund/apply/save`,
            body: {
                projId: projId,
                refundReason: values.other,
                refundVoucher: refunArray.join(',')
            },
            onBefore() {
                setIsDisabled(true)
            },
            onSuccess() {
                messageApi.success('提交成功')
                setIsDisabled(true)
                setTimeout(() => {
                    props.closeModal()
                }, 500)

                getData()

            },
            onFinally() {
                setIsDisabled(false)
            }
        })
    };
    const getData = () => {
        get({
            messageApi,
            url: `/api/proj/refund/apply/listpage/self`,
            config: {
                params: {
                    page: 1,
                    rows: 20,
                    applyStatus: ''
                }
            },
            onSuccess(data: any) {
                dispath({
                    type: 'upRefunArray',
                    val: data.data.rows
                })
                dispath({
                    type: 'upRefunTotal',
                    val: data.data.total
                })
            }
        })
    }
    // 获取未退款项目
    const getRefunData = () => {
        get({
            messageApi,
            url: `/api/proj/refund/apply/listpage-proj-unapply/self`,
            config: {
                params: {
                    page: 1,
                    rows: 20,
                    keywords
                }
            },
            onBefore() {


            },
            onSuccess(data: any) {
                setRefunDataArray(data.data.rows)
                setTotal(data.data.total)
            },
            onFinally() {


            },
        })
    }
    useEffect(() => {
        getRefunData()
    }, [page, keywords])
    return (
        <div className='refunModal'>
            {contextHolder}
            <Form
                name="Form"
                form={form}
                onFinish={onFinish}
                initialValues={{ softWare: '' }}
                style={{ maxWidth: 600 }}
            >
                <div className='refunModal-item'>
                    <div className='refunModal-title'>
                        退款软著<span className='refunModal-red'>*</span>
                    </div>
                    <div className='refunInput'>

                        <Form.Item
                            name="title"
                            rules={[{ required: true, message: '请选择一个软著!' }]}
                        >
                            <Input style={{
                                width: 405,
                                height: 46,
                                background: '#FFF',
                                color: 'black'
                            }}
                                placeholder="选择需要退款的软著"
                                disabled
                            >
                            </Input>

                        </Form.Item>
                        <div className='refunInput-button' onClick={() => {
                            setProjModal(true)
                            setKeywords('')
                            setPage(1)
                            getRefunData()
                        }}>
                            选择
                        </div>
                    </div>

                </div>
                <div className='refunModal-item'>
                    <div className='refunModal-title'>
                        退款原因<span className='refunModal-red'>*</span>
                    </div>
                    <Form.Item
                        name="other"
                        rules={[{ required: true, message: '请输入退款原因' }]}
                    >
                        <TextArea
                            placeholder="输入退款原因"
                            style={{ height: 120, resize: 'none', width: 405 }}
                        />
                    </Form.Item>
                </div>
                <div className='refunModal-item'>
                    <div className='refunModal-title'>
                        退款凭证<span className='refunModal-red'>*</span>
                    </div>
                    <div style={{ width: 405, }}>
                        <Form.Item
                            name="img"
                            // label="退款软著"
                            valuePropName="fileList"
                            getValueFromEvent={(e: any) => {
                                if (e.file.status === 'done') {
                                    refunArray.push(e.file.response.data.fileId);
                                    setRefunArray(refunArray);
                                }
                                if (e.file.status === 'removed') {
                                    const idArray = refunArray.filter(item => item != e.file.response.data.fileId);
                                    setRefunArray(idArray);
                                }
                                return e.fileList;
                            }}
                            rules={[{ required: true, message: '请上传补正通知书' }]}
                        >
                            <Upload
                                name="image"
                                action={uploadImageUrl()}
                                headers={{ 'X-USER-ID': DevUserId }}
                                beforeUpload={(file) => {
                                    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                                    if (!isJpgOrPng) {
                                        message.error('只能上传 JPG/PNG 格式文件!');
                                        return Upload.LIST_IGNORE; // 不允许上传非
                                    }
                                    return isJpgOrPng;
                                }}
                            // listType="picture-card"
                            >

                                <Button icon={<UploadOutlined />} style={{ marginTop: 2 }}>上传补正通知书</Button>
                            </Upload>
                        </Form.Item>
                    </div>
                </div>

                <Form.Item>
                    <div className='refunModal-btn'>
                        <Button type="primary" htmlType="submit" style={{
                            width: 273,
                            height: 52
                        }}
                            disabled={isDisabled}
                        >
                            提交申请
                        </Button>
                    </div>
                </Form.Item>
            </Form>

            <Modal title="选择退款项目"
                destroyOnClose
                okText="确认"
                cancelText="取消"

                open={projModal}

                onOk={

                    () => {
                        if (newprojId) {
                            setProjName(newprojName)
                            setProjId(newprojId)
                            setProjModal(false)
                            setselectedRowKeys([newprojId])
                            form.setFieldsValue({
                                title: newprojName
                            });
                        } else {
                            messageApi.open({
                                type: 'error',
                                content: '请选择要退款项目'
                            })
                        }

                    }

                }
                width={1220}
                onCancel={() => {
                    setselectedRowKeys([projId])
                    setnewProjId(projId)
                    setnewprojName(projName)
                    setProjModal(false)


                }}>
                <Search placeholder="输入项目名称"
                    onSearch={handleSearch}
                    onChange={handleChange}
                    style={{
                        width: '200px',
                        height: '31px',
                        marginBottom: 15
                    }}
                    allowClear
                />
                <Table
                    rowSelection={{
                        selectedRowKeys: selectedRowKeys,
                        type: 'radio',
                        // ...rowSelection,
                        onChange: (_selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
                            console.log('selectedRows: ', selectedRows);
                            setselectedRowKeys([selectedRows[0].projId])
                            setnewProjId(selectedRows[0].projId)
                            setnewprojName(selectedRows[0].projName)

                        },
                    }}
                    columns={columns}
                    dataSource={refunDataArray}
                    rowKey={'projId'}
                    pagination={
                        {
                            pageSize: 20,
                            total: total,
                            onChange: (currentPage) => {
                                setPage(currentPage);
                            },
                            showSizeChanger: false,
                            current: page

                        }

                    }
                    locale={{
                        emptyText: <Empty
                            description="暂无数据"
                        />,
                    }}
                    scroll={{ y: 500 }}

                />

            </Modal>
        </div>
    )
}
