import moment from 'moment';
import { connect } from 'umi';
import { useRef, useState } from 'react';
import useRequest from '@ahooksjs/use-request';
import ProTable, { EditableProTable } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, Drawer, message, Popconfirm, Row, Space, Image, Modal, Form, Switch, Upload, Typography } from 'antd';
import { ModalForm, ProFormDatePicker, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from '@ant-design/pro-form';

import type { CurrentUser } from 'umi';
import type { FormInstance } from 'antd';
import type { ConnectState } from '@/models/connect';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { UploadFile } from 'antd/es/upload/interface';
import type { PictureModel } from '@/services/options/typings';

import { getQualificationList, delQualification, updateQualification, getQualificationDetail, relateBusinessCommodity } from './service';
import { getSupplierList } from '../Management/service';
import { deleteAHYDPicture, deletePicture, uploadAHYDPicture, uploadPicture } from '@/services/picture';
import { getFieldEnum } from '@/services/options';
import { transferImg } from '@/utils/format';
import { getBase64 } from '@/utils/utils';

import type { QualificationModel, RTQCBModel } from './data';
import type { CommdityLocalModel } from '../../commodity/BaseInfo/data';

import SelectCommdity from '@/pages/merchantManagement/commodity/BaseInfo/components/SelectCommdity';
import React from 'react';
import Draggable from 'react-draggable';
import { getCommodityList } from '../../commodity/BaseInfo/service';

const { confirm } = Modal;

// 删除资质数据
// const handelDelete = async (supplierid: number) => {
//     const hide = message.loading('正在删除...');
//     try {
//         const result = await delQualification(supplierid);

//         hide();
//         if (result.Result_Code !== 100) {
//             message.error(`${result.Result_Code !== 100}:删除失败`);
//             return false;
//         }
//         message.success('删除成功！');
//         return true;
//     } catch (error) {
//         hide();
//         message.error('删除失败');
//         return false;
//     }
// };

// 更新资质数据
const handleAddUpdate = async (fields: QualificationModel, commodityIds: string,
    staffId: number | undefined, staffName: string | undefined) => {
    const hide = message.loading('正在提交...');
    const result = await updateQualification(fields);
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`);
        return false;
    }

    if (commodityIds && commodityIds.split(',').length > 0) {
        const rtResult = await relateBusinessCommodity({
            QualificationId: result.Result_Data.QUALIFICATION_ID,
            CommodityIds: commodityIds,
            StaffId: staffId, StaffName: staffName
        } as RTQCBModel)
        if (rtResult.Result_Code !== 100) {
            message.error(`${rtResult.Result_Desc}` || `${rtResult.Result_Code}:提交失败`);
            return false;
        }
    }
    hide();
    message.success(fields.QUALIFICATION_ID ? '更新成功！' : '新建成功！');
    return result.Result_Data;
};

// 上传资质图片
const customUploadRequest = async (fileList: UploadFile[], tableId: string) => {
    if (!fileList.length) {
        message.error("您上传的图片不存在.")
        return false
    }
    const formData = new FormData();
    fileList.forEach(file => {
        formData.append('files[]', file);
    });

    formData.append('TableName', 'QUALIFICATION');
    formData.append('TableId', tableId);
    const success = await uploadAHYDPicture(formData)
    if (success) {
        return true
    }
    return false
}

/**
 * @description: 资质管理
 * @param {currentUser} 用户信息
 * @return {CommdityTable}  页面组件
 */
const CommdityTable: React.FC<{ currentUser?: CurrentUser }> = ({ currentUser }) => {
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const rtCommodityFormRef = useRef<FormInstance>();
    const [currentRow, setCurrentRow] = useState<QualificationModel>();
    const [showDetail, setShowDetail] = useState<boolean>();
    const [modalVisible, handleModalVisible] = useState<boolean>();
    const [priviewImage, setPriviewImage] = useState<string>(); // 预览的图片地址
    const [fileList, setFileList] = useState<UploadFile[]>([]); // 需要上传的资质图片列表
    const nowFilterDate = {
        1: [moment(), moment().add(1, 'months')],
        2: [moment(), moment().add(3, 'months')],
        3: [moment(), moment().add(6, 'months')]
    }
    const [selectCommdityVisible, setSelectCommdityVisible] = useState<boolean>(false);
    const [editCommdity, setEditCommdity] = useState<CommdityLocalModel[]>([]); // 需要关联资质的商品
    const [editableKeys, setEditableRowKeys] = useState<React.Key[]>();

    const [qualificationId, setQualificationId] = useState<number>();
    const [modalRTVisible, handleModalRTVisible] = useState<boolean>();
    // 拖动
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<any>()

    const onDraggaleStart = (event, uiData) => {

        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };
    // 拖动结束

    // const [priviewFileList, setPriviewFileList] = useState<UploadFile[]>([]); // 预览资质图片列表
    // 获取供应商列表
    const { loading, data: supplierList } = useRequest(async () => {
        const data = await getSupplierList({ OWNERUNIT_ID: currentUser?.BusinessManID, current: 1, pageSize: 9999, SUPPLIER_STATE: 1 })
        return data?.data ? data?.data.reduce((p: any, c: { SUPPLIER_NAME: any; SUPPLIER_ID: any; }) => { // 格式化供应商数据为 下拉选择使用的数据
            return [...p, {
                label: c.SUPPLIER_NAME,
                value: c.SUPPLIER_ID,
                // state: c.SUPPLIER_STATE
            }]
        }, []) : []
    })
    // 获取详情
    const getDetail = async (record: QualificationModel) => {
        const data = await getQualificationDetail(record?.QUALIFICATION_ID)
        const files = data?.ImgList ? data?.ImgList.map((n: PictureModel) => {
            return {
                uid: n.ImageId,
                name: n.ImageName,
                status: 'done',
                url: n.ImageUrl,
                deletepath: n.ImagePath
            }
        }) : []
        // setPriviewFileList(files)
        setFileList(files)
        return data
    }

    const columns: ProColumns<QualificationModel>[] = [
        {
            dataIndex: 'QUALIFICATION_NAME',
            title: '资质名称',
            hideInDescriptions: true,
            hideInSearch: true,
            render: (_, record) => {
                return <a onClick={async () => {
                    setCurrentRow(await getDetail(record));
                    setShowDetail(true);
                }}>{_}</a>
            }
            // width: '15%',
        },
        {
            dataIndex: 'QUALIFICATION_DESC',
            title: '资质说明',
            hideInSearch: true,
        },
        {
            dataIndex: 'SUPPLIER_ID',
            title: '供应商名称',
            valueType: 'select',
            fieldProps: {
                showSearch: true,
                options: !loading ? supplierList : []
            }
        },
        {
            dataIndex: 'QUALIFICATION_TYPE',
            title: '资质类型',
            align: 'center',
            valueType: 'select',
            request: async () => {
                return await getFieldEnum({ FieldExplainField: 'QUALIFICATION_TYPE' })
            }
        },
        {
            dataIndex: 'ISSUING_DATE',
            title: '签发日期',
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                if (record?.ISSUING_DATE) {
                    return moment(record?.ISSUING_DATE).format('YYYY-MM-DD')
                }
                return _
            }
        },
        {
            dataIndex: 'QUALIFICATION_ENDDATE',
            title: '有效期至',
            align: 'center',
            sorter: true,
            hideInSearch: true,
            valueType: 'date',
            render: (_, record) => {
                if (record?.QUALIFICATION_ENDDATE && record?.QUALIFICATION_ENDDATE.toString() !== '') {
                    // 资质到期时间在一个月内，内容标红显示
                    if (moment().add(1, 'month').diff(moment(record?.QUALIFICATION_ENDDATE)) > 0 &&
                        moment(record?.QUALIFICATION_ENDDATE).diff(moment().format('YYYY/MM/DD')) >= 0) {
                        return <Space style={{ color: '#FD4B54' }}>{_}</Space>
                    }
                    // 资质已过期，则置灰显示
                    if (moment(record?.QUALIFICATION_ENDDATE).diff(moment().format('YYYY/MM/DD')) < 0) {
                        return <Space style={{ color: '#d9d9d9' }}>{_}</Space>
                    }
                }
                return _
            }
        },
        {
            dataIndex: 'QUALIFICATION_ENDDATE',
            title: '到期',
            align: 'center',
            hideInTable: true,
            valueType: 'radioButton',
            hideInDescriptions: true,
            valueEnum: {
                1: { text: '一个月' },
                2: { text: '三个月' },
                3: { text: '半年' },
            },
        },
        {
            dataIndex: 'QUALIFICATION_STATE',
            title: '状态',
            align: 'center',
            valueType: 'select',
            hideInDescriptions: true,
            valueEnum: {
                1: { text: '有效', status: 'processing' },
                2: { text: '过期', status: "default" },
            },
        },
        {
            dataIndex: 'OPERATE_DATE',
            title: '更新时间',
            align: 'center',
            valueType: 'fromNow',
            hideInTable: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'STAFF_NAME',
            title: '操作员',
            align: 'center',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            dataIndex: 'option',
            title: '操作',
            align: 'center',
            valueType: 'option',
            hideInSearch: true,
            render: (_, record) => {
                return (
                    <Space>
                        <a
                            onClick={async () => {
                                setCurrentRow(await getDetail(record));
                                handleModalVisible(true);
                            }}
                        >
                            编辑
                        </a>
                        <a
                            onClick={async () => {
                                setQualificationId(record.QUALIFICATION_ID);
                                handleModalRTVisible(true);
                            }}
                        >
                            查看商品
                        </a>
                        {/* <Popconfirm
                            title="确认删除该资质信息吗?"
                            onConfirm={async () => {
                                const sucesse = await handelDelete(record.QUALIFICATION_ID);
                                if (sucesse && actionRef.current) {
                                    actionRef.current.reload();
                                }
                            }}
                        >
                            <a>删除</a>
                        </Popconfirm> */}
                    </Space>
                );
            },
        },
    ];

    // 表格列数据配置
    const columnsCommodity: ProColumns<CommdityLocalModel>[] = [
        {
            dataIndex: 'COMMODITY_NAME',
            title: '商品名称',
            hideInSearch: true,
            editable: false
        },
        {
            dataIndex: 'COMMODITY_BARCODE',
            title: '商品条码',
            hideInSearch: true,
            width: 150,
            align: 'center',
            editable: false,
        },
        {
            dataIndex: 'COMMODITY_RETAILPRICE',
            title: '零售价',
            width: 80,
            align: 'center',
            hideInSearch: true,
            editable: false
        },
        {
            dataIndex: 'COMMODITY_RULE',
            title: '规格',
            width: 100,
            align: 'center',
            hideInSearch: true,
            editable: false
        },
        {
            dataIndex: 'COMMODITY_UNIT',
            title: '单位',
            width: 100,
            align: 'center',
            hideInSearch: true,
            editable: false
        },
    ];

    return (
        <PageContainer header={{
            title: '',
            breadcrumb: {},
        }}>
            <ProTable<QualificationModel>
                rowKey="QUALIFICATION_ID"
                headerTitle="资质管理"
                actionRef={actionRef}
                search={{ span: 6 }}
                request={async (params, sorter) => {
                    // 排序字段
                    const sortstr = Object.keys(sorter).map(n => {
                        const value = sorter[n]
                        return value ? `${n} ${value.replace('end', '')}` : ''
                    })
                    const data = await getQualificationList({
                        ...params,
                        BUSINESSMAN_ID: currentUser?.BusinessManID,
                        QUALIFICATION_ENDDATE: params?.QUALIFICATION_ENDDATE ? nowFilterDate[params?.QUALIFICATION_ENDDATE][1] : '',
                        QUALIFICATION_STARTDATE: params?.QUALIFICATION_ENDDATE ?
                            nowFilterDate[params?.QUALIFICATION_ENDDATE][0] : params?.QUALIFICATION_STARTDATE || '',
                        QUALIFICATION_STATESEARCH: '1,2',
                        SortStr: sortstr.length ? sortstr.toString() : "OPERATE_DATE desc",
                    });
                    return data;
                }}
                columns={columns}
                toolbar={{
                    actions: [
                        <Button
                            key="new"
                            icon={<PlusOutlined />}
                            type="primary"
                            onClick={() => {
                                setCurrentRow({ QUALIFICATION_TYPE: 1000 } as QualificationModel)
                                handleModalVisible(true);
                            }}
                        >
                            资质
                        </Button>,
                    ],
                }}
            // options={false}
            />
            <Drawer
                width={600}
                visible={showDetail}
                onClose={() => {
                    setCurrentRow(undefined);
                    setFileList([]);
                    setShowDetail(false);
                }}
                closable={false}
            >
                {currentRow?.QUALIFICATION_NAME && (<>
                    <ProDescriptions<QualificationModel>
                        column={1}
                        title={currentRow?.QUALIFICATION_NAME}
                        request={async () => ({
                            data: currentRow || {},
                        })}
                        params={{
                            id: currentRow?.QUALIFICATION_ID,
                        }}
                        columns={columns as ProDescriptionsItemProps<QualificationModel>[]}
                    />

                </>)}
                <div>资质文件</div>
                {
                    currentRow?.ImgList ?
                        <Upload
                            defaultFileList={transferImg(currentRow?.ImgList) as unknown as UploadFile[] || []}
                            showUploadList={{
                                showDownloadIcon: false,
                                showRemoveIcon: false,
                            }}
                        /> : '-'
                    // <Image.PreviewGroup>
                    //     {currentRow?.ImgList && currentRow?.ImgList.map(n =>
                    //         <div style={{ width: 108, height: 108, padding: 4, border: '1px solid #eee', display: "inline-flex", marginRight: 16 }}>
                    //             <Image width={100} height={100} src={n?.ImageUrl} style={{ objectFit: "contain" }} />
                    //         </div>
                    //     )
                    //     }
                    // </Image.PreviewGroup>
                }
            </Drawer>
            <ModalForm<QualificationModel>
                title={currentRow?.QUALIFICATION_ID ? '更新资质信息' : '新建资质'}
                layout={'horizontal'}
                width={1024}
                wrapperCol={{ span: 16 }}
                labelCol={{ span: 6 }}
                formRef={formRef}
                visible={modalVisible}
                autoFocusFirstInput
                modalProps={{
                    onCancel: () => {
                        // console.log('close')
                    },
                }}
                onVisibleChange={(value) => {
                    handleModalVisible(value);
                    if (value) {
                        formRef.current?.setFieldsValue(
                            currentRow || { QUALIFICATION_STATE: 1 },
                        );
                    } else {
                        formRef.current?.resetFields();
                        setFileList([])
                        setPriviewImage('')
                        // setPriviewFileList([])
                        setCurrentRow(undefined);
                        setEditCommdity([])
                        setEditableRowKeys([])
                    }
                }}
                onFinish={async (values) => {
                    let newValue: QualificationModel = {
                        ...values,
                        QUALIFICATION_STATE: values.QUALIFICATION_STATE || 1,
                        QUALIFICATION_ENDDATE: values.QUALIFICATION_ENDDATE || ''
                    };
                    if (currentRow) {
                        // 编辑数据
                        newValue = { ...currentRow, ...newValue };
                    }
                    const success = await handleAddUpdate(newValue,
                        editableKeys ? editableKeys?.toString() : '',
                        currentUser?.ID, currentUser?.Name);

                    if (success) {
                        const waitUpload = fileList.filter(n => n.status !== 'done')

                        if (waitUpload.length > 0) {
                            setCurrentRow(success)
                            const uploadSuccess = await customUploadRequest(waitUpload, success?.QUALIFICATION_ID)
                            if (uploadSuccess) {
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }
                                return true
                            }
                            return false
                        }
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                        return true
                    }
                    return false
                }}
            >
                <div>
                    <Row >
                        <Col span={12}>
                            <ProFormText
                                name="QUALIFICATION_NAME"
                                label="资质名称"
                                placeholder="请输入资质名称"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入资质名称',
                                    },
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                name="SUPPLIER_ID"
                                label="供应商名称"
                                placeholder="请输入供应商名称"

                                showSearch
                                options={!loading ? supplierList : []}

                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                name="QUALIFICATION_TYPE"
                                label="资质类型"
                                placeholder="请选择资质类型"
                                rules={[{
                                    required: true,
                                    message: '请选择资质类型',
                                }]}
                                fieldProps={{
                                    onChange: (value) => {
                                        setCurrentRow({ ...currentRow, QUALIFICATION_TYPE: value } as QualificationModel)
                                    }
                                }}
                                request={async () => {
                                    return await getFieldEnum({ FieldExplainField: 'QUALIFICATION_TYPE' })
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDatePicker
                                name="ISSUING_DATE"
                                label="签发日期"
                                width="md"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择签发日期',
                                    }
                                ]}
                                fieldProps={{
                                    onChange: (value) => {
                                        if (currentRow?.QUALIFICATION_TYPE === 1000) {
                                            formRef.current?.setFieldsValue({ QUALIFICATION_ENDDATE: moment(value).add(1, 'year') })
                                        }
                                    }
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDatePicker
                                name="QUALIFICATION_ENDDATE"
                                label={"有效期至"}
                                width="md"
                                rules={[
                                    {
                                        required: currentRow?.QUALIFICATION_TYPE === 1000,
                                        message: '请选择有效截止期',
                                    }
                                ]}
                                // readonly={currentRow?.QUALIFICATION_TYPE === 1000}
                                fieldProps={{
                                    allowClear: true,
                                    onChange: (value) => {
                                        if (value && value > moment(currentRow?.ISSUING_DATE).add(1, 'year')) {
                                            formRef.current?.setFieldsValue({ QUALIFICATION_ENDDATE: moment(currentRow?.ISSUING_DATE).add(1, 'year') })
                                        }
                                    }
                                }}
                            />
                        </Col>
                        {
                            currentRow?.QUALIFICATION_TYPE === 2000 &&
                            <Col span={12}>
                                <Form.Item
                                    name="QUALIFICATION_STATE"
                                    label="是否过期"
                                >
                                    <Switch
                                        checkedChildren="是"
                                        unCheckedChildren="否"
                                        defaultChecked={currentRow ? currentRow.QUALIFICATION_STATE === 2 : false}
                                        onChange={(value) => {
                                            formRef.current?.setFieldsValue({ QUALIFICATION_STATE: value ? 2 : 1 })

                                        }}
                                    />
                                </Form.Item>
                            </Col>
                        }
                        <Col span={24}>
                            <ProFormTextArea
                                name="QUALIFICATION_DESC"
                                label={currentRow?.QUALIFICATION_TYPE === 2000 ? "批次说明" : "备注说明"}
                                labelCol={{ span: 3 }}
                                wrapperCol={{ span: 20 }}
                                placeholder={`请输入${currentRow?.QUALIFICATION_TYPE === 2000 ? "批次说明" : "备注说明"}`}
                                fieldProps={{
                                    autoSize: { minRows: 1, maxRows: 2 }
                                }}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormUploadButton
                                name="ImgList"
                                title="选择资质文件"
                                label="上传资质"
                                wrapperCol={{ span: 20 }}
                                labelCol={{ span: 3 }}
                                rules={[
                                    {
                                        required: true,
                                        message: '请上传资质文件，文件类型为pdf',
                                    }
                                ]}
                                fieldProps={{
                                    name: 'files',
                                    // listType: 'picture-card',
                                    className: 'upload-list-inline',
                                    accept: '.pdf',
                                    // defaultFileList: priviewFileList,
                                    fileList, // : fileList,
                                    multiple: true,
                                    onPreview: async (file) => {
                                        if (file.type && file.type?.indexOf('image/') > -1) { // 未上传的文件 如果是图片类型的
                                            if (!file.url && !file.preview) {
                                                setPriviewImage(await getBase64(file.lastModifiedDate))
                                            } else {
                                                setPriviewImage(file?.url)
                                            }
                                        } else {
                                            const filenameSplitPointArr = file.fileName?.split('.') || []

                                            if (['png', 'jpg', 'jpeg'].indexOf(filenameSplitPointArr[filenameSplitPointArr?.length - 1]) > -1) {
                                                setPriviewImage(file?.url)
                                            }
                                            else if (file?.url) {
                                                window.open(file?.url)
                                            }
                                        }
                                    },
                                    beforeUpload: (file, files) => {
                                        setFileList([...fileList, ...files])
                                        return false
                                    },
                                    onChange: async (info: any) => {
                                        if (info.file.status === 'removed') {
                                            // 如果在待上传列表中找到，则说明当前图片没有上传服务器，可直接删除
                                            const index = fileList.findIndex(n => n.uid === info.file.uid);

                                            if (!info.file?.deletepath) {
                                                const newFileList = fileList.slice();
                                                newFileList.splice(index, 1);
                                                setFileList(newFileList)
                                                return
                                            }
                                            confirm({
                                                title: '确认删除该文件吗？',
                                                icon: <ExclamationCircleOutlined />,
                                                async onOk() {
                                                    const deleteLoading = message.loading('正在删除...')
                                                    // const success = await deletePicture(info.file?.deletepath, info.file?.uid, 'QUALIFICATION')
                                                    const success = await deleteAHYDPicture(info.file?.deletepath, info.file?.uid, 'QUALIFICATION')
                                                    deleteLoading()

                                                    if (success) {
                                                        const files = [...fileList]
                                                        files.splice(index, 1)
                                                        setFileList(files)
                                                    }
                                                    else {
                                                        message.error("删除失败")
                                                    }
                                                },
                                                onCancel() {
                                                },
                                            });
                                        }
                                    }
                                }}
                            />
                            <div style={{ display: 'none' }}>
                                <Image width={100} height={100} src={priviewImage} style={{ objectFit: "contain", display: 'none' }}
                                    preview={{
                                        visible: !!priviewImage,
                                        onVisibleChange: value => {
                                            if (!value) {
                                                setPriviewImage('');
                                            }
                                        },
                                    }} />
                            </div>
                        </Col>
                    </Row>
                </div>
                <div>
                    <EditableProTable
                        cardProps={{
                            bodyStyle: {
                                padding: '0px 40px 0px 40px'
                            }
                        }}
                        headerTitle={<div >
                            <Typography.Text>关联商品</Typography.Text>
                            <Typography.Text>(共<span> {editCommdity.length} </span>项商品)</Typography.Text>
                        </div>}
                        scroll={{ y: 370 }}
                        formRef={rtCommodityFormRef}
                        columns={[
                            {
                                title: '序号', valueType: 'indexBorder', dataIndex: 'index', width: 48,
                                align: 'center',
                            },
                            ...columnsCommodity,
                            {
                                title: '操作',
                                valueType: 'option',
                                width: 60,
                                align: 'center',
                                render: () => {
                                    return null;
                                },
                            },
                        ]}
                        dataSource={editCommdity}
                        rowKey="COMMODITY_BUSINESS_ID"
                        value={editCommdity}
                        recordCreatorProps={false}
                        editable={{
                            type: 'multiple',
                            editableKeys,
                            actionRender: (row, config, defaultDoms) => {
                                return [defaultDoms.delete];
                            },
                            onValuesChange: (record, recordList) => {
                                setEditCommdity(recordList);
                            },
                            onChange: setEditableRowKeys,
                        }}
                        toolbar={{
                            actions: [
                                <Button type="primary" onClick={() => setSelectCommdityVisible(true)}>选择商品</Button>,
                            ],
                        }}
                    >
                    </EditableProTable>
                </div>
            </ModalForm>
            {/* 选择要关联资质的商品 */}
            <SelectCommdity editableKeys={editableKeys}
                ServerpartShopIds={formRef.current?.getFieldValue('ServerpartShopIds') ?
                    formRef.current?.getFieldValue('ServerpartShopIds').toString() : ''}
                dataFormat={2} visible={selectCommdityVisible}
                onOk={(values) => {
                    // 去重
                    const totalCommdity = [...editCommdity, ...values].reduce<CommdityLocalModel[]>((p, item) => {
                        const haveThis = p.find(n => n.COMMODITY_BUSINESS_ID === item.COMMODITY_BUSINESS_ID)
                        if (!haveThis) {
                            return [...p, item]
                        }
                        return p
                    }, [])
                    setSelectCommdityVisible(false)
                    setEditCommdity(totalCommdity)
                    setEditableRowKeys(totalCommdity?.map(n => n.COMMODITY_BUSINESS_ID))
                }}
                onCancel={() => {
                    setSelectCommdityVisible(false)
                }} />
            {/* 关联商品列表 */}
            <Modal
                title={
                    <div
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}

                        onFocus={() => { }}
                        onBlur={() => { }}
                    >
                        关联商品列表
                    </div>
                }
                destroyOnClose={true}
                width={1024}
                visible={modalRTVisible}
                onCancel={() => {
                    handleModalRTVisible(false)
                }}
                onOk={() => {
                    handleModalRTVisible(false)
                }}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <ProTable<CommdityLocalModel>
                    rowKey="COMMODITY_BUSINESS_ID"
                    size="small"
                    actionRef={actionRef}
                    search={{ span: 12 }}
                    tableStyle={{ minHeight: 500 }}
                    request={async (params) => {
                        const data = await getCommodityList({
                            ...params,
                            QUALIFICATION_ID: qualificationId,
                            BUSINESSMAN_ID: currentUser?.BusinessManID,
                            keyWord: params.keyword ? { key: 'COMMODITY_NAME,COMMODITY_BARCODE', value: params.keyword } : null, // 关键词查询
                        });
                        return data;
                    }}
                    params={{
                        SERVERPARTSHOP_IDS: formRef.current?.getFieldValue('ServerpartShopIds') ?
                            formRef.current?.getFieldValue('ServerpartShopIds').toString() : '',
                    }}
                    columns={[{
                        dataIndex: 'keyword',
                        title: '名称/条码',
                        hideInDescriptions: true,
                        hideInTable: true,
                    },
                    {
                        dataIndex: 'COMMODITY_TYPENAME',
                        title: '类别',
                        // width: 150,
                        ellipsis: true,
                        hideInSearch: true,
                    }, ...columnsCommodity]}
                    options={false}
                    pagination={{ defaultPageSize: 10, size: 'small', showSizeChanger: false }}
                />
            </Modal>
        </PageContainer>
    );
};

export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(CommdityTable);
