package com.gxwebsoft.apps.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.apps.entity.BcFood;
import com.gxwebsoft.apps.entity.BcPlan;
import com.gxwebsoft.apps.param.BcFoodParam;
import com.gxwebsoft.apps.param.BcPlanParam;
import com.gxwebsoft.apps.service.BcFoodService;
import com.gxwebsoft.apps.service.BcPlanService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderGoods;
import com.gxwebsoft.shop.entity.UserReferee;
import com.gxwebsoft.shop.param.OrderGoodsParam;
import com.gxwebsoft.shop.param.OrderParam;
import com.gxwebsoft.shop.param.UserRefereeParam;
import com.gxwebsoft.shop.service.GoodsService;
import com.gxwebsoft.shop.service.OrderGoodsService;
import com.gxwebsoft.shop.service.OrderService;
import com.gxwebsoft.shop.service.UserRefereeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.gxwebsoft.common.core.constants.OrderConstants.ORDER_STATUS_DOING;
import static com.gxwebsoft.common.core.constants.OrderConstants.PAY_STATUS_SUCCESS;

/**
 * 发布菜品明细控制器
 *
 * @author 科技小王子
 * @since 2023-04-27 17:59:40
 */
@Api(tags = "发布菜品明细管理")
@RestController
@RequestMapping("/api/apps/bc-food")
public class BcFoodController extends BaseController {
    @Resource
    private BcFoodService bcFoodService;
    @Resource
    private BcPlanService bcPlanService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private OrderService orderService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private UserRefereeService userRefereeService;

    @ApiOperation("查询菜品列表")
    @GetMapping("/getFoodList")
    public ApiResult<?> getFoodList(BcPlanParam param) {
      // 验证签名
      isCheckSign();
      BcPlan plan = param.getOne(bcPlanService.listRel(param));
      if(plan == null){
        return fail("当日未发布菜品");
      }
      System.out.println("查询菜品列表param = " + param);
      System.out.println("plan = " + plan);
      // json转数组 如：[0,1]转为ArrayList
      ArrayList goodsIds = JSONUtil.parseObject(plan.getGoodsIds(), ArrayList.class);
      final HashMap<String, Object> map = new HashMap<>();
      map.put("week",plan.getWeek());
      map.put("list",goodsService.listByIds(goodsIds));
      return success(map);
    }

    @ApiOperation("查询一周菜谱")
    @GetMapping("/getWeekFood")
    public ApiResult<?> getWeekFood() {
      // 验证签名
      isCheckSign();
      final HashMap<String, Object> map = new HashMap<>();
      // 今天日期
      final DateTime today = DateUtil.parse(DateUtil.today());
      // 本周一周开始的日期
      final DateTime dateTime = DateUtil.beginOfWeek(today);
      // 查询本周菜谱
      final List<BcPlan> list = bcPlanService.list(new LambdaQueryWrapper<BcPlan>().ge(BcPlan::getDayTime, dateTime).last("limit 0,7"));
        try {
          list.forEach(d -> {
            // json转数组 如：[0,1]转为ArrayList
            d.setGoodsList(goodsService.listByIds(JSONUtil.parseObject(d.getGoodsIds(), ArrayList.class)));
          });
        } catch (Exception e) {
          e.printStackTrace();
        }
      return success(list);
    }

    @ApiOperation("查询代取餐人员的报餐信息")
    @GetMapping("/getOthersFood")
    public ApiResult<?> getOthersFood() {
      // 验证签名
      isCheckSign();

      UserRefereeParam param = new UserRefereeParam();
      param.setDealerId(getLoginUserId());
      List<UserReferee> list = userRefereeService.listRel(param);
      // 附加自己
      final UserReferee userReferee = new UserReferee();
      userReferee.setUserId(getLoginUserId());
      userReferee.setNickname(getLoginUser().getNickname());
      list.add(userReferee);
      list.forEach(d -> {
        // 查询他的订单信息
        OrderParam orderParam = new OrderParam();
        orderParam.setUserId(d.getUserId());
        orderParam.setDeliveryTime(DateUtil.beginOfDay(DateUtil.date()).toString());
        orderParam.setOrderStatus(ORDER_STATUS_DOING);
        orderParam.setPayStatus(PAY_STATUS_SUCCESS);
        List<Order> orders = orderService.listRel(orderParam);
          orders.forEach(o -> {
            // 查询菜品信息
            List<OrderGoods> orderGoods = orderGoodsService.list(new LambdaQueryWrapper<OrderGoods>()
              .eq(OrderGoods::getOrderId,o.getOrderId())
              .gt(OrderGoods::getTotalNum,0));
            o.setGoodsList(orderGoods);
          });
        d.setOrder(orders);
      });
      return success(list);
    }

