/* eslint-disable @typescript-eslint/no-use-before-define */

// agv线路数据页面
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Tag } from 'antd';
import { useEffect, useRef, useState } from 'react';
import agvlineInfoAPI from '@/api/agvlineService'
import agvbasicInfoAPI from '@/api/agvbasicService';
import Select from 'antd/lib/select';






const Agvline = () => {
    // 2.定义编辑/新增的弹窗

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modelTitle, setModelTitle] = useState<string>();
    const [typeForm] = Form.useForm();
    // 起始点位状态
    const [startoptin, setstartoptin] = useState<MySelectType.Select[]>([])
    //  结束点位状态
    const [endoption, setendoption] = useState<MySelectType.Select[]>([])
    const actionRef = useRef<ActionType>();
    // 1.定义列


    const columns: ProColumns<AgvlineInfoTypes.Info>[] = [
        {
            title: 'id',
            dataIndex: 'id',
            tip: '规则名称是唯一的 key',
            hideInSearch: true,
            hideInTable: true,

        },
        {
            title: '线路名称',
            dataIndex: 'name',
            ellipsis: true,
            align: 'center'
        },
        {
            title: '线路编码',
            dataIndex: 'code',
            ellipsis: true,
            align: 'center'
        },
        {
            title: '起始点位',
            dataIndex: 'startPointId',
            hideInSearch: true,
            ellipsis: true,
            align: 'center',
            render: (_, record) => {
                return <>{startoptin.find(x => x.key === record.startPointId)?.label}</>
            }

        },
        {
            title: '结束点位',
            dataIndex: 'endPointId',
            hideInSearch: true,
            ellipsis: true,
            align: 'center',
            render: (_, record) => {
                return <>{endoption.find(x => x.key === record.endPointId)?.label}</>
            }
        },
        {
            title: '业务描述',
            dataIndex: 'description',
            hideInSearch: true,
            ellipsis: true,
            align: 'center'
        },

        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            align: 'center',
            // 4.操作内有两个按钮
            render: (_, record) => [
                <Button
                    key="edit"
                    type="primary" ghost
                    onClick={async () => {
                        setIsModalOpen(true);
                        setModelTitle('编辑线路');
                        const copyFormData = JSON.parse(JSON.stringify(record));
                        typeForm.setFieldsValue(copyFormData);
                    }}
                >编辑
                </Button>,

                // 删除
                <Popconfirm
                    key="del"
                    title="确定要删除此条数据吗？"
                    onConfirm={() => {
                        const EnablejsonData: AgvlineInfoTypes.Info = {
                            id: record.id,
                            name: '',
                            code: '',
                            endPointId: '',
                            startPointId: '',
                            description: ''
                        };
                        agvlineInfoAPI.Del(EnablejsonData).then((r: MyResponse.Content) => {
                            if (r.statusCode === 200) {
                                message.success(r.statusCode === 200 ? '删除成功' : r.message);
                                actionRef.current?.reload();

                            }
                        });
                    }}
                    onCancel={() => {
                        message.info('已取消删除');
                    }}
                    okText="确认"
                    cancelText="关闭"
                >
                    <Button type="primary" danger ghost>删除</Button>
                </Popconfirm>,
            ]

        },
    ];

    useEffect(() => {
        const startList = async () => {
            const infomation = await agvbasicInfoAPI.selectlist()
            console.log('dinfomation', infomation);
            //   data就是点位
            // eslint-disable-next-line array-callback-return
            infomation.data.map((item: { label: any; value: any; key: any; }) => {
                // console.log('222',item.label);
                item.label = item.value
            })
            // eslint-disable-next-line array-callback-return
            setstartoptin(infomation.data)
        }
        startList()
        const endList = async () => {
            const infomation1 = await agvbasicInfoAPI.selectlist()
            console.log('infomation1', infomation1);
            // eslint-disable-next-line array-callback-return, @typescript-eslint/no-unused-vars
            infomation1.data.map((item: { label: any; value: any; key: any; }) => {
                // console.log(item,'222');
                item.label = item.value
            })
            setendoption(infomation1.data)
        }
        endList()
    }, []);

    // 7.定义表单提交
    //  表单提交
    const OnSubmit = async (values: AgvlineInfoTypes.Info) => {
        console.log(values);
        if (values.id) {
            const response = await agvlineInfoAPI.Update(values);
            if (response.statusCode === 200) {
                message.success('修改成功');
                actionRef.current?.reload();
                setIsModalOpen(false);
            } else {
                message.error(JSON.stringify(response.errors) || '修改失败');
            }
        } else {
            // 让code默认为空
            // values.code = '';
            const response = await agvlineInfoAPI.Add(values);
            actionRef.current?.reload()
            if (response.statusCode === 200) {
                message.success('添加成功');
                actionRef.current?.reload()
                setIsModalOpen(false);
            } else {
                message.error(JSON.stringify(response.errors) || '添加失败');
            }
        }
    };
    return (
        <>
            <ProTable<AgvlineInfoTypes.Info>
                actionRef={actionRef}
                request={async (params = {}) => {
                    const jsonData: AgvlineInfoTypes.Page = {
                        pageIndex: params.current || 1,
                        pageSize: params.pageSize || 10,
                        name: params.name || '',
                        code: ''
                    };
                    const response = await agvlineInfoAPI.PagedList(jsonData);
                    if (response.statusCode === 200) {
                        return {
                            data: response.data.items,
                            success: true,
                            total: response.data.total,
                        };
                    } else {
                        return {
                            data: [],
                            success: false,
                            total: 0,
                        };
                    }
                }}
                rowKey="id"
                pagination={{
                    pageSize: 10,
                    showSizeChanger:false
                }}
                dateFormatter="string"
                headerTitle="线路列表"
                columns={columns}
                toolBarRender={() => [
                    <Button
                        key="button"
                        type="primary"
                        onClick={() => {
                            typeForm.resetFields();
                            setIsModalOpen(true);
                            setModelTitle('新增线路');

                        }}
                    >
                        新增线路
                    </Button>,
                ]}


            />
            {/* 弹窗 */}
            <Modal
                maskClosable={false}
                key="01"
                width={800}
                title={<Tag color="#cd201f">{modelTitle}</Tag>}
                open={isModalOpen}
                onCancel={() => {
                    setIsModalOpen(false);
                }}

                footer={[
                    <Button
                        key="back"
                        onClick={() => {
                            setIsModalOpen(false);

                        }}
                    >
                        返回
                    </Button>,
                    <Button key="submit" form="agvlineForm" type="primary" htmlType="submit">
                        提交
                    </Button>,
                ]}
            >
                {/* 弹窗内的表单 */}
                <Form
                    form={typeForm}
                    name="line"
                    id="agvlineForm"
                    labelAlign='right'
                    // lCol={{ span: 4 }}
                    wrapperCol={{ span: 12 }}
                    onFinish={OnSubmit}
                    autoComplete="off"
                >
                    <Form.Item label="id" name="id" hidden>
                        <Input />
                    </Form.Item>


                    <Form.Item
                        label="线路名称"
                        name="name"
                        rules={[{ required: true, message: '此项为必填项!' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item label="线路编码" name="code" >
                        <Input />
                    </Form.Item>
                    <Form.Item label="起始点位" name="startPointId" rules={[{ required: true, message: '此项为必填项!' }]} >
                        <Select placeholder='请选择起始点位' style={{ width: 375 }}>
                            {
                                startoptin.map((item: MySelectType.Select) => {
                                    return <Select.Option value={item.key} key={item.key}>
                                        <span>{item.value}</span>
                                    </Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item label="结束点位" name="endPointId" rules={[{ required: true, message: '此项为必填项!' }]} >
                        <Select placeholder='请选择起始点位' style={{ width: 375 }}>
                            {
                                endoption.map((item: MySelectType.Select) => {
                                    return <Select.Option value={item.key} key={item.key}>
                                        <span>{item.value}</span>
                                    </Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item label="点位描述" name="description" rules={[{ required: true, message: '此项为必填项!' }]} >
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>

        </>
    )
}

export default Agvline

