package com.tourism.webadmin.app.wechat.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.page.PageMethod;
import com.tourism.common.additional.utils.StringUtils;
import com.tourism.common.additional.utils.UrlConvertUtils;
import com.tourism.common.core.annotation.DisableDataFilter;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.MyOrderParam;
import com.tourism.common.core.object.MyPageData;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.tourism.webadmin.app.website.dto.*;
import com.tourism.webadmin.app.wechat.dto.TourRestaurantCartChangeDto;
import com.tourism.webadmin.app.wechat.model.WechatRestaurantCart;
import com.tourism.webadmin.app.wechat.vo.shopfood.WechatRestaurantCartTotalVo;
import com.tourism.webadmin.app.wechat.vo.shopfood.WechatRestaurantCartVo;
import com.tourism.webadmin.back.dto.RestaurantCartDto;
import com.tourism.webadmin.back.model.*;
import com.tourism.webadmin.back.service.*;
import com.tourism.webadmin.back.vo.*;
import com.tourism.common.additional.config.ApplicationConfig;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.List;

/**
 * 旅游项目页面接口。
 *
 * @author chenchen
 * @date 2024-09-26
 */
@Tag(name = "小程序美食板块接口")
@Slf4j
@RestController
@RequestMapping("/wechat/foodProject")
@DisableDataFilter
public class TakeOutProjectController {

    @Autowired
    private RestaurantTypeService restaurantTypeService;
    @Autowired
    private RestaurantInfoService restaurantInfoService;
    @Autowired
    private RestaurantFoodTypeService restaurantFoodTypeService;
    @Autowired
    private RestaurantFoodInfoService restaurantFoodInfoService;
    @Autowired
    private RestaurantCartService restaurantCartService;
    @Autowired
    private ApplicationConfig applicationConfig;

    /**
     * 列出符合过滤条件的店铺分类列表。
     * 接口：旅游页面的接口(searchString: 标题模糊查询;pageNum: 页码;pageSize: 每页大小;count: true)
     * @return 应答结果对象，包含查询结果集。
     */
    @SaIgnore
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/restaurantTypeList")
    public ResponseResult<MyPageData<RestaurantTypeVo>> restaurantTypeList(TourismRestaurantTypeToWebDto tourismRestaurantTypeToWebDto){

        //小程序看到的为启用的餐馆
        tourismRestaurantTypeToWebDto.setEnable(1);
        if (tourismRestaurantTypeToWebDto.getPageNum() != null && tourismRestaurantTypeToWebDto.getPageSize() != null) {
            PageMethod.startPage(tourismRestaurantTypeToWebDto.getPageNum(), tourismRestaurantTypeToWebDto.getPageSize(), true);
        }
        RestaurantType restaurantType = MyModelUtil.copyTo(tourismRestaurantTypeToWebDto, RestaurantType.class);
//        String orderBy = MyOrderParam.buildOrderBy(tourismRestaurantTypeToWebDto.getOrderParamList(), RestaurantType.class);
        List<RestaurantType> restaurantFoodTypeList =
                restaurantTypeService.getRestaurantTypeListWithRelation(restaurantType, "tour_restaurant_type.show_order");


        MyPageData<RestaurantTypeVo> restaurantTypeVoMyPageData = MyPageUtil.makeResponseData(restaurantFoodTypeList, RestaurantTypeVo.class);


        List<RestaurantTypeVo> dataList = restaurantTypeVoMyPageData.getDataList();
        dataList.stream().forEach(item ->
        {
            if(StringUtils.isNotEmpty(item.getUrl())) {
                List<String> arrayList2 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getUrl());
                item.setUrlAfterConvert(arrayList2);
            }
        });

