import { ArrowLeftOutlined, LeftCircleOutlined, LeftSquareTwoTone, PlusOutlined } from '@ant-design/icons';
import {
    ActionType,
    ProColumns,
    ProForm,
    ProFormInstance,
} from '@ant-design/pro-components';
import {
    ProCard,
    ProTable,
} from '@ant-design/pro-components';
import { v4 as uuid } from 'uuid'
import { Button, Card, Col, Divider, Form, FormInstance, Input, message, Modal, Popconfirm, Row, Select, Space } from 'antd';
import { useState, useRef, useEffect } from 'react';
import { history } from '@umijs/max';
//引入接口
import deviceProductApi from '@/api/deviceInfo/services/deviceProduct'
import deviceProducFunctiontApi from '@/api/deviceInfo/services/deviceProductFunction'
import { uniqueId, values } from 'lodash';
import './index.less'

interface ParmForm {
    paramName: string,
    paramCode: string,
    paramType: number,
    paramUnit: string,
    id: string,
}


const ParmsTypeList = [{

    label: '数据',
    value: 0
},
{
    label: '数组',
    value: 1
}
]

export default () => {
    const [fromType, setFromType] = useState<any>('table')
    const ref = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    const [funcfromType, setFuncFromType] = useState<any>('table')
    const funcRef = useRef<ProFormInstance>();
    const funcActionRef = useRef<ActionType>();

    const [paramsForm] = Form.useForm();
    const [selectRow, setSelectRow] = useState<deviceProduct.output>();
    const [funcParams, setFuncParams] = useState<ParmForm[]>([]);

    //  useEffect(()=>{
    // console.log("funcParams");
    const [isParamsUnit, setIsParamsUnit] = useState<boolean>();

    //  },[funcParams])
    const [paramsModelOpen, setParamsModelOpen] = useState<boolean>(false);
    const [isfunc, setIsfunc] = useState<boolean>(false)

    const Reolod = () => {
        ref.current?.resetFields()
        actionRef.current?.reload()
    }
    const FuncReolod = () => {
        funcRef.current?.resetFields()
        funcActionRef.current?.reload()
    }
    const columns: ProColumns<deviceProduct.output>[] = [
        {
            title: '主键',
            dataIndex: 'id',
            formItemProps:{
                hidden:true
            },
            search: false,
        },
        {
            title: '名称',
            dataIndex: 'name',
            formItemProps:{
                rules:[{ required: true, message: '此项为必填项!' }]
            },
        },
        {
            title: '编码',
            dataIndex: 'code',
            formItemProps:{
                rules:[{ required: true, message: '此项为必填项!' }]
            },
            search: false,
        },
        {
            title: '描述',
            dataIndex: 'description',
            search: false,
        },
        {
            title: '操作',
            valueType: 'option',
            fixed:'right',
            render: (text, row) => [
                <Space key={+new Date() + Math.random()}>
                    <Button type='primary' size='small' onClick={() => {
                        setFromType('form')
                        ref.current?.setFieldsValue(row)
                    }} key={+new Date() + Math.random()} target="_blank" rel="noopener noreferrer">
                        编辑
                    </Button>
                    <Button type='primary' size='small' onClick={() => {
                        setIsfunc(true)
                        setSelectRow(row)
                        setFuncParams([])
                    }}>

                        设置功能

                    </Button>

                    <Popconfirm
                        key="del"
                        title="确定要删除此条数据吗？"
                        onConfirm={() => {

                            deviceProductApi.Del(row).then((res: MyResponse.Content) => {
                                if (res.statusCode === 200) {
                                    message.info("删除成功!");
                                    Reolod()
                                } else {
                                    message.error(res.errors);
                                }
                            })
                        }}
                        onCancel={() => {
                            message.info('已取消删除');
                        }}
                        okText="确认"
                        cancelText="关闭"
                    >
                        <Button type='primary' size='small' danger>
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ],
        },
    ];

    return (
        <>
            {!isfunc ?
                <>

                    <ProTable<deviceProduct.output>
                        columns={columns}
                        type={fromType as 'table'}
                        formRef={ref}
                        actionRef={actionRef}
                        cardBordered
                        bordered
                        scroll={{ x: true }}
                        rowClassName={(record: any, index: number, indent: number) => {
                            if (index % 2 === 0) {
                                return ''; // 偶数行的类名
                            } else {
                                return 'even-row-background'; // 奇数行的类名
                            }
                        }}
                        onSubmit={(params: any) => {
                            console.log(params);
                            if (fromType === 'form') {
                                if (params.id) {
                                    deviceProductApi.Update(params).then((res: MyResponse.Content) => {
                                        if (res.statusCode === 200) {
                                            message.info("更新成功!");
                                            setFromType('table')
                                            Reolod()
                                        } else {
                                            message.error(res.errors);
                                        }
                                    })
                                } else {
                                    deviceProductApi.Add(params).then((res: MyResponse.Content) => {
                                        if (res.statusCode === 200) {
                                            message.info("新增成功!");
                                            setFromType('table')
                                            Reolod()
                                        } else {
                                            message.error(res.errors);
                                        }
                                    })
                                }
                            }
                        }}
                        request={async (params = {}) => {
                            const jsonData: deviceProduct.queryPage = {
                                pageIndex: params.current || 1,
                                pageSize: params.pageSize || 10,
                                name: params.name || '',
                            };
                            const response = await deviceProductApi.PagedList(jsonData);
                            if (response.statusCode === 200) {
                                return {
                                    data: response.data.items,
                                    success: true,
                                    total: response.data.total,
                                };
                            } else {
                                return {
                                    data: [],
                                    success: false,
                                    total: 0,
                                };
                            }
                        }}
                        pagination={{
                            pageSize: 5,
                            showSizeChanger: false
                        }}
                        rowKey="id"
                        dateFormatter="string"
                        headerTitle="列表"
                        toolBarRender={() => [
                            <Button key="3" type="primary" onClick={() => {
                                setFromType('form');
                            }}>
                                <PlusOutlined />
                                新建
                            </Button>,
                        ]}
                        form={{
                            ignoreRules: true,// 自定义提交按钮的属性
                            submitter: {
                                onReset: () => {
                                    ref.current?.resetFields()
                                    setFromType("table")
                                },
                                searchConfig: { resetText: fromType === 'form' ? '返回' : '重置', submitText: fromType === 'form' ? '提交' : '查询' },
                            }
                        }}
                    />
                </>
                :
                <>
                    <ProCard bordered>
                        {isfunc ? <Button icon={<LeftCircleOutlined />} type='primary' size='middle' onClick={() => {
                            setIsfunc(false)
                        }}>{"返回产品列表"}</Button> : ""}
                    </ProCard>
                    <ProCard bordered>
                        <div>产品名称：{selectRow?.name}</div>
                        <div>产品描述：{selectRow?.description}</div>
                    </ProCard>
            
                        <ProTable<deviceProduct.output>
                            type={funcfromType as 'table'}
                            cardBordered
                            bordered
                            scroll={{ x: true }}
                            rowClassName={(record: any, index: number, indent: number) => {
                                if (index % 2 === 0) {
                                    return ''; // 偶数行的类名
                                } else {
                                    return 'even-row-background'; // 奇数行的类名
                                }
                            }}
                            headerTitle="列表"
                            formRef={funcRef}
                            actionRef={funcActionRef}
                            search={false}
                            columns={[
                                {
                                    title: '功能主键',
                                    dataIndex: 'id',
                                    search: false,
                                    formItemProps: {
                                        hidden: true
                                      },
                                    readonly: true,
                                },
                                {
                                    title: '功能名称',
                                    dataIndex: 'name',
                                    ellipsis: true,
                                    search: false,
                                },
                                {
                                    title: '功能编码',
                                    hideInDescriptions: true,
                                    dataIndex: 'code',
                                    search: false,
                                }, {
                                    title: '输入参数',
                                    hideInDescriptions: true,
                                    hideInTable: true,
                                    dataIndex: "params",
                                    search: false,
                                    renderFormItem(schema, config, form, action?) {
                                        // let b = JSON.parse(config?.record!.params);
                                        return (
                                            <div>
                                                {funcParams.map((res: ParmForm, index: number) => (
                                                    <Row key={+new Date() + Math.random()} style={{ borderBottom: "0.5px solid #f3e0e0", margin: "10px" }}>
                                                        <Space split={<Divider type="vertical" />}>
                                                            <div>参数名称：{res.paramName}</div>
                                                            <div>参数代码：{res.paramCode}</div>
                                                            <Button type='link' onClick={() => {
                                                                setParamsModelOpen(true)
                                                                setTimeout(() => {
                                                                    paramsForm.setFieldsValue(funcParams[index]);
                                                                }, 100);
                                                            }}>设置</Button>
                                                            <Button type='link' onClick={() => {
                                                                const newData = [...funcParams];
                                                                newData.splice(index, 1);
                                                                setTimeout(() => {
                                                                    setFuncParams(newData);
                                                                }, 100);
                                                            }}>删除</Button>
                                                        </Space>
                                                    </Row>
                                                )
                                                )}
                                                <Button type='link' onClick={() => {
                                                    paramsForm.resetFields();
                                                    setParamsModelOpen(true)
                                                }}>+增加参数</Button>
                                                <Modal
                                                    maskClosable={false} destroyOnClose title="设置参数" footer={false} onCancel={() => setParamsModelOpen(false)} open={paramsModelOpen}>
                                                    <ProForm form={paramsForm} id="paramsForm"
                                                        onFinish={async (values) => {
                                                            console.log(values);
                                                            const b = paramsForm.getFieldsValue();
                                                            if (b.id) {
                                                                funcParams.forEach((res) => {
                                                                    if (res.id === b.id) {
                                                                        res.paramCode = b.paramCode;
                                                                        res.paramName = b.paramName;
                                                                        res.paramType = b.paramType;
                                                                        res.paramUnit = b.paramUnit;
                                                                    }
                                                                })
                                                                setFuncParams(funcParams);
                                                            } else {
                                                                b.id = uuid()
                                                                funcParams.push(b);
                                                            }
                                                            setFuncParams(funcParams);
                                                            console.log(b);
                                                            setParamsModelOpen(false)

                                                        }}>
                                                        <Form.Item label="主键" hidden name="id">
                                                            <Input></Input>
                                                        </Form.Item>
                                                        <Form.Item label="参数名称" name="paramName" rules={[{ required: true, message: '此项为必填项!' }]}>
                                                            <Input></Input>
                                                        </Form.Item>
                                                        <Form.Item label="参数代码" name="paramCode" rules={[{ required: true, message: '此项为必填项!' }]}>
                                                            <Input></Input>
                                                        </Form.Item>
                                                        <Form.Item label="参数类型" name="paramType" rules={[{ required: true, message: '此项为必填项!' }]}>
                                                            <Select onChange={(value) => {
                                                                if (value === 0) {
                                                                    setIsParamsUnit(false)
                                                                } else {
                                                                    setIsParamsUnit(true)
                                                                }
                                                            }} placeholder="选择数据类型" options={ParmsTypeList}>

                                                            </Select>
                                                        </Form.Item>
                                                        <Form.Item label="参数单位" hidden={isParamsUnit} name="paramUnit" rules={[{ required: !isParamsUnit, message: '此项为必填项!' }]}>
                                                            <Input></Input>
                                                        </Form.Item>
                                                    </ProForm>
                                                </Modal>
                                            </div>
                                        )
                                    },

                                },
                                {
                                    title: '描述',
                                    dataIndex: 'description',
                                    search: false,
                                },
                                {
                                    title: '操作',
                                    valueType: 'option',
                                    dataIndex: 'id',
                                    fixed:'right',
                                    render: (text, row) => [
                                        <Space key={+new Date() + Math.random()}>
                                            <a onClick={() => {
                                                setFuncFromType('form')
                                                console.log('row', row);
                                                setTimeout(() => {
                                                    funcRef.current?.setFieldsValue(row)
                                                    if (row.params) {
                                                        const ppp = JSON.parse(row.params)
                                                        setFuncParams(ppp)
                                                    } else {
                                                        setFuncParams([])
                                                    }

                                                }, 200);

                                            }} key={+new Date() + Math.random()} target="_blank" rel="noopener noreferrer">
                                                编辑
                                            </a>
                                            <Popconfirm
                                                key="del"
                                                title="确定要删除此条数据吗？"
                                                onConfirm={() => {

                                                    deviceProducFunctiontApi.Del(row).then((res: MyResponse.Content) => {
                                                        if (res.statusCode === 200) {
                                                            message.info("删除成功!");
                                                            Reolod()
                                                        } else {
                                                            message.error(res.errors);
                                                        }
                                                    })
                                                }}
                                                onCancel={() => {
                                                    message.info('已取消删除');
                                                }}
                                                okText="确认"
                                                cancelText="关闭"
                                            >
                                                <a>
                                                    删除
                                                </a>
                                            </Popconfirm>
                                        </Space>
                                    ],
                                },
                            ]}
                            onSubmit={(params: any) => {
                                console.log(params, funcParams);
                                params.params = JSON.stringify(funcParams);
                                params.deviceProductId = selectRow?.id
                                if (funcfromType === 'form') {
                                    if (params.id) {
                                        deviceProducFunctiontApi.Update(params).then((res: MyResponse.Content) => {
                                            if (res.statusCode === 200) {
                                                message.info("更新成功!");
                                                setFuncFromType('table')
                                                FuncReolod()
                                            } else {
                                                message.error(res.errors);
                                            }
                                        })
                                    } else {
                                        deviceProducFunctiontApi.Add(params).then((res: MyResponse.Content) => {
                                            if (res.statusCode === 200) {
                                                message.info("新增成功!");
                                                setFuncFromType('table')
                                                FuncReolod()
                                            } else {
                                                message.error(res.errors);
                                            }
                                        })
                                    }
                                }
                            }}
                            request={async (params = {}) => {
                                const jsonData: deviceProductFunction.queryPage = {
                                    pageIndex: params.current || 1,
                                    pageSize: params.pageSize || 10,
                                    deviceProductId: selectRow?.id
                                };
                                const response = await deviceProducFunctiontApi.PagedList(jsonData);
                                if (response.statusCode === 200) {
                                    return {
                                        data: response.data.items,
                                        success: true,
                                        total: response.data.total,
                                    };
                                } else {
                                    return {
                                        data: [],
                                        success: false,
                                        total: 0,
                                    };
                                }
                            }}
                            form={{
                                ignoreRules: true,// 自定义提交按钮的属性
                                submitter: {
                                    onReset: () => {
                                        funcRef.current?.resetFields();
                                        setFuncFromType("table")
                                    },
                                    searchConfig: { resetText: funcfromType === 'form' ? '返回' : '重置', submitText: funcfromType === 'form' ? '提交' : '查询' },
                                }
                            }}
                            pagination={{
                                pageSize: 5,
                                showSizeChanger: false
                            }}
                            rowKey="id"
                            dateFormatter="string"

                            toolBarRender={() => [
                                <Button key="3" type="primary" onClick={() => {
                                    setFuncFromType('form');
                                    setFuncParams([])
                                }}>
                                    <PlusOutlined />
                                    添加功能
                                </Button>,
                            ]}
                        />
                 
                </>
            }
        </>
    );
};