import { Modal, message, Popconfirm,Dropdown,Space  } from 'antd';
import { useRef, useState,useEffect } from "react";
import { GetStoreGoods, stopgoods, UpdateStoreGoodsStatusAsync,AddGoodDevice } from '../services';
import ProTable from '@ant-design/pro-table';
import { history } from 'umi';
import GoodsForm from "./GoodsForm";
import ChooseDevice from './ChooseDevice';

/**
 * 菜谱关联加盟商商品
 * @param {*} props 
 * @returns 
 */
const MenuGoods = (props) => {
    const actionRef = useRef();
    // 是否展示 商品弹窗
    const [showGoodsModal, setShowGoodsModal] = useState(false);
    // 当前操作的商品
    const [currGoods, setCurrGoods] = useState();
    // 是否展示设备弹窗
    const [deviceModal, setDeviceModal] = useState(false);
    const [items, setitems] = useState([]);
    const [itemselect, setitemselect] = useState(0);
    const onClick =async (key,record ) => {
       
        if(key.key=='1' || key.key=='2'){
            setitemselect(key.key);
            setDeviceModal(true);
        }else{
            setCurrGoods(record);
            if(key.key=='0'){
                console.log(currGoods)
                const response = await AddGoodDevice({
                    foodMenuId: currGoods.foodMenuId,
                    foods: currGoods.goodsId,
                    deviceIds:[],
                    isDevice:key.key
                });
                console.log(response)
                if (response.statusCode === 200) {
                    message.success("修改成功！");
                    actionRef.current.reloadAndRest();
                } else {
                    message.error(JSON.stringify(response.errors) || '修改失败');
                }
            }
            
        }
      };
    const columns = [
        {
            title: '主键',
            dataIndex: 'id',
            hideInSearch: true,
            hideInTable: true,
            tip: '规则名称是唯一的 key',
        },
        {
            title: '商品',
            dataIndex: 'goods_Name',
            valueType: 'textarea',
        },
        {
            title: '商品价格',
            dataIndex: 'price',
            valueType: 'money',
            hideInSearch: true,

        },
        {
            title: '商品会员价格',
            dataIndex: 'vipPrice',
            valueType: 'money',
            hideInSearch: true,
        },

        {
            title: '制作方式',
            dataIndex: 'isDevice',
            valueEnum: {
                0: { text: '店铺', status: 'Processing' },
                1: { text: '设备', status: 'Success' },
                2: { text: '设备扫码', status: 'Warning' },
            },
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueEnum: {
                0: { text: '上架', status: 'Processing' },
                1: { text: '下架', status: 'Success' },
            },
        },
        {
            title: '估清',
            dataIndex: 'stopSales',
            valueEnum: {
                0: { text: '销售', status: 'Processing' },
                1: { text: '估清', status: 'Success' },
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="update"
                    onClick={() => {
                        setCurrGoods(record);
                        setShowGoodsModal(true);
                    }}
                >
                    编辑
                </a>,
                <Popconfirm
                    key="stopSales"
                    title={`确定要${record.stopSales == 0 ? '估清' : '销售'}吗？`}
                    onConfirm={async () => {
                        let stopSales = 0;
                        if (record.stopSales == 0) {
                            stopSales = 1;
                        } else {
                            stopSales = 0;
                        }
                        let goodss = [{ goodsId: record.foodId, storeId: record.storeId, StopSales: stopSales }];
                        const response = await stopgoods(goodss);
                        if (response.statusCode === 200 && response.data) {
                            message.success('操作成功！')
                            actionRef.current.reloadAndRest();
                        } else {
                            message.error(JSON.stringify(response.errors) || '操作失败');
                        }
                    }}
                    okText="确定"
                    cancelText="取消"
                >
                    <a
                        onClick={async () => {

                        }}
                    >
                        {record.stopSales == 0 ? '估清' : '销售'}
                    </a>
                </Popconfirm>,
                <Popconfirm
                    title={`确定要${record.status == 0 ? '下架' : '上架'}吗？`}
                    onConfirm={async () => {
                        record.status = record.status == 0 ? 1 : 0;
                        const response = await UpdateStoreGoodsStatusAsync(record);
                        if (response.data) {
                            actionRef.current.reloadAndRest();
                            message.success('操作成功！');
                        } else {
                            message.error(JSON.stringify(response.errors) || '操作失败');
                        }
                    }}
                    key="status"
                    okText="确定"
                    cancelText="取消"
                >
                    <a>
                        {record.status == 0 ? '下架' : '上架'}
                    </a>
                </Popconfirm>,
                // <a
                //     key="primary"
                //     onClick={() => {
                //         setCurrGoods(record);
                //         setDeviceModal(true);
                //     }}
                // >
                //     修改为{record.isDevice == 0 ? '设备制作' : '门店制作'}
                // </a>,
                <Dropdown menu={{ items,selectable: true,onClick,
                    defaultSelectedKeys: [] }} trigger={['click']}>
                    <a onClick={(e) => {onClick(e,record)}}>
                    <Space>
                        制作方式
                    </Space>
                    </a>
                </Dropdown>,
                <a
                    key="config"
                    onClick={() => {
                        history.push({
                            pathname: '/shopmanage/storeAddGoodsInfo',
                            query: {
                                isAdd: false,
                                values: record,
                                storeId: props.storeId
                            },
                        });
                    }}
                >
                    加购商品
                </a>,
            ],
        },
    ];
    useEffect(() => {
        setitems([{key:'1',label:"设备制作"},{key:'0',label:"店铺制作"},{key:'2',label:"设备扫码制作"}])
    }, [])
    return <Modal destroyOnClose footer={null} width={1200} title={props.foodMenu.name} visible={props.open} onCancel={props.onCancel}>
        <ProTable
            columns={columns}
            actionRef={actionRef}
            pagination={{
                pageSize: 10
            }}
            request={async (params = {}, sort, filter) => {
                if (props.storeId && props.foodMenu?.id) {
                    if(params.status){
                        params.status=parseInt( params.status);
                    }
                    
                    const response = await GetStoreGoods({
                        ...params,
                        goodsName: params.goods_Name,
                        storeId: props.storeId,
                        foodMenuId: props.foodMenu.id
                    });
                    if (response.statusCode === 200) {
                        return {
                            data: response.data.data,
                            success: true,
                            total: response.data.total,
                        };
                    } else {
                        return []
                    }
                }
                return []
            }}
            rowKey="id"
            headerTitle="商品列表"
        />

        {
            showGoodsModal && currGoods && <GoodsForm
                open={showGoodsModal}
                goods={currGoods}
                onCancel={() => setShowGoodsModal(false)}
                onOk={() => {
                    actionRef.current.reloadAndRest();
                    setShowGoodsModal(false);
                }}
            >

            </GoodsForm>
        }

        {
            deviceModal && <ChooseDevice
                open={deviceModal}
                goods={currGoods}
                foodMenu={props.foodMenu}
                storeId={props.storeId}
                isDevice={itemselect}
                onCancel={() => setDeviceModal(false)}
                onOk={() => {
                    actionRef.current.reloadAndRest();
                    setDeviceModal(false);
                }}
            >

            </ChooseDevice>
        }
    </Modal>
}

export default MenuGoods;