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.BcExport;
import com.gxwebsoft.apps.param.BcExportParam;
import com.gxwebsoft.apps.service.BcExportService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.param.UserParam;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderGoods;
import com.gxwebsoft.shop.service.OrderGoodsService;
import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

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

/**
 * 报餐统计导出控制器
 *
 * @author 科技小王子
 * @since 2023-06-01 21:47:02
 */
@Api(tags = "报餐统计导出管理")
@RestController
@RequestMapping("/api/apps/bc-export")
public class BcExportController extends BaseController {
    @Resource
    private BcExportService bcExportService;

    @Resource
    private OrderService orderService;

    @Resource
    private OrderGoodsService orderGoodsService;

    @Resource
    private UserService userService;

    @PreAuthorize("hasAuthority('apps:bcExport:list')")
    @OperationLog
    @ApiOperation("分页查询报餐统计导出")
    @GetMapping("/page")
    public ApiResult<PageResult<BcExport>> page(BcExportParam param) {
        PageParam<BcExport, BcExportParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(bcExportService.page(page, page.getWrapper()));
        // 使用关联查询
        //return success(bcExportService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('apps:bcExport:list')")
    @ApiOperation("查询全部报餐统计导出")
    @GetMapping()
    public ApiResult<List<BcExport>> list(BcExportParam param) {
      LinkedList<BcExport> resutl = new LinkedList<>();
        PageParam<BcExport, BcExportParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
      // 查询所有员工信息
      final UserParam param1 = new UserParam();
      param1.setOrganizationId(param.getOrganizationId());
      final List<User> users = userService.listRel(param1);
      if(CollectionUtils.isEmpty(users)){
        return success(resutl);
      }
      final Set<Integer> userIds = users.stream().map(User::getUserId).collect(Collectors.toSet());

      // 获取所有订单
      final LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>()
        .eq(Order::getPayStatus,PAY_STATUS_SUCCESS)
        .in(Order::getUserId,userIds);

      if(param.getDeliveryTimeStart() == null){
        System.out.println("默认查询当天 = ");
        // 今天开始时间 2023-05-01 00:00:00
        DateTime parse = DateUtil.parse(DateUtil.today());
        wrapper.eq(Order::getDeliveryTime, parse);
      }
      if(StringUtils.hasText(param.getDeliveryTime())){
        wrapper.eq(Order::getDeliveryTime, param.getDeliveryTime());
      }
      if(StringUtils.hasText(param.getDeliveryTimeStart())){
        wrapper.ge(Order::getDeliveryTime, param.getDeliveryTimeStart());
      }
      if(StringUtils.hasText(param.getDeliveryTimeEnd())){
        wrapper.le(Order::getDeliveryTime, param.getDeliveryTimeEnd());
      }

      final List<Order> list = orderService.list(wrapper);
      if(CollectionUtils.isEmpty(list)){
        return success(resutl);
      }
      // 获取所有订单商品
      final Set<Integer> orderIds = list.stream().map(Order::getOrderId).collect(Collectors.toSet());
      final List<OrderGoods> orderGoods = orderGoodsService.list(new LambdaQueryWrapper<OrderGoods>().in(OrderGoods::getOrderId, orderIds));

      // 按订单分组
      final Map<Integer, List<OrderGoods>> orderGoodsCollect = orderGoods.stream().collect(Collectors.groupingBy(OrderGoods::getOrderId));
      // 按员工分组
      final Map<Integer, List<Order>> userCollect = list.stream().collect(Collectors.groupingBy(Order::getUserId));
      // 计算订餐和签到次数
      int btotalCount = 0;
      int btotalSingCount = 0;
      int ltotalCount = 0;
      int ltotalSingCount = 0;
      int dtotalCount = 0;
      int dtotalSingCount = 0;
      BigDecimal maxTotalPrice = BigDecimal.ZERO;
      for (Integer userId : userCollect.keySet()) {
        final List<Order> userList = userCollect.get(userId); // 员工订单
        final User user = users.stream().filter(u -> u.getUserId().equals(userId)).findFirst().get();
        BcExport bcExport = new BcExport();
        int bCount = 0;
        int bSingCount = 0;
        int lCount = 0;
        int lSingCount = 0;
        int dCount = 0;
        int dSingCount = 0;
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (Order order : userList) {
          // 获取商品
          totalPrice = totalPrice.add(order.getTotalPrice());
          final List<OrderGoods> goodsList = orderGoodsCollect.get(order.getOrderId());
          if(!CollectionUtils.isEmpty(goodsList)){
            for (OrderGoods goods : goodsList) {
              // 查询早餐
              // 查询午餐
              // 查询晚餐
              if(goods.getCategoryId().equals(25)){
                bCount++;
                if(goods.getDeliveryStatus().equals(DELIVERY_STATUS_YES)){
                  bSingCount++;
                }
              }else if(goods.getCategoryId().equals(26)){
                lCount++;
                if(goods.getDeliveryStatus().equals(DELIVERY_STATUS_YES)){
                  lSingCount++;
                }
              }if(goods.getCategoryId().equals(27)){
                dCount++;
                if(goods.getDeliveryStatus().equals(DELIVERY_STATUS_YES)){
                  dSingCount++;
                }
              }
            }
          }
        }
        btotalCount += bCount;
        btotalSingCount += bSingCount;
        ltotalCount += lCount;
        ltotalSingCount += lSingCount;
        dtotalCount += dCount;
        dtotalSingCount += dSingCount;
        maxTotalPrice = maxTotalPrice.add(totalPrice);
        bcExport.setBreakfastPost(bCount);
        bcExport.setBreakfastSign(bSingCount);
        bcExport.setLunchPost(lCount);
        bcExport.setLunchSign(lSingCount);
        bcExport.setDinnerPost(dCount);
        bcExport.setDinnerSign(dSingCount);
        bcExport.setExpendMoney(totalPrice);
        bcExport.setUserId(userId);
        bcExport.setOrganizationName(user.getOrganizationName());
        bcExport.setNickname(user.getNickname());

        resutl.add(bcExport);

      }
      BcExport totalBcExport = new BcExport();
      totalBcExport.setNickname("合计");
      totalBcExport.setBreakfastPost(btotalCount);
      totalBcExport.setBreakfastSign(btotalSingCount);
      totalBcExport.setLunchPost(ltotalCount);
      totalBcExport.setLunchSign(ltotalSingCount);
      totalBcExport.setDinnerPost(dtotalCount);
      totalBcExport.setDinnerSign(dtotalSingCount);
      totalBcExport.setExpendMoney(maxTotalPrice);
      totalBcExport.setOrganizationName("");
      resutl.addFirst(totalBcExport);
      return success(resutl);
    }

    @PreAuthorize("hasAuthority('apps:bcExport:list')")
    @OperationLog
    @ApiOperation("根据id查询报餐统计导出")
    @GetMapping("/{id}")
    public ApiResult<BcExport> get(@PathVariable("id") Integer id) {
        return success(bcExportService.getById(id));
        // 使用关联查询
        //return success(bcExportService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('apps:bcExport:save')")
    @OperationLog
    @ApiOperation("添加报餐统计导出")
    @PostMapping()
    public ApiResult<?> save(@RequestBody BcExport bcExport) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          bcExport.setUserId(loginUser.getUserId());
        }
        if (bcExportService.save(bcExport)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('apps:bcExport:update')")
    @OperationLog
    @ApiOperation("修改报餐统计导出")
    @PutMapping()
    public ApiResult<?> update(@RequestBody BcExport bcExport) {
        if (bcExportService.updateById(bcExport)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('apps:bcExport:remove')")
    @OperationLog
    @ApiOperation("删除报餐统计导出")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (bcExportService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('apps:bcExport:save')")
    @OperationLog
    @ApiOperation("批量添加报餐统计导出")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<BcExport> list) {
        if (bcExportService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('apps:bcExport:update')")
    @OperationLog
    @ApiOperation("批量修改报餐统计导出")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<BcExport> batchParam) {
        if (batchParam.update(bcExportService, "export_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('apps:bcExport:remove')")
    @OperationLog
    @ApiOperation("批量删除报餐统计导出")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (bcExportService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
