// 商城评价管理
import React, { useRef, useState, Suspense } from 'react';
import moment from 'moment'; // 时间相关引用，没有使用可以删除
import numeral from "numeral"; // 数字相关引用，没有使用可以删除
import { connect } from 'umi';

import useRequest from '@ahooksjs/use-request'; // 请求数据的引用
import Draggable from 'react-draggable';
import SubMenu from "antd/lib/menu/SubMenu";
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProForm, { ProFormDatePicker, ProFormDateRangePicker, ProFormDateTimePicker, ProFormDigit, ProFormMoney, ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect, ProFormUploadButton } from '@ant-design/pro-form';
import { MenuFoldOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, Drawer, message, Row, Popconfirm, Space, Image, Modal, Form, Switch, Upload, Tooltip, Descriptions, TreeSelect, Divider } from 'antd';

import type { CurrentUser } from "umi";
import type { ConnectState } from '@/models/connect';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { FormInstance } from 'antd';
import type { COMMODITYModel } from './data';

import { getFieldEnumTree, getFieldEnumName } from "@/services/options"; // 枚举的引用，没有使用可以删除
import { getList, delcommodity, updatecommodity } from './service'; // 接口相关对象的引用
import PageTitleBox from "@/components/PageTitleBox";
import { handeDeleteCOMMODITY, handeDeleteMALLCOMMENT, handeGetCOMMODITY_MULTIList, handeGetCOMMODITYDetail, handeGetCOMMODITYList, handeGetMALLCOMMENTList, handeSynchroCOMMODITY, handleGetBRANDList } from '../service';
import session from '@/utils/session';
import LeftSelectMallType from '../ProductListingManagement/component/LeftSelectMallType';
import { handleSetlogSave } from '@/utils/format';


const MallEvaluationManage: React.FC<{ currentUser: CurrentUser | undefined, isComponent?: boolean, parentDetail?: any }> = (props) => {
    const { currentUser, isComponent, parentDetail } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [currentRow, setCurrentRow] = useState<COMMODITYModel>();
    const [showDetail, setShowDetail] = useState<boolean>();
    const [modalVisible, handleModalVisible] = useState<boolean>();
    const [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
    const [searchParams, setSearchParams] = useState<any>();
    const [collapsible, setCollapsible] = useState<boolean>(false)
    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<any>()
    // 拿到左侧树的数据
    const [leftTreeData, setLeftTreeData] = useState<any>()
    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    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 columns: any = [
        {
            dataIndex: 'searchText',
            title: '查询内容',
            hideInTable: true,
            fieldProp: {
                placeholder: "请输入评价人员/商家名称"
            }
        },
        {
            title: '评价时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            hideInDescriptions: true,
            search: {
                transform: (value) => {
                    return {
                        CREATE_DATE_Start: value[0],
                        CREATE_DATE_End: value[1],
                    };
                },
            },
            initialValue: [moment().add(-1, 'M').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
        },
        {
            dataIndex: 'index',
            title: '序号',
            align: 'center',
            width: 70,
            ellipsis: true,
            valueType: 'index',
            hideInSearch: true,
        },
        {
            dataIndex: 'MERCHANTS_NAME',
            title: '商家名称',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'COMMODITY_NAME',
            title: '评价商品',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'CREATE_DATE',
            title: '评价时间',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            render: (_, record) => {
                return record?.CREATE_DATE ? moment(record?.CREATE_DATE).format('YYYY-MM-DD HH:mm:ss') : ""
            }
        },
        {
            dataIndex: 'MEMBERSHIP_NAME',
            title: '评价人员',
            align: 'center',
            hideInSearch: true,
            hideInDescriptions: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'MEMBERSHIP_TYPE',
            title: '会员类型',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'MALLCOMMENT_SCORE',
            title: '评分',
            align: 'center',
            hideInSearch: true,
            width: 120,
            ellipsis: true,
        },
        {
            dataIndex: 'MALLCOMMENT_CONTENT',
            title: '评价内容',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'MALLCOMMENT_REPLY',
            title: '回复内容',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'option',
            title: '操作',
            valueType: 'option',
            align: 'center',
            hideInSearch: true,
            width: 120,
            fixed: "right",
            ellipsis: true,
            render: (_, record) => {
                return (
                    <Space>
                        {/* <a
                            onClick={() => {
                                setCurrentRow({ ...record });
                                handleModalVisible(true);
                            }}
                        >
                            编辑
                        </a> */}
                        <Popconfirm
                            title="确认删除该商品管理列表信息吗?"
                            onConfirm={async () => {
                                await handelDelete(record.MALLCOMMENT_ID);
                            }}
                        >
                            <a>删除</a>
                        </Popconfirm>
                    </Space>
                );
            },
        },
    ];

    const handelDelete = async (MALLCOMMENT_ID: number) => {
        const result = await handeDeleteMALLCOMMENT({ MALLCOMMENTId: MALLCOMMENT_ID });

        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:删除失败`);
        } else {
            message.success('删除成功！');
            actionRef.current?.reload()
        }
    };

    const handleAddUpdate = async (res: any) => {
        let req: any = {}
        if (currentRow?.USERDEFINEDTYPE_ID) {
            req = {
                ...currentRow,
                ...res,
                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                OWNERUNIT_NAME: currentUser?.OwnerUnitName,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                OPERATE_PERSON: currentUser?.ID,
                COMMODITY_TYPE: 4000,
                OPERATE_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        } else {
            req = {
                ...res,
                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                OWNERUNIT_NAME: currentUser?.OwnerUnitName,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                OPERATE_PERSON: currentUser?.ID,
                COMMODITY_TYPE: 4000,
                OPERATE_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        }
        const data = await handeSynchroCOMMODITY(req)
        handleConfirmLoading(false)
        if (data.Result_Code === 100) {
            message.success("新增成功！")
            setCurrentRow(undefined)
            formRef?.current?.resetFields()
            handleModalVisible(false)
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    };

    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                {
                    isComponent ? '' :
                        <LeftSelectMallType setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} setData={setLeftTreeData} isShowAllInTree={true} />

                }
                <div style={{
                    width: isComponent ? '100%' : !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    {/* 最外层的列表 */}
                    <ProTable<COMMODITYModel>
                        scroll={{ x: "100%", y: isComponent ? '300px' : 'calc(100vh - 370px)' }}
                        rowKey={(record) => {
                            return `${record?.COMMODITY_ID}`
                        }}
                        formRef={formRef}
                        bordered
                        options={false}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        actionRef={actionRef}
                        search={isComponent ? false : { span: 6, labelWidth: 'auto' }}
                        // 请求数据
                        request={async (params, sorter) => {
                            const req: any = isComponent ? {
                                searchParameter: {
                                    OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                    PROVINCE_CODE: currentUser?.ProvinceCode,
                                    ISVALID: 1,
                                    CREATE_DATE_Start: params?.CREATE_DATE_Start || "",
                                    CREATE_DATE_End: params?.CREATE_DATE_End || "",
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                                SortStr: "CREATE_DATE desc",
                            } : {
                                searchParameter: {
                                    OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                    PROVINCE_CODE: currentUser?.ProvinceCode,
                                    ISVALID: 1,
                                    MEMBERSHIP_ID: parentDetail?.MEMBERSHIP_ID,
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                                SortStr: "CREATE_DATE desc",
                                keyWord: {
                                    Key: "MEMBERSHIP_NAME",
                                    Value: params?.searchText || ""
                                },
                            }
                            const data = await handeGetMALLCOMMENTList(req)
                            console.log('datadatadatadatadata', data);
                            if (data.List && data.List.length > 0) {
                                handleSetlogSave(`点击查询按钮`)
                                return { data: data.List, success: true, total: data.TotalCount }
                            }
                            return { data: [], success: true }
                        }}
                        columns={columns}
                        toolbar={{
                            actions: [

                            ],
                        }}
                    />
                </div>
            </div>
        </div>
    );
};
export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(MallEvaluationManage);