/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable array-callback-return */
// 产线管理

import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Upload, UploadProps, Spin, Tag, Col, Divider, Row, Card, Space, Select } from 'antd';
import { useEffect, useRef, useState } from 'react';
import RecipeInfoAPI from '@/api/recipeService'
// import MaterialsInfoAPI from '@/api/materialService'
import { dictDataApi } from '@/api/dictType/service'
import DeviceInfoAPI from '@/api/DeviceInfo'
// 料仓接口
import StockInfoAPI from '@/api/StockService';
import ProductlineInfoAPI from '@/api/productlineService'
import { RedoOutlined, PlusSquareOutlined, EditOutlined } from '@ant-design/icons';
import styles from './index.less'
// import { values } from 'lodash';
const Index = () => {
    //表单
    const [typeForm] = Form.useForm();
    // 料仓表单
    const [binForm] = Form.useForm()

    //编辑/新增弹窗
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalGroupOpen, setIsModalGroupOpen] = useState(false);
    const [are, setare] = useState([])
    // 设备变量
    const [devicestatus, setdevicestatus] = useState([])
    // 料仓变量

    const [stockstatus, setstockstatus] = useState([])

    // 料仓弹窗
    const [binModelopen, setbinModelopen] = useState(false)
    //    产线变量
    const [producLine, setProducline] = useState([])


    const [isModalGroupFormOpen, setIsModalGroupFormOpen] = useState(false);
    const [selectGroup, setSelectGroup] = useState(0)
    // 当前产线
    const [currentproductionline, setcurrentproductionline] = useState<ProductlineTypes.Info>()
    const [recipeparams, setRecipeparams] = useState<any>();

    const [GroupList, setGroupList] = useState<ProductlineTypes.Info[]>([{
        id: '',
        name: '',
        describe: '',
        code: '',
        des: ''
    }]);

    const actionRef = useRef<ActionType>();
    // const [formRef] = Form.useForm();

    const [groupForm] = Form.useForm();
    const [ProductlineEditForm] = Form.useForm();
    // 设备下拉
    useEffect(() => {

        const device = async () => {
            const deviceList = await DeviceInfoAPI.selectlist()
            // 设备的数组
            // console.log(deviceList);
            setdevicestatus(deviceList.data)
        }
        device()

        // 料仓下拉
        const stock = async () => {
            const stockList = await StockInfoAPI.selectlist()
            // 料仓的数组
            // console.log(stockList);
            setstockstatus(stockList.data)

        }
        stock()


        //产线
        ProductlineInfoAPI.selectlist().then((res: MyResponse.Content) => {
            if (res.statusCode === 200) {
                setProducline(res.data)
            }
        })




    }, [])






    //设备成功方法
    const OnSubmit = async (values: DeviceTypes.deviceBinAddInput) => {
        // console.log(values);

        // values.picUrl = imageUrl!;
        if (values.id) {
            const response = await DeviceInfoAPI.Update(values);
            if (response.statusCode === 200) {
                message.success('修改成功');
                actionRef.current?.reload();
                setIsModalOpen(false);
            } else {
                message.error(response.errors || '修改失败');
            }
        } else {


            // 属性
            const property: ProductlineTypes.Productlinedevice = {
                deviceId: values.deviceId,
                lineId: values.lineId
            }
            const response = await ProductlineInfoAPI.adddevice(property);
            console.log(response);

            if (response.statusCode === 200) {
                message.success('添加成功');

                actionRef.current?.reload();
                setIsModalOpen(false);
            } else {
                message.error(response.errors || '添加失败');
            }
        }
    }

    // 料仓成功

    const submission = async (values: StockTypes.StockInfoOutput) => {
        // values.picUrl = imageUrl!;
        if (values.id) {
            const response = await StockInfoAPI.Update(values);
            // console.log(response);

            if (response.statusCode === 200) {
                message.success('修改成功');

                actionRef.current?.reload();
                setbinModelopen(false);
            } else {
                message.error(response.errors || '修改失败');
            }
        } else {

            const ac: ProductlineTypes.Productlinestock = {
                stockId: values.stockId,
                lineId: values.lineId
            }
            const response = await ProductlineInfoAPI.addstock(ac);
            console.log(response);



            if (response.statusCode === 200) {
                message.success('添加成功');
                actionRef.current?.reload();
                setbinModelopen(false);
            } else {
                message.error(response.errors || '添加失败');
            }
        }
    }



    //表单名
    const columns: ProColumns<DeviceTypes.DeviceInfoOutput>[] = [
        {
            title: 'id',
            dataIndex: 'id',
            tip: '规则名称是唯一的 key',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '设备名称',
            dataIndex: 'deviceName',
            width: 200,
            align: 'center',
            hideInSearch: true,

        },
        {
            title: '当前产线',
            width: 200,
            dataIndex: 'lineId',
            hideInSearch: true,
            renderText(text, record) {

                return <>{GroupList.find(x => x.id === record.lineId)?.name}</>
            },
            align: 'center',
        },
        {
            title: '设备类型',
            dataIndex: 'deviceType',
            align: 'center',
            width: 100,
            hideInSearch: true
        },
        {
            title: '操作',
            align: 'center',
            width: 40,
            valueType: 'option',


            key: 'option',
            render: (_, record) => [
                <Space key='nm' size="middle">

                    <Button
                        onClick={() => {
                            setIsModalGroupOpen(true)
                            const copyFormData = JSON.parse(JSON.stringify(record));
                            groupForm.setFieldsValue(copyFormData);
                        }}
                        key='fl' type='primary' ghost >修改产线</Button>
                    <Popconfirm
                        key="del"
                        title="确定要删除此条数据吗？"
                        onConfirm={() => {
                            const delData: ProductlineTypes.Productionlinedeletiondevice = {
                                id: record.id,
                                lineId: '',
                                deviceId: '',
                            };
                            ProductlineInfoAPI.deletedevice(delData).then((r: any) => {
                                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>
                </Space>
            ],
        },
    ];








    // 料仓列表
    const list: ProColumns<ProductlineTypes.Productionlinestockpaging>[] = [
        {
            title: 'id',
            dataIndex: 'id',
            tip: '规则名称是唯一的 key',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '料仓名称',
            dataIndex: 'stockName',
            width: 200,
            align: 'center',

        },
        {
            title: '料仓剩余',
            width: 200,
            dataIndex: 'des',
            align: 'center',
            hideInSearch: true,

        },
        {
            title: '当前产线',
            width: 200,
            dataIndex: 'lineId',
            hideInSearch: true,
            renderText(text, record) {
                return <>{GroupList.find(x => x.id === record.lineId)?.name}</>
            },
            align: 'center',
        },





        {
            title: '操作',
            align: 'center',
            width: 10,

            valueType: 'option',

            key: 'option',
            render: (_, record) => [
                <Space key='nm' size="middle">

                    <Button

                        onClick={() => {
                            setIsModalGroupOpen(true)
                            const copyFormData = JSON.parse(JSON.stringify(record));
                            groupForm.setFieldsValue(copyFormData);
                        }}
                        key='fl' type='primary' ghost  >修改产线</Button>


                    <Popconfirm
                        key="del"
                        title="确定要删除此条数据吗？"
                        onConfirm={() => {
                            const delData: ProductlineTypes.Productionlinedeletstock = {
                                id: record.id,

                                stockId: '',
                                lineId: '',
                            };
                            ProductlineInfoAPI.deletestock(delData).then((r: any) => {
                                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>
                </Space>
            ],
        },
    ];








    //    获取产线的数据
    const GetGroupList = () => {
        ProductlineInfoAPI.List().then((res: MyResponse.Content) => {
            if (res.statusCode === 200) {
                res.data.unshift(
                    {
                        code: '',
                        name: '全部',
                        describe: '',

                    }
                )
                setGroupList(res.data)
            }
        })
    }
    // 更新分组
    const OnGroupSubmit = (value: any) => {
        const jsonData: RecipeTypes.RecipesGroupInput = {
            GroupId: value.groupId,
            RecipesId: value.id
        }
        RecipeInfoAPI.ChangeGroup(jsonData).then((res: MyResponse.Content) => {
            if (res.statusCode === 200) {
                message.success("设置完成");
                setIsModalGroupOpen(false);
                actionRef.current?.reload();
            } else {
                message.error("设置失败");
            }
        });
    }
    // 修改分组数据
    const OnGroupEditSubmit = (value: ProductlineTypes.Info) => {
        if (value.id) {
            ProductlineInfoAPI.Update(value).then((res: MyResponse.Content) => {
                if (res.statusCode) {
                    message.success("修改成功");
                    setIsModalGroupFormOpen(false);
                    GetGroupList();
                } else {
                    message.success("修改失败");
                }
            })
        } else {
            ProductlineInfoAPI.Add(value).then((res: MyResponse.Content) => {
                if (res.statusCode) {
                    message.success("新增成功");
                    setIsModalGroupFormOpen(false);
                    GetGroupList();

                } else {
                    message.success("新增失败");
                }
            })
        }
        ProductlineEditForm.resetFields();
    }
    useEffect(() => {

        const areList = async () => {
            const jsonData: dictData.queryParms = {
                typeCode: "cxfz",
            }
            const data: MyResponse.Content = await dictDataApi.List(jsonData)
            // console.log(data);
            if (data.statusCode === 200) {
                const list: any[] = data.data
                list.map((res) => {
                    res.title = res.id
                })
            }
            setare(data.data)
        }
        areList();

        GetGroupList();
    }, [])

    useEffect(() => {
        const jsonData: RecipeTypes.Page = {
            pageIndex: 1,
            pageSize: 4,
            picUrl: '',
            id: '',
            code: '',
            groupId: GroupList[selectGroup].id === '-1' ? '' : GroupList[selectGroup].id
        };
        setRecipeparams(jsonData);
    }, [selectGroup])


    return (
        <>
            {
      /*
      * 产线
      */}
            <Row wrap={false} gutter={[10, 10]}>
                <Col flex={0.1}>
                    <Card>
                        <Space size="middle">
                            <Button type='primary'
                                onClick={() => {
                                    setIsModalGroupFormOpen(true)
                                    ProductlineEditForm.resetFields();
                                }}><PlusSquareOutlined /> 新增产线</Button>
                            <Button onClick={() => {
                                GetGroupList()
                            }}><RedoOutlined />刷新</Button>
                        </Space>
                        <Divider />
                        <div className={styles.tag}>
                            {GroupList.map((item, index) => (
                                <div key={index} onClick={() => {
                                    // 当前选中的产线
                                    console.log(item);
                                    setcurrentproductionline(item);
                                    setSelectGroup(index);


                                }} className={`${styles.tag_item} ${index === selectGroup ? styles.tag_item_activeItem : ''}`}>
                                    <Space size="middle">
                                        <div title={item.des}>{item.name}</div>
                                        {item.id === "-1" ? '' : <div className={styles.tag_item_editicon}><EditOutlined style={{ fontSize: '20px' }} title='修改名称' onClick={(e) => {
                                            e.stopPropagation();
                                            const copyFormData = JSON.parse(JSON.stringify(GroupList[index]));
                                            ProductlineEditForm.setFieldsValue(copyFormData);
                                            setIsModalGroupFormOpen(true)
                                        }} twoToneColor="#eb2f96"></EditOutlined></div>}
                                    </Space>
                                    <div className={index === selectGroup ? styles.tag_item_active : ''}></div>
                                </div>
                            ))}
                        </div>
                    </Card>
                </Col>
                <Col flex={4} >
                    {/* 设备分页列表 */}
                    <ProTable<DeviceTypes.Info>
                        key="myTable"
                        columns={columns}
                        actionRef={actionRef}


                        cardBordered
                        params={recipeparams}
                        request={async (params = {}) => {
                            // console.log('params', params);

                            const jsonData: ProductlineTypes.Productionlinepaging = {
                                pageIndex: params.current || 1,
                                pageSize: params.pageSize || 4,
                                name: params.name || '',
                                lineId: currentproductionline?.id

                            };



                            const response = await ProductlineInfoAPI.devicepagelist(jsonData);
                            // console.log(jsonData, '1111111111111');
                            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: 4,
                            showSizeChanger:false
                        }}
                        dateFormatter="string"
                        headerTitle="设备列表"
                        toolBarRender={() => [
                            <Button
                                // 当选择的为全部时禁用添加设备按钮
                                disabled={selectGroup.toString() === '0'}
                                key="button"
                                type="primary"
                                onClick={() => {
                                    typeForm.resetFields();
                                    setIsModalOpen(true);
                                }}
                            >
                                绑定设备
                            </Button>,
                        ]}
                    />
                    <Col style={{ height: 20 }}></Col>
                    {/* 料仓列表 */}
                    <ProTable<StockTypes.Info>
                        key="myTable2"
                        columns={list}
                        actionRef={actionRef}
                        cardBordered
                        params={recipeparams}
                        request={async (params = {}) => {
                            // console.log('params', params);

                            const jsonData: ProductlineTypes.Productionlinestockpaging = {
                                pageIndex: params.current || 1,
                                pageSize: params.pageSize || 4,
                                name: params.name || '',
                                id: params.id,
                                // code: params.code,

                                lineId: currentproductionline?.id
                            };
                            const response = await ProductlineInfoAPI.stockpagelist(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: 4,
                            showSizeChanger:false
                        }}
                        dateFormatter="string"
                        headerTitle="料仓列表"
                        toolBarRender={() => [
                            <Button
                                // 当选择的为全部时禁用添加料仓按钮
                                disabled={selectGroup.toString() === '0'}
                                key="button"
                                type="primary"
                                onClick={() => {
                                    binForm.resetFields();
                                    setbinModelopen(true);


                                }}
                            >
                                绑定料仓
                            </Button>,
                        ]}


                    />

                </Col>


            </Row>
            {
      /*
      * 设备绑定
      */}
            <Modal
                maskClosable={false}
                key="01"
                width={600}
                title={<Tag color="#cd201f">设备绑定</Tag>}
                open={isModalOpen}
                onCancel={() => {
                    setIsModalOpen(false);
                }}
                footer={[
                    <Button
                        key="back"
                        onClick={() => {
                            setIsModalOpen(false);
                        }}
                    >
                        返回
                    </Button>,
                    <Button key="submit" form="manufacturingForm" type="primary" htmlType="submit">
                        提交
                    </Button>,
                ]}
            >
                <Form
                    form={typeForm}
                    name="basic"
                    id="manufacturingForm"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 12 }}
                    onFinish={OnSubmit}
                    autoComplete="off"
                    //    显示当前产线
                    initialValues={{ 'lineId': currentproductionline?.id }}
                >
                    <Form.Item label="id" name="id" hidden>
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="设备名称"
                        // name="deviceID"
                        name="deviceId"
                        rules={[{ required: true, message: '此项必填！' }]}
                    >
                        <Select placeholder="下拉选择设备">
                            {
                                devicestatus.map((item: MySelectType.Select) => {
                                    return <Select.Option value={item.key} key={item.key}>
                                        <span>{item.value}</span>
                                    </Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item name="lineId" label="当前产线" >
                        <Select
                            placeholder="下拉选择产线"
                            allowClear
                            defaultValue="1"
                        >
                            {
                                producLine.map((item: MySelectType.Select) => {
                                    return <Select.Option value={item.key} key={item.key}>
                                        <span>{item.value}</span>
                                    </Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>



            {/* 料仓绑定 */}
            <Modal
                maskClosable={false}
                key="02"
                width={600}
                title={<Tag color="#cd201f">料仓绑定</Tag>}

                open={binModelopen}
                onCancel={() => {
                    setbinModelopen(false);
                }}
                footer={[
                    <Button
                        key="back2"
                        onClick={() => {
                            setbinModelopen(false);

                        }}
                    >
                        返回
                    </Button>,
                    <Button key="submit" form="binForm" type="primary" htmlType="submit">
                        提交

                    </Button>,
                ]}
            >
                <Form
                    form={binForm}
                    name="basic2"
                    id="binForm"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 12 }}
                    onFinish={submission}
                    autoComplete="off"
                    initialValues={{ 'lineId': currentproductionline?.id }}
                >
                    <Form.Item label="id" name="id" hidden>
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="料仓名称"
                        // name="name"
                        name="stockId"
                        rules={[{ required: true, message: '此项必填！' }]}
                    >
                        <Select placeholder='下拉选择料仓'>
                            {
                                stockstatus.map((item: MySelectType.Select) => {
                                    return <Select.Option value={item.key} key={item.key}>
                                        <span>{item.value}</span>
                                    </Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item name="lineId" label="当前产线" >
                        <Select
                            placeholder="下拉选择产线"

                            allowClear
                            defaultValue='1'

                        >
                            {
                                producLine.map((item: MySelectType.Select) => {
                                    return <Select.Option value={item.key} key={item.key}>
                                        <span>{item.value}</span>
                                    </Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
            {
      /*
      * 新增产线的弹框
      */}
            <Modal
                maskClosable={false}
                open={isModalGroupFormOpen}
                destroyOnClose
                title={<Tag color='#cd201f'>新增产线</Tag>}
                onCancel={() => {
                    ProductlineEditForm.resetFields();
                    setIsModalGroupFormOpen(false)
                }}
                footer={[
                    <Popconfirm
                        key="del"
                        title="确定要删除此条数据吗？"
                        onConfirm={() => {
                            // console.log('sss', ProductlineEditForm.getFieldValue('id'));
                            const delJosnData: ProductlineTypes.ProductlineInfoDelInput = {
                                id: ProductlineEditForm.getFieldValue('id'),
                                name: '',
                                des: ''
                            };
                            ProductlineInfoAPI.Del(delJosnData).then((res: MyResponse.Content) => {
                                if (res.statusCode === 200) {
                                    message.success("删除成功!");
                                    setIsModalGroupFormOpen(false);
                                    GetGroupList();
                                }
                            })
                        }}
                        onCancel={() => { }}
                    >
                        <Button
                            key="back"
                        // onClick={() => {
                        //   setIsModalGroupFormOpen(false)
                        // }}
                        >
                            删除产线
                        </Button>
                    </Popconfirm>,
                    <Button key="submit2" form="ProductlineEditForm" type="primary" htmlType="submit">
                        提交
                    </Button>,
                ]}
            >
                {/* 新增产线的表单 */}
                <Form
                    form={ProductlineEditForm}
                    name="basic"
                    id="ProductlineEditForm"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 12 }}
                    onFinish={OnGroupEditSubmit}
                    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="describe"
                        rules={[{ required: true, message: '此项必填！' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="产线分组"
                        name="code"
                        rules={[{ required: true, message: '此项必填！' }]}
                    >
                        <Select placeholder="请选择成品配方"
                            options={are}
                        />
                    </Form.Item>
                </Form>
            </Modal>
            {
      /*
      * 修改产线的弹框
      */}
            <Modal
                maskClosable={false} open={isModalGroupOpen}
                title={<Tag color='#cd201f'>修改产线</Tag>}
                centered
                onCancel={() => setIsModalGroupOpen(false)}
                destroyOnClose
                footer={[
                    <Button
                        key="back"
                        onClick={() => {
                            //   setIsModalOpen(false);
                            setIsModalGroupOpen(false)
                        }}
                    >
                        返回
                    </Button>,
                    <Button key="submit" form="manufacturingForm" type="primary" htmlType="submit">
                        提交
                    </Button>,
                ]}
            >
                <Divider />
                {/* 修改产线选择分类 */}
                <Form
                    form={groupForm}
                    id='manufacturingForm'
                    onFinish={OnGroupSubmit}
                >
                    <Form.Item name="id" hidden >

                    </Form.Item>
                    <Form.Item name="lineId" rules={[{ required: true, message: '此项为必填项!' }]}>
                        <Select placeholder='请选择分类'>
                            {GroupList.map((item) => {
                                if (item.id !== '-1') {
                                    return <Select.Option value={item.id} key={item.id}>
                                        <span>{item.name}</span>
                                    </Select.Option>
                                }
                            })}
                        </Select>
                    </Form.Item>
                </Form>
                <Divider />
            </Modal>
        </>
    )
}
export default Index;
