// 便利店商品审核
import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import ProCard from "@ant-design/pro-card";
import { MenuFoldOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Button, Input, InputNumber, message, Popconfirm, Space, Spin, Tree, TreeSelect } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import LeftSelectTree from "@/pages/reports/settlementAccount/component/leftSelectTree";
import PageTitleBox from "@/components/PageTitleBox";
import { handleApproveCommodityInfo_AHJG, handleDeleteCOMMODITY_RUNNING, handleGetCOMMODITY_RUNNINGList } from "./service";
import session from "@/utils/session";
import ShopDetailModal from "./components/ShopDetailModal";
import { handleGetNestingCOMMODITYTYPETree } from "../commodityInfo/service";


const ConvenienceStoreProductReview: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const downloadBtnRef = useRef<any>()
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
    const [collapsible, setCollapsible] = useState<boolean>(false)
    const [treeView, setTreeView] = useState<any>()
    const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())

    const serverpartObj = session.get('serverpartObj')
    console.log('serverpartObjserverpartObj', serverpartObj);

    // 商品类型
    const [commodityTree, setCommodityTree] = useState<any>()
    // 商品类型的默认值
    const [defaultCommodityType, setDefaultCommodityType] = useState<any>()
    // 获取商品类型树
    const { loading: treeLoading, data: treeViews } = useRequest(async () => {
        const req = {
            PROVINCE_CODE: currentUser?.ProvinceCode,
            COMMODITYTYPE_VALID: 1,
            ShowCode: false
        }
        const data = await handleGetNestingCOMMODITYTYPETree(req)
        let list: any = []
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                if (item.value === 1901) {
                    list.push(item)
                }
            })
        }
        let res: any = disableParentNodes(list)
        console.log('商品类型树', res);
        let defaultValue: any = findFirstLeafValue(res)
        setCommodityTree(res)
        setDefaultCommodityType(defaultValue)
        return res
    })

    const findFirstLeafValue = (treeData: any[]): number | null => {
        for (const node of treeData) {
            if (node.children && node.children.length > 0) {
                const leafValue = findFirstLeafValue(node.children);
                if (leafValue !== null) return leafValue;
            } else {
                return node.value; // 找到第一个叶子节点
            }
        }
        return null;
    };

    const disableParentNodes = (treeData: any[]) => {
        return treeData.map(node => {
            const newNode: any = { ...node };
            if (newNode.children && newNode.children.length > 0) {
                newNode.disabled = true; // 有 children 的节点禁用
                newNode.children = disableParentNodes(newNode.children); // 递归处理子节点
            }
            return newNode;
        });
    };


    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 导出的加载效果
    const [showLoading, setShowLoading] = useState<boolean>(false)
    // 是否显示打印的表格
    const [showExportTable, setShowExportTable] = useState<boolean>(false)
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()
    // 表格数据
    const [tableData, setTableData] = useState<any>()
    // 审批的loading效果
    const [loading, setLoading] = useState<boolean>(false)
    // 选中的行
    const [selectedModalOrderRowKeys, setSelectedModalOrderRowKeys] = useState<any>()
    // 选中的行数据
    const [selectModalRowList, setSelectModalRowList] = useState<any>()
    // 显示商品详情悬浮框
    const [showShopDetail, setShowShopDetail] = useState<boolean>(false)
    // 行数据
    const [currentRow, setCurrentRow] = useState<any>()

    const columns: any = [
        {
            title: '查询内容',
            dataIndex: 'searchText',
            hideInTable: true,
            fieldProps: {
                placeholder: '请输入商品名称/商品条码/商品编码',
            }
        },
        {
            title: "服务区",
            width: 200,
            dataIndex: "SERVERPART_ID",
            hideInSearch: true,
            valueType: 'select',
            valueEnum: serverpartObj,
            align: 'center',
            ellipsis: true,
        },
        {
            title: "商品名称",
            width: 200,
            dataIndex: "COMMODITY_NAME",
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
            render: (_, record) => {
                return record?.COMMODITY_NAME ?
                    <a onClick={() => {
                        setCurrentRow(record)
                        setShowShopDetail(true)
                    }}>{record?.COMMODITY_NAME}</a> : "-"
            }
        },
        {
            title: "商品条码",
            width: 150,
            dataIndex: "COMMODITY_BARCODE",
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
        },
        // 领导说取这个字段
        {
            title: "商家自编码",
            width: 150,
            dataIndex: "COMMODITY_BRAND",
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
        },
        {
            title: "商品类型",
            width: 250,
            dataIndex: "COMMODITY_TYPE",
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
            render: (_, record) => {
                return <TreeSelect
                    style={{ width: '220px' }}
                    treeData={commodityTree}
                    defaultValue={record?.COMMODITY_TYPE !== '普通商品' ? record?.COMMODITY_TYPE : defaultCommodityType}
                    showSearch  // 开启搜索
                    treeDefaultExpandAll
                    filterTreeNode={(input, node) =>
                        (node?.label as string)?.toLowerCase().includes(input.toLowerCase())
                    }
                    onChange={(value, label, extra) => {
                        console.log('valuevaluevalue', value, label, extra);

                        let newType = value
                        let list = JSON.parse(JSON.stringify(tableData))
                        let newTableData: any = []
                        list.forEach((item: any) => {
                            if (item.COMMODITY_ID === record?.COMMODITY_ID) {
                                item.COMMODITY_TYPE = newType // 商品当前价格 
                                newTableData.push(item)
                            } else {
                                newTableData.push(item)
                            }
                        })
                        setTableData(newTableData)
                    }}
                />
            }
        },
        {
            title: "商品价格",
            width: 150,
            dataIndex: "COMMODITY_CURRPRICE",
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
            render: (_, record) => {
                return <InputNumber min={0} defaultValue={record?.COMMODITY_CURRPRICE} onBlur={(e: any) => {
                    // 拿到当前输入的内容
                    let newPrice = e.target.value
                    let list = JSON.parse(JSON.stringify(tableData))
                    let newTableData: any = []
                    list.forEach((item: any) => {
                        if (item.COMMODITY_ID === record?.COMMODITY_ID) {
                            item.COMMODITY_CURRPRICE = newPrice // 商品当前价格 
                            item.COMMODITY_RETAILPRICE = newPrice  // 零售价
                            item.COMMODITY_MEMBERPRICE = newPrice // 会员价格
                            newTableData.push(item)
                        } else {
                            newTableData.push(item)
                        }
                    })
                    setTableData(newTableData)
                }} />
            }
        },
        {
            title: "商品规格",
            width: 150,
            dataIndex: "COMMODITY_RULE",
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
        },
        {
            title: "商品税率",
            width: 150,
            dataIndex: "DUTY_PARAGRAPH",
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
        },
        {
            title: "商品说明",
            width: 250,
            dataIndex: "COMMODITY_DESC",
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
        },
    ]

    // 批量审核
    const handleBatchReviewCommodity = async () => {
        // 拿到当前的审批列表
        if (selectModalRowList && selectModalRowList.length > 0) {
            // 商品勾选的行
            let list: any = JSON.parse(JSON.stringify(selectedModalOrderRowKeys))
            let reqList: any = []
            // 判断是不是所有的价格都已经输入了
            let isAllOk: boolean = true
            // 没有价格的商品名称
            let noPriceName: string = ''
            tableData.forEach((item: any) => {
                if (list.indexOf(item.COMMODITY_ID.toString()) !== -1) {
                    if (item.COMMODITY_TYPE === '普通商品') {
                        item.COMMODITY_TYPE = 1903
                    }
                    reqList.push(item)
                }
                if (!item.COMMODITY_CURRPRICE) {
                    isAllOk = false
                    if (noPriceName) {
                        noPriceName += `【${item.COMMODITY_NAME}】`
                    } else {
                        noPriceName = `【${item.COMMODITY_NAME}】`
                    }
                }
            })

            if (!isAllOk) {
                message.error(`${noPriceName}为输入价格！`)
                return
            }

            let req: any = {
                list: reqList
            }
            const data = await handleApproveCommodityInfo_AHJG(req)

            if (data.Result_Code === 100) {
                message.success(data.Result_Desc)
                setSelectedModalOrderRowKeys([])
                setSelectModalRowList([])
                actionRef.current?.reload()
            } else {
                message.error(data.Result_Desc)
            }
        } else {
            message.error('请选择审批商品！')
        }
    }

    // 删除商品
    const handleBatchDeleteCommodity = async (id: any) => {
        const req: any = {
            COMMODITY_RUNNINGId: id
        }
        const data = await handleDeleteCOMMODITY_RUNNING(req)
        if (data.Result_Code === 100) {
            message.success('删除成功！')
            handleCloseModal()
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    }

    // 关闭的方法
    const handleCloseModal = () => {
        setCurrentRow(undefined)
        setShowShopDetail(false)
    }

    return (
        <div ref={(el) => {
            // 打印报表
            if (!reqDetailList || reqDetailList.length === 0) return;
            setPrintOut(el);
        }} >

            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} />
                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        rowKey={(record: any) => {
                            return `${record?.COMMODITY_ID}`
                        }}
                        scroll={{ x: "100%", y: "calc(100vh - 430px)" }}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        search={{ span: 6 }}
                        dataSource={tableData}
                        request={async (params) => {
                            if (!selectedId) {
                                return
                            }

                            setSearchParams(params)
                            let req: any = {
                                SearchParameter: {
                                    SERVERPART_IDS: selectedId,
                                    BUSINESSTYPES: 1005
                                },
                                keyWord: {
                                    Key: "COMMODITY_NAME,COMMODITY_BARCODE,COMMODITY_BRAND",
                                    Value: params?.searchText || ""
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                            }

                            const data = await handleGetCOMMODITY_RUNNINGList(req)
                            if (data.List && data.List.length > 0) {
                                setTableData(data.List)
                                return
                                // return { data: data.List, success: true }
                            }
                            setTableData([])
                            return
                            // return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [
                                <Popconfirm
                                    title="确认批量审核已选商品？"
                                    onConfirm={async () => {
                                        if (loading) {
                                            return
                                        }
                                        setLoading(true)
                                        await handleBatchReviewCommodity()
                                        setLoading(false)
                                    }}
                                    onCancel={() => {
                                    }}
                                    okText="确认"
                                    cancelText="取消"
                                >
                                    <Button type={"primary"} loading={loading}>批量审核</Button>
                                </Popconfirm>
                            ]
                        }}
                        rowSelection={{
                            type: 'checkbox',
                            selectedRowKeys: selectedModalOrderRowKeys,
                            onChange: (selectedRowKeys: any, selectedRows: any) => {
                                setSelectModalRowList(selectedRows)
                                setSelectedModalOrderRowKeys(selectedRowKeys)
                            },
                        }}
                    />
                </div>
            </div>


            <ShopDetailModal showDetailDrawer={showShopDetail} handleCloseModal={handleCloseModal} parentRow={currentRow} handleDelete={handleBatchDeleteCommodity} />
        </div>
    )
}

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