package shop.alien.store.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreCuisine;
import shop.alien.entity.store.StoreInfo;
import shop.alien.entity.store.StorePrice;
import shop.alien.entity.store.dto.CuisineComboDto;
import shop.alien.entity.store.dto.CuisineTypeResponseDto;
import shop.alien.entity.store.dto.TablewareFeeDto;
import shop.alien.entity.store.vo.PriceListVo;
import shop.alien.store.annotation.TrackEvent;
import shop.alien.store.service.StoreCuisineService;
import shop.alien.store.service.StoreInfoService;
import shop.alien.store.service.StorePriceService;
import shop.alien.store.util.ai.AiGetPriceUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 美食价目表
 *
 * @author auto-generated
 * @since 2025-12-30
 */
@Slf4j
@Api(tags = {"美食价目表"})
@ApiSort(1)
@CrossOrigin
@RestController
@RequestMapping("/store/cuisine")
@RequiredArgsConstructor
public class StoreCuisineController {

    private final StoreCuisineService storeCuisineService;

    private final AiGetPriceUtil aiGetPriceUtil;

    private final StorePriceService storePriceService;

    private final StoreInfoService storeInfoService;

    @ApiOperation("新增美食套餐或单品")
    @ApiOperationSupport(order = 1)
    @PostMapping("/addCuisineCombo")
    public R<StoreCuisine> addCuisineCombo(@RequestBody CuisineComboDto cuisineComboDto) {
        log.info("StoreCuisineController.save?storeCuisine={}", cuisineComboDto);
        if (storeCuisineService.addCuisineCombo(cuisineComboDto)) {
            return R.success("新增成功");
        }
        return R.fail("新增失败");
    }

    @ApiOperation("修改美食套餐或单品")
    @ApiOperationSupport(order = 2)
    @PostMapping("/updateCuisineCombo")
    public R<String> updateCuisineCombo(@RequestBody CuisineComboDto cuisineComboDto) {
        log.info("StoreCuisineController.updateCuisineCombo?dto={}", cuisineComboDto);
        if (storeCuisineService.updateCuisineCombo(cuisineComboDto)) {
            return R.success("修改成功");
        }
        return R.fail("修改失败");
    }

    @ApiOperation("获取所有美食单品名称，用于添加套餐")
    @ApiOperationSupport(order = 1)
    @GetMapping("/getSingleName")
    public R<List<StoreCuisine>> getSingleName() {
        return R.data(storeCuisineService.getSingleName());
    }

    @TrackEvent(
            eventType = "PRICE_VIEW",
            eventCategory = "PRICE",
            storeId = "#{result.data.data.storeId}",
            targetId = "#{#id}",
            targetType = "PRICE"
    )
    @ApiOperation("根据id与类型获取美食单品或套餐详情")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "美食/套餐 id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "cuisineType", value = "美食类型：1-单品，2-套餐", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getByCuisineType")
    public R<CuisineTypeResponseDto> getByCuisineType(Integer id, Integer cuisineType) {
        return R.data(storeCuisineService.getByCuisineTypeNew(id, cuisineType));
    }


    @ApiOperation("删除美食价目")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "美食价目id", dataType = "Integer", paramType = "query", required = true)})
    @PostMapping("/delete")
    public R<String> delete(Integer id) {
        log.info("StoreCuisineController.delete?id={}", id);
        if (storeCuisineService.removeById(id)) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @ApiOperation("批量删除美食价目")
    @ApiOperationSupport(order = 6)
    @PostMapping("/deleteBatch")
    public R<String> deleteBatch(@RequestBody List<Integer> ids) {
        log.info("StoreCuisineController.deleteBatch?ids={}", ids);
        if (storeCuisineService.removeByIds(ids)) {
            return R.success("批量删除成功");
        }
        return R.fail("批量删除失败");
    }

    @ApiOperation("美食上下架：1-上架，2-下架")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "美食价目id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "shelfStatus", value = "上下架状态：1-上架，2-下架", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/changeShelfStatus")
    public R<String> changeShelfStatus(@RequestParam("id") Integer id, @RequestParam("shelfStatus") Integer shelfStatus) {
        log.info("StoreCuisineController.changeShelfStatus?id={},shelfStatus={}", id, shelfStatus);
        if (shelfStatus == null || (shelfStatus != 1 && shelfStatus != 2)) {
            return R.fail("上下架状态不合法（只能为1或2）");
        }
        if (storeCuisineService.changeShelfStatus(id, shelfStatus)) {
            return R.success("操作成功");
        }
        return R.fail("操作失败");
    }

    @ApiOperation("分页查询美食价目/通用价目")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页容", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "商户id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "菜名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态：0-待审核 1-审核通过 2-审核拒绝", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型：1-美食 2-通用", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "startCreatedTime", value = "创建时间开始（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endCreatedTime", value = "创建时间结束（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query", required = false)
    })
    @GetMapping("/getPage")
    public R<List<PriceListVo>> getPage(
            @RequestParam int pageNum,
            @RequestParam int pageSize,
            @RequestParam(required = false) Integer storeId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = true) Integer type,
            @RequestParam(required = false) Integer origin,
            @RequestParam(required = false) String startCreatedTime,
            @RequestParam(required = false) String endCreatedTime)
    {
        log.info("StoreCuisineController.getPage?pageNum={},pageSize={},storeId={},name={},status={},type={},startCreatedTime={},endCreatedTime={}", pageNum, pageSize, storeId, name, status, type, startCreatedTime, endCreatedTime);
        List<PriceListVo> priceListVo = new ArrayList<>();

        // 解析时间参数
        Date startTime = null;
        Date endTime = null;
        if (startCreatedTime != null && !startCreatedTime.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                startTime = sdf.parse(startCreatedTime);
            } catch (Exception e) {
                log.warn("解析开始时间失败: {}", startCreatedTime, e);
            }
        }
        if (endCreatedTime != null && !endCreatedTime.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                endTime = sdf.parse(endCreatedTime);
            } catch (Exception e) {
                log.warn("解析结束时间失败: {}", endCreatedTime, e);
            }
        }

        if(type == 1){
            Page<StoreCuisine> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<StoreCuisine> queryWrapper = new LambdaQueryWrapper<>();
            // 默认只查询已上架的菜品/套餐（shelf_status = 1）
            if(null==origin){
                queryWrapper.eq(StoreCuisine::getShelfStatus, 1);
            }
            if (storeId != null) {
                queryWrapper.eq(StoreCuisine::getStoreId, storeId);
            }
            if (name != null && !name.isEmpty()) {
                queryWrapper.like(StoreCuisine::getName, name);
            }
            if (status != null) {
                queryWrapper.eq(StoreCuisine::getStatus, status);
            }
            // 创建时间范围查询
            if (startTime != null) {
                queryWrapper.ge(StoreCuisine::getCreatedTime, startTime);
            }
            if (endTime != null) {
                queryWrapper.le(StoreCuisine::getCreatedTime, endTime);
            }
            queryWrapper.orderByDesc(StoreCuisine::getCreatedTime);
            IPage<StoreCuisine> result = storeCuisineService.page(page, queryWrapper);
            List<StoreCuisine> cuisineList = result.getRecords();

            if (cuisineList != null && !cuisineList.isEmpty()) {
                for (StoreCuisine cuisine : cuisineList) {
                    PriceListVo vo = new PriceListVo();

                    BeanUtils.copyProperties(cuisine, vo);
                    // 设置分类名称
                    vo.setCategoryNames(storeCuisineService.getCategoryNames(cuisine.getCategoryIds()));
                    priceListVo.add(vo);
                }
            }
            return R.data(priceListVo);
        }else{
            Page<StorePrice> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<StorePrice> queryWrapper = new LambdaQueryWrapper<>();
            if (storeId != null) {
                queryWrapper.eq(StorePrice::getStoreId, storeId);
            }
            if (name != null && !name.isEmpty()) {
                queryWrapper.like(StorePrice::getName, name);
            }
            if (status != null) {
                queryWrapper.eq(StorePrice::getStatus, status);
            }
            // 默认只查询已上架的菜品/套餐（shelf_status = 1）
            queryWrapper.eq(StorePrice::getShelfStatus, 1);
            // 创建时间范围查询
            if (startTime != null) {
                queryWrapper.ge(StorePrice::getCreatedTime, startTime);
            }
            if (endTime != null) {
                queryWrapper.le(StorePrice::getCreatedTime, endTime);
            }
            queryWrapper.orderByDesc(StorePrice::getCreatedTime);
            IPage<StorePrice> result = storePriceService.page(page, queryWrapper);
            List<StorePrice> storePrices = result.getRecords();
            if (storePrices != null && !storePrices.isEmpty()) {
                for (StorePrice storePrice : storePrices) {
                    PriceListVo vo = new PriceListVo();

                    BeanUtils.copyProperties(storePrice, vo);
                    priceListVo.add(vo);
                }
            }
            return R.data(priceListVo);
        }
    }

    @ApiOperation("根据菜品和位置查询推荐菜价")
    @ApiOperationSupport(order = 6)
    @PostMapping("/getPrice")
    public R<String> getPrice(String dish_name,String location) {
        JSONObject dishPrice = aiGetPriceUtil.getDishPrice(dish_name, location);
        
        // 检查响应状态码
        Integer code = dishPrice.getInteger("code");
        if (code == null || code != 200) {
            String message = dishPrice.getString("message");
            log.warn("查询菜品价格失败，code: {}, message: {}", code, message);
            return R.fail(message != null ? message : "查询菜品价格失败");
        }
        
        // 获取 data 对象
        JSONObject data = dishPrice.getJSONObject("data");
        if (data == null) {
            log.warn("查询菜品价格响应中 data 为空");
            return R.fail("查询菜品价格失败：响应数据为空");
        }
        
        // 从 data 中获取 price
        Object priceObj = data.get("price");
        if (priceObj == null) {
            log.warn("查询菜品价格响应中 price 为空");
            return R.fail("查询菜品价格失败：价格信息为空");
        }
        
        // 将价格转换为字符串返回
        String price = priceObj.toString();
        return R.data(price);
    }

    @ApiOperation("保存或更新餐具费")
    @ApiOperationSupport(order = 8)
    @PostMapping("/saveTablewareFee")
    public R<String> saveTablewareFee(@RequestBody TablewareFeeDto tablewareFeeDto) {
        log.info("StoreCuisineController.saveTablewareFee?storeId={},tablewareFee={}", 
                tablewareFeeDto.getStoreId(), tablewareFeeDto.getTablewareFee());
        
        if (tablewareFeeDto.getStoreId() == null) {
            return R.fail("门店ID不能为空");
        }
        
        if (storeInfoService.saveOrUpdateTablewareFee(tablewareFeeDto.getStoreId(), tablewareFeeDto.getTablewareFee())) {
            return R.success("保存成功");
        }
        return R.fail("保存失败");
    }

    @ApiOperation("查询餐具费")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getTablewareFee")
    public R<Integer> getTablewareFee(@RequestParam("storeId") Integer storeId) {
        log.info("StoreCuisineController.getTablewareFee?storeId={}", storeId);
        
        if (storeId == null) {
            return R.fail("门店ID不能为空");
        }
        
        StoreInfo storeInfo = storeInfoService.getById(storeId);
        if (storeInfo == null) {
            return R.fail("门店不存在");
        }
        
        return R.data(storeInfo.getTablewareFee());
    }
}


