/**
 * 工单基础信息管理
 * @param Page
 * @returns
 */
import type {
    ActionType, ProColumns,
    EditableFormInstance,
    ProFormInstance,
} from '@ant-design/pro-components';
import type { TableColumnsType } from 'antd';
import { ProTable } from '@ant-design/pro-components';
import { Button, Popconfirm, message, Modal, Form, Input, Space, Select, Table, Descriptions } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import {
    EditableProTable,
    ProCard,
    ProForm,
    ProFormField,
    ProFormRadio,
} from '@ant-design/pro-components';

type materialSelctType = {
    title: string;
    value: string;
};

import OrderService from '@/api/orderService';
import ProductLineAPI from '@/api/productlineService';
import FinalAPI from '@/api/finalService';
import { json } from 'express';
import { set } from 'lodash';


export default () => {
    const actionRef = useRef<ActionType>();
    const [modelTitle, setModelTitle] = useState<string>("创建订单");
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
    const [isWorkModalOpen, setIsWorkModalOpen] = useState<boolean>(false);
    const [form] = Form.useForm();
    const [form2] = Form.useForm();
    const [isRead, setIsRead] = useState<boolean>(false);

    const [materialSelect, setMaterialSelect] = useState<MaterialSelectType[]>([]);
    //产线
    const [productionSelect, setProductionSelect] = useState<MaterialSelectType[]>([]);
    //成品
    const [productSelect, setProductSelect] = useState<MaterialSelectType[]>([]);

    const [orderMaterial, setOrderMaterial] = useState<OrderType.FormFinalsl>();
    const columns: ProColumns<OrderType.Info>[] = [
        {
            title: '工单编码',
            dataIndex: 'id',
            hideInSearch: true,
            align: 'center',
        },
        {
            title: '状态',
            dataIndex: 'status',
            ellipsis: true,
            align: 'center',
            valueEnum: {
                0: {
                    text: '未开始',
                    status: 'error',
                },
                1: {
                    text: '进行中',
                    status: 'Processing',
                },
                2: {
                    text: '完成',
                    status: 'Success',
                },
            },

        },
        //  {
        //     title: '分配进度',
        //     dataIndex: 'allocationRate',
        //     ellipsis: true,
        //     align: 'center',

        // }, 
        {
            title: '生产进度',
            dataIndex: 'produceRate',
            hideInSearch: true,
            render: (_, record) => (
                <p>{record.produceRate}/{record.produceSum}</p>
            ),

        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            ellipsis: true,
            hideInSearch: true,
            align: 'center',

        }, {
            title: '操作',
            valueType: 'option',
            key: 'option',
            width: 300,
            render: (_, record) => [
                <Button
                    key="look"
                    type="primary" ghost
                    onClick={async () => {
                        const res = await OrderService.GetorderMaterial(record.id);
                        let data: OrderType.FormFinalsl = {
                            id: record.id,
                            finalsl: JSON.parse(JSON.stringify(res.data))
                        }
                        form.setFieldsValue(JSON.parse(JSON.stringify(data)));
                        setOrderMaterial(data);
                        setModelTitle("查看订单详情");
                        setIsRead(true);
                        setIsModalOpen(true);
                    }}
                >
                    查看
                </Button>,
                <Button
                    key="edit"
                    disabled={record.status != 0}
                    type="primary" ghost
                    onClick={async () => {
                        const res = await OrderService.GetorderMaterial(record.id);
                        let data: OrderType.FormFinalsl = {
                            id: record.id,
                            finalsl: JSON.parse(JSON.stringify(res.data))
                        }
                        form.setFieldsValue(JSON.parse(JSON.stringify(data)));
                        setOrderMaterial(data);
                        setModelTitle(orderMaterial?.id ? "新建订单" : "修改订单");
                        setIsRead(false);
                        setIsModalOpen(true);

                    }}
                >
                    编辑
                </Button>,
                <Button
                    key="generate"
                    disabled={record.status != 0}
                    type="primary" ghost
                    onClick={async () => {
                        const res = await OrderService.GetorderMaterial(record.id);
                        let data: OrderType.FormFinalsl = {
                            id: record.id,
                            finalsl: JSON.parse(JSON.stringify(res.data))
                        }
                        form2.setFieldsValue(JSON.parse(JSON.stringify(data)));
                        setIsWorkModalOpen(true);
                    }}
                >
                    生成工单
                </Button>,
                <Popconfirm
                    disabled={record.status != 0}
                    key="del"
                    title="确定要删除此条数据吗？"
                    onConfirm={async () => {

                        const res = await OrderService.del(record.id);
                        if (res.data) {
                            message.success('删除成功');
                            actionRef.current?.reload();
                            setIsModalOpen(false);
                        } else {
                            message.error(res.errors || '删除失败');
                        }

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



    //提交
    const Submit = async (data: OrderType.FormFinalsl) => {
        if (data.id) {
            data.finalsl.map((item) => {
                item.OrderId = data.id;
            });
            const res = await OrderService.update(data.finalsl);
            if (res.data) {
                message.success('修改成功');
                actionRef.current?.reload();
                setIsModalOpen(false);
            } else {
                message.error(res.errors || '修改失败');
            }

        } else {
            const res = await OrderService.Add(data.finalsl);
            if (res.data) {
                message.success('添加成功');
                actionRef.current?.reload();
                setIsModalOpen(false);
            } else {
                message.error(res.errors || '添加失败');
            }
        }

    }

    //提交
    const SubmitFinalsl = async (data: OrderType.FormFinalsl) => {
        const res = await OrderService.orderassociationwork(data.finalsl);
        if (res.data) {
            message.success('添加成功');
            actionRef.current?.reload();
            setIsWorkModalOpen(false);
        } else {
            message.error(res.errors || '添加失败');
        }

    }


    interface ExpandedDataType {
        key: React.Key;
        date: string;
        name: string;
        upgradeNum: string;
    }

    const expandedRowRender = (data: OrderType.Info) => {
        var res = data.orderInfos;
        return (
            <ProTable
                columns={[
                    { title: '工单编码', dataIndex: 'id', key: 'id' },
                    { title: '线路名称', dataIndex: 'productionLineName', key: 'productionLineName' },
                    { title: '线路ID', hideInTable: true, dataIndex: 'productionLineId', key: 'productionLineId' },
                    { title: '成品名称', dataIndex: 'finalslName', key: 'finalslName' },
                    { title: '成品Id', hideInTable: true, dataIndex: 'finalslId', key: 'finalslId' },
                    { title: '产量', dataIndex: 'number', key: 'number' },
                    {
                        title: '状态', dataIndex: 'status', key: 'status', valueEnum: {
                            0: {
                                text: '草稿',
                                status: 'error',
                            },
                            1: {
                                text: '已下发',
                                status: 'Processing',
                            },
                            2: {
                                text: '已接受',
                                status: 'Processing',
                            },
                            3: {
                                text: '已启动',
                                status: 'Processing',
                            },
                            4: {
                                text: '已完成',
                                status: 'Success',
                            },
                            5: {
                                text: '废弃',
                                status: 'error',
                            },
                        },
                    },
                    { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
                ]}
                headerTitle={false}
                search={false}
                options={false}
                dataSource={res}
                pagination={false}
            />
        );
    };



    type MaterialSelectType = {
        key: string,
        value: string,
    }

    //初始化
    useEffect(() => {
        ProductLineAPI.selectlist().then((res: MyResponse.Content) => {
            if (res.statusCode === 200) {
                setProductionSelect(res.data)
            }
        })

        FinalAPI.SelectList().then((res: MyResponse.Content) => {
            if (res.statusCode === 200) {
                setProductSelect(res.data)
            }
        })


    }, [])


    return (
        <>
            <ProTable<OrderType.Info>
                key="myTable"
                columns={columns}
                actionRef={actionRef}
                cardBordered
                expandable={{ expandedRowRender }}
                request={async (params = {}) => {

                    const jsonData: OrderType.Page = {
                        pageIndex: params.current || 1,
                        pageSize: params.pageSize || 10,
                        status: params.status,
                        id: params.id,
                        AllocationRate: 0,
                        produceRate: 0,
                        CreateTime: ''
                    };

                    const response = await OrderService.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="订单列表"
                toolBarRender={() => [
                    <Button
                        key="button"
                        type="primary"
                        onClick={() => {
                            form.resetFields();
                            setModelTitle(orderMaterial?.id ? "修改订单" : "新建订单");
                            setIsRead(false);
                            setIsModalOpen(true);

                        }}
                    >
                        新建订单
                    </Button>,
                ]}
            />

            {/* 订单创建修改*/}
            <Modal
                maskClosable={false} title={modelTitle} open={isModalOpen} width={800}
                destroyOnClose={true}
                okButtonProps={{ disabled: isRead }}
                cancelButtonProps={{ disabled: isRead }}
                onOk={() => {
                    form.submit();
                }}
                onCancel={() => { setIsModalOpen(false) }}>
                <Form
                    form={form}
                    onFinish={Submit}
                    style={{ maxWidth: 800 }}
                    autoComplete="off"
                >
                    <Form.Item name="id" hidden={true}>
                        <Input />
                    </Form.Item>
                    <Form.List name="finalsl"  >
                        {(fields, { add, remove }) => (
                            <>
                                {fields.map(({ key, name, ...restField }) => (
                                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                        <Form.Item
                                            shouldUpdate={true}
                                        >
                                            {() => (
                                                <Form.Item
                                                    {...restField}
                                                    label="成品"
                                                    name={[name, 'finalslId']}
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请选择成品',
                                                        },
                                                    ]}
                                                >
                                                    <Select style={{ width: 400, }}  >
                                                        {productSelect.map((item) => (
                                                            <Select.Option key={item.key} value={item.key}>
                                                                {item.value}
                                                            </Select.Option>
                                                        ))}
                                                    </Select>
                                                </Form.Item>
                                            )}
                                        </Form.Item>

                                        <Form.Item
                                            {...restField}
                                            label="数量"
                                            name={[name, 'number']}
                                            labelCol={{ span: 8 }}
                                            rules={[{ required: true, message: '请输入数量！', },]}
                                        >
                                            <Input type="number" style={{ width: '110px' }} />
                                        </Form.Item>
                                        <MinusCircleOutlined hidden={isRead} onClick={() => remove(name)} />
                                    </Space>
                                ))}
                                <Form.Item>
                                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                        添加产品
                                    </Button>
                                </Form.Item>
                            </>
                        )}
                    </Form.List>
                </Form>
            </Modal>

            {/* 生成工单 */}
            <Modal
                maskClosable={false} title={"生成工单"} open={isWorkModalOpen} width={800}
                destroyOnClose={true}
                forceRender
                onOk={() => {
                    form2.submit();
                }}
                onCancel={() => { setIsWorkModalOpen(false) }}>

                <Form
                    form={form2}
                    onFinish={SubmitFinalsl}
                    style={{ maxWidth: 800 }}
                    autoComplete="off"
                >
                    <Form.Item name="id" hidden={true}>
                        <Input />
                    </Form.Item>
                    <Form.List name="finalsl"  >
                        {(fields, { add, remove }) => (
                            <>
                                {fields.map(({ key, name, ...restField }) => (
                                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                        <Form.Item
                                            shouldUpdate={true}
                                        >
                                            {() => (
                                                <Form.Item
                                                    {...restField}
                                                    label="成品"
                                                    name={[name, 'finalslId']}
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请选择成品',
                                                        },
                                                    ]}
                                                >
                                                    <Select style={{ width: 200, }}  >
                                                        {productSelect.map((item) => (
                                                            <Select.Option key={item.key} value={item.key}>
                                                                {item.value}
                                                            </Select.Option>
                                                        ))}
                                                    </Select>
                                                </Form.Item>
                                            )}
                                        </Form.Item>
                                        <Form.Item
                                            shouldUpdate={true}
                                        >
                                            {() => (
                                                <Form.Item
                                                    {...restField}
                                                    label="产线"
                                                    name={[name, 'ProductionLineId']}
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请选择产线',
                                                        },
                                                    ]}
                                                >
                                                    <Select style={{ width: 200, }}  >
                                                        {productionSelect.map((item) => (
                                                            <Select.Option key={item.key} value={item.key}>
                                                                {item.value}
                                                            </Select.Option>
                                                        ))}
                                                    </Select>
                                                </Form.Item>
                                            )}
                                        </Form.Item>


                                        <Form.Item
                                            {...restField}
                                            label="数量"
                                            name={[name, 'number']}
                                            labelCol={{ span: 8 }}
                                            rules={[{ required: true, message: '请输入数量！', },]}
                                        >
                                            <Input type="number" style={{ width: '110px' }} />
                                        </Form.Item>
                                        <MinusCircleOutlined hidden={isRead} onClick={() => remove(name)} />
                                    </Space>
                                ))}
                                <Form.Item>
                                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                        添加产品
                                    </Button>
                                </Form.Item>
                            </>
                        )}
                    </Form.List>
                </Form>

            </Modal>

        </>
    );
};