        return ResponseResult.success(restaurantTypeVoMyPageData);
    }


    /**
     * 列出符合过滤条件的店铺列表。
     * 接口：旅游页面的接口(searchString: 标题模糊查询;pageNum: 页码;pageSize: 每页大小;count: true)
     * @return 应答结果对象，包含查询结果集。
     */
    @SaIgnore
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/restaurantInfoList")
    public ResponseResult<MyPageData<RestaurantInfoVo>>        restaurantInfoList(TourismRestaurantInfoToWebDto tourismRestaurantInfoToWebDto){

        //小程序看到的为启用的店铺
        tourismRestaurantInfoToWebDto.setEnable(1);
        if (tourismRestaurantInfoToWebDto.getPageNum() != null && tourismRestaurantInfoToWebDto.getPageSize() != null) {
            PageMethod.startPage(tourismRestaurantInfoToWebDto.getPageNum(), tourismRestaurantInfoToWebDto.getPageSize(), true);
        }
        RestaurantInfo restaurantInfo = MyModelUtil.copyTo(tourismRestaurantInfoToWebDto, RestaurantInfo.class);
        String orderBy = MyOrderParam.buildOrderBy(tourismRestaurantInfoToWebDto.getOrderParamList(), RestaurantInfo.class);
        List<RestaurantInfo> restaurantInfoList =
                restaurantInfoService.getRestaurantInfoList(restaurantInfo, orderBy);
        MyPageData<RestaurantInfoVo> restaurantInfoVoMyPageData = MyPageUtil.makeResponseData(restaurantInfoList, RestaurantInfoVo.class);
        List<RestaurantInfoVo> dataList = restaurantInfoVoMyPageData.getDataList();
        dataList.stream().forEach(item ->
        {
            if(StringUtils.isNotEmpty(item.getUrl())) {
                List<String> arrayList2 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getUrl());
                item.setUrlAfterConvert(arrayList2);
            }
            if(StringUtils.isNotEmpty(item.getEnvironmentImage())) {
                List<String> arrayList2 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getEnvironmentImage());
                item.setEnvironmentImageAfterConvert(arrayList2);
            }
        });
        return ResponseResult.success(restaurantInfoVoMyPageData);
    }

    /**
     * 列出符合过滤条件的美食类型列表。
     * 接口：旅游页面的接口(searchString: 标题模糊查询;pageNum: 页码;pageSize: 每页大小;count: true)
     * @return 应答结果对象，包含查询结果集。
     */
    @SaIgnore
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/restaurantFoodTypeList")
    public ResponseResult<MyPageData<RestaurantFoodTypeVo>> restaurantFoodTypeList(TourismRestaurantFoodTypeToWebDto tourismRestaurantFoodTypeToWebDto){

        //小程序看到的为启用的美食类型列表
        tourismRestaurantFoodTypeToWebDto.setEnable(1);
        if (tourismRestaurantFoodTypeToWebDto.getPageNum() != null && tourismRestaurantFoodTypeToWebDto.getPageSize() != null) {
            PageMethod.startPage(tourismRestaurantFoodTypeToWebDto.getPageNum(), tourismRestaurantFoodTypeToWebDto.getPageSize(), true);
        }
        RestaurantFoodType restaurantFoodType = MyModelUtil.copyTo(tourismRestaurantFoodTypeToWebDto, RestaurantFoodType.class);
        String orderBy = MyOrderParam.buildOrderBy(tourismRestaurantFoodTypeToWebDto.getOrderParamList(), RestaurantFoodType.class);
        List<RestaurantFoodType> restaurantFoodTypeList =
                restaurantFoodTypeService.getRestaurantFoodTypeList(restaurantFoodType, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(restaurantFoodTypeList, RestaurantFoodTypeVo.class));
    }


    /**
     * 列出符合过滤条件的美食列表。
     * 接口：旅游页面的接口(searchString: 标题模糊查询;pageNum: 页码;pageSize: 每页大小;count: true)
     * @return 应答结果对象，包含查询结果集。
     */
    @SaIgnore
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/restaurantFoodList")
    public ResponseResult<MyPageData<RestaurantFoodInfoVo>> restaurantFoodList(TourismRestaurantFoodInfoToWebDto tourismRestaurantFoodInfoToWebDto){

        //小程序看到的为启用的美食列表
        tourismRestaurantFoodInfoToWebDto.setEnable(1);
        if (tourismRestaurantFoodInfoToWebDto.getPageNum() != null && tourismRestaurantFoodInfoToWebDto.getPageSize() != null) {
            PageMethod.startPage(tourismRestaurantFoodInfoToWebDto.getPageNum(), tourismRestaurantFoodInfoToWebDto.getPageSize(), true);
        }
        RestaurantFoodInfo restaurantFoodinfo = MyModelUtil.copyTo(tourismRestaurantFoodInfoToWebDto, RestaurantFoodInfo.class);
        String orderBy = MyOrderParam.buildOrderBy(tourismRestaurantFoodInfoToWebDto.getOrderParamList(), RestaurantFoodInfo.class);
        List<RestaurantFoodInfo> restaurantFoodList =
                restaurantFoodInfoService.getRestaurantFoodInfoList(restaurantFoodinfo, orderBy);

        MyPageData<RestaurantFoodInfoVo> restaurantInfoVoMyPageData = MyPageUtil.makeResponseData(restaurantFoodList, RestaurantFoodInfoVo.class);


        List<RestaurantFoodInfoVo> dataList = restaurantInfoVoMyPageData.getDataList();
        dataList.stream().forEach(item ->
        {
            if(StringUtils.isNotEmpty(item.getUrl())) {
                List<String> arrayList2 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), item.getUrl());
                item.setUrlAfterConvert(arrayList2);
            }
        });

        return ResponseResult.success(restaurantInfoVoMyPageData);
    }


    /**
     * 店铺详情。
     * 接口：店铺详情接口(id)
     * @return 应答结果对象，包含查询结果集。
     */
    @SaIgnore
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/restaurantInfoById")
    public ResponseResult<RestaurantInfoVo> restaurantInfoById(@RequestParam(required = true) String id){

        //小程序看到的为启用的店铺

//        RestaurantInfo filter = new RestaurantInfo();
//        filter.setId(id);
//        filter.setEnable(1);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",id);
        queryWrapper.eq("enable",1);
        RestaurantInfo restaurantInfo = restaurantInfoService.getOne(queryWrapper);
        if (restaurantInfo == null) {
            return ResponseResult.success(null);
        }
        RestaurantInfoVo restaurantInfoVo = MyModelUtil.copyTo(restaurantInfo, RestaurantInfoVo.class);
        if(StringUtils.isNotEmpty(restaurantInfoVo.getUrl())) {
            List<String> arrayList2 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), restaurantInfoVo.getUrl());
            restaurantInfoVo.setUrlAfterConvert(arrayList2);
        }
        if(StringUtils.isNotEmpty(restaurantInfoVo.getEnvironmentImage())) {
            List<String> arrayList2 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), restaurantInfoVo.getEnvironmentImage());
            restaurantInfoVo.setEnvironmentImageAfterConvert(arrayList2);
        }
        if(StringUtils.isNotEmpty(restaurantInfoVo.getRestaurantBanner())) {
            List<String> arrayList2 = UrlConvertUtils.urlConvert(applicationConfig.getHostIpPort(), restaurantInfoVo.getRestaurantBanner());
            restaurantInfoVo.setRestaurantBannerAfterConvert(arrayList2);
        }
        return ResponseResult.success(restaurantInfoVo);
    }


    /**
     * 列出符合过滤条件的购物车列表。
     * restaurantId必传
     * 接口：购物车的接口(restaurantCartDto)
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/foodCartList")
    public ResponseResult<WechatRestaurantCartTotalVo> foodCartList(RestaurantCartDto restaurantCartDto){

        if(restaurantCartDto.getRestaurantId() == null){
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST,"数据验证失败，餐馆id不能为空！");
        }
//        TokenData tokenData = TokenData.takeFromRequest();
//        restaurantCartDto.setUserId(tokenData.getUserId());
        restaurantCartDto.setUserId(1L);
        WechatRestaurantCart wechatRestaurantCart = MyModelUtil.copyTo(restaurantCartDto, WechatRestaurantCart.class);
        String orderBy = MyOrderParam.buildOrderBy(null, RestaurantCart.class);
        //获取该用户在该餐馆的购物车记录
        List<WechatRestaurantCart> wechatRestaurantCartList = restaurantCartService.getRestaurantCartListAndFoodDetail(wechatRestaurantCart, orderBy);
        List<WechatRestaurantCartVo> wechatRestaurantCartVo = MyModelUtil.copyCollectionTo(wechatRestaurantCartList, WechatRestaurantCartVo.class);

        BigDecimal totalPrice = BigDecimal.ZERO;
        wechatRestaurantCartVo.stream().forEach(item->{
            BigDecimal decimalCount = BigDecimal.valueOf(item.getCount());
            totalPrice.add(item.getPrice().multiply(decimalCount));
        });
        WechatRestaurantCartTotalVo wechatRestaurantCartTotalVo = new WechatRestaurantCartTotalVo();
        wechatRestaurantCartTotalVo.setTotalPirce(totalPrice);
        wechatRestaurantCartTotalVo.setWechatRestaurantCartVoList(wechatRestaurantCartVo);
        return ResponseResult.success(wechatRestaurantCartTotalVo);
    }


    /**
     * 购物车数量变化。
     * restaurantFoodId必传
     * 接口：购物车的接口(restaurantCartDto)
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @GetMapping("/foodCartChange")
    public ResponseResult foodCartChange(@Valid TourRestaurantCartChangeDto restaurantCartChangeDto){
        //不允许传负数
        if(restaurantCartChangeDto.getCount()<0){
            return ResponseResult.error(ErrorCodeEnum.UPLOAD_FAILED);
        }
        //新增,则查询是否有购物车记录;没有的话,则新增;有的话,则修改+1
        RestaurantCart filter = new RestaurantCart();
//            TokenData tokenData = TokenData.takeFromRequest();
//            filter.setUserId(tokenData.getUserId());
            filter.setUserId(1L);
            filter.setRestaurantFoodId(restaurantCartChangeDto.getRestaurantFoodId());
            RestaurantCart restaurantCart = restaurantCartService.getOne(filter);
            //能查到user和菜品的购物车记录
            if(!ObjectUtils.isEmpty(restaurantCart)){
                //如果传递的数量是0的话，则应该删除该条购物车记录
                if(restaurantCartChangeDto.getCount() == 0) {
                    boolean remove = restaurantCartService.remove(restaurantCart.getId());
                    //删除失败
                    if(!remove){
                        return ResponseResult.error(ErrorCodeEnum.DATA_SAVE_FAILED);
                    }else {
                        return ResponseResult.success();
                    }
                }else {
                    //如果传递的数量不是0的话，则应该更新记录
                    restaurantCart.setCount(restaurantCartChangeDto.getCount());
                    boolean remove = restaurantCartService.updateById(restaurantCart);
                    //更新失败
                    if(!remove){
                        return ResponseResult.error(ErrorCodeEnum.DATA_SAVE_FAILED);
                    }else {
                        return ResponseResult.success();
                    }
                }
            }else {
                //当查不到购物车记录时，则表明为新增
                RestaurantCart restaurantCart1 = new RestaurantCart();
//                restaurantCart1.setUserId(tokenData.getUserId());
                restaurantCart1.setUserId(1L);
                restaurantCart1.setRestaurantFoodId(restaurantCartChangeDto.getRestaurantFoodId());
                restaurantCart1.setRestaurantId(restaurantCartChangeDto.getRestaurantId());
                restaurantCart1.setCount(restaurantCartChangeDto.getCount());
                RestaurantCart restaurantCart2 = restaurantCartService.saveNew(restaurantCart1);
                //更新失败
                if(ObjectUtils.isEmpty(restaurantCart2)){
                    return ResponseResult.error(ErrorCodeEnum.DATA_SAVE_FAILED);
                }else {
                    return ResponseResult.success();
                }
            }
    }
}