    @ApiOperation("取消代餐")
    @GetMapping("/cancel")
    public ApiResult<?> cancel() {
      UserRefereeParam param = new UserRefereeParam();
      param.setDealerId(getLoginUserId());
      List<UserReferee> list = userRefereeService.listRel(param);
      list.forEach(d -> {
        // 查询他的订单信息
        OrderParam orderParam = new OrderParam();
        orderParam.setUserId(d.getUserId());
        orderParam.setDeliveryTime(DateUtil.beginOfDay(DateUtil.date()).toString());
        orderParam.setPayStatus(PAY_STATUS_SUCCESS);
        List<Order> orders = orderService.listRel(orderParam);
        orders.forEach(o -> {
          // 查询菜品信息
          OrderGoodsParam goodsParam = new OrderGoodsParam();
          goodsParam.setOrderId(o.getOrderId());
          List<OrderGoods> orderGoods = orderGoodsService.listRel(goodsParam);
          o.setGoodsList(orderGoods);
        });
        d.setOrder(orders);
      });
      return success(list);
    }

    @ApiOperation("查询临时报餐信息")
    @GetMapping("/getTemporaryOrder")
    public ApiResult<?> getTemporaryOrder(OrderParam param) {
      // 验证签名
      isCheckSign();
      LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
      lambdaQueryWrapper
        .eq(Order::getUserId,getLoginUserId())
        .eq(Order::getPayStatus,PAY_STATUS_SUCCESS)
        .eq(Order::getOrderStatus,ORDER_STATUS_DOING)
        .eq(Order::getDeleted,0)
        .eq(Order::getIsTemporary,1)
        .eq(Order::getDeliveryTime,param.getDeliveryTime());
      Order order = orderService.getOne(lambdaQueryWrapper,false);
      if(order != null){
        final List<OrderGoods> goods = orderGoodsService.list(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId, order.getOrderId()));
        order.setGoodsList(goods);
        return success("查询成功",order);
      }
      return fail("没有临时报餐数据",null);
    }

    @PreAuthorize("hasAuthority('apps:bcFood:list')")
    @OperationLog
    @ApiOperation("分页查询发布菜品明细")
    @GetMapping("/page")
    public ApiResult<PageResult<BcFood>> page(BcFoodParam param) {
        // 使用关联查询
        return success(bcFoodService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('apps:bcFood:list')")
    @OperationLog
    @ApiOperation("查询全部发布菜品明细")
    @GetMapping()
    public ApiResult<List<BcFood>> list(BcFoodParam param) {
        // 使用关联查询
        return success(bcFoodService.listRel(param));
    }

    @PreAuthorize("hasAuthority('apps:bcFood:list')")
    @OperationLog
    @ApiOperation("根据id查询发布菜品明细")
    @GetMapping("/{id}")
    public ApiResult<BcFood> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(bcFoodService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('apps:bcFood:save')")
    @OperationLog
    @ApiOperation("添加发布菜品明细")
    @PostMapping()
    public ApiResult<?> save(@RequestBody BcFood bcFood) {
        // 记录当前登录用户id、租户id、商户编号
        User loginUser = getLoginUser();
        if (loginUser != null) {
          bcFood.setUserId(loginUser.getUserId());
        }
        if (bcFoodService.save(bcFood)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('apps:bcFood:update')")
    @OperationLog
    @ApiOperation("修改发布菜品明细")
    @PutMapping()
    public ApiResult<?> update(@RequestBody BcFood bcFood) {
        if (bcFoodService.updateById(bcFood)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('apps:bcFood:remove')")
    @OperationLog
    @ApiOperation("删除发布菜品明细")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (bcFoodService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('apps:bcFood:save')")
    @OperationLog
    @ApiOperation("批量添加发布菜品明细")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<BcFood> list) {
        if (bcFoodService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('apps:bcFood:update')")
    @OperationLog
    @ApiOperation("批量修改发布菜品明细")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<BcFood> batchParam) {
        if (batchParam.update(bcFoodService, "bc_food_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('apps:bcFood:remove')")
    @OperationLog
    @ApiOperation("批量删除发布菜品明细")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (bcFoodService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
