package io.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.annotation.Login;
import io.common.constant.Constant;
import io.common.page.PageData;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.modules.item.dao.ItemDao;
import io.modules.item.dao.OrderDao;
import io.modules.item.dto.*;
import io.modules.item.entity.HouseEntity;
import io.modules.item.entity.OrderEntity;
import io.modules.item.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
/**
 * 订单表
 */
@RestController
@RequestMapping("/api/order")
@Tag(name="订单表")
@CrossOrigin
public class OrderController {
    @Autowired
    private OrderService orderService;


    @Autowired
    private UserService userService;

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ItemDao itemDao;
    @Autowired
    private HouseService itemService;

    @Login
    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
        @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref="int") ,
        @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY,required = true, ref="int") ,
        @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref="String") ,
        @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref="String")
    })
    public Result<PageData<OrderDTO>> page(@Parameter(hidden = true) @RequestAttribute("userId") Long userId,@Parameter(hidden = true) @RequestParam Map<String, Object> params){
        params.put("userId",userId);
        PageData<OrderDTO> page = orderService.page(params);
        List<OrderDTO> collect = page.getList().stream().map(e -> {
            //拼接商品名称
            HouseDTO itemDTO = itemService.get(e.getItemId());
            if (itemDTO != null) {
                e.setItem(itemDTO);
            }
            HouseDTO houseDTO = itemService.get(e.getUserHouseId());
            if (itemDTO != null) {
                e.setItemA(houseDTO);
            }
            return e;  // 返回修改后的对象
        }).collect(Collectors.toList());
        page.setList(collect);
        return new Result<PageData<OrderDTO>>().ok(page);
    }


    @Login
    @GetMapping("list")
    public Result<List<OrderDTO>> list(@Parameter(hidden = true) @RequestAttribute("userId") Long userId){

        //查询用户下所有房源信息
        LambdaQueryWrapper<HouseEntity> lwq = new LambdaQueryWrapper<>();
        lwq.eq(HouseEntity::getUserId,userId);
        List<HouseEntity> houseEntities = itemDao.selectList(lwq);
        if (houseEntities.isEmpty()){
            return new Result<List<OrderDTO>>().ok(new ArrayList<>());
        }

        List<Long> idList = houseEntities.stream()
                .map(HouseEntity::getId)
                .collect(Collectors.toList());


        List<OrderEntity> orderEntities = new ArrayList<>();
        //查询订单中是否存在房源
        for (Long aLong : idList) {
            LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderEntity::getItemId,aLong);
            List<OrderEntity> orderEntityList = orderDao.selectList(wrapper);
            orderEntities.addAll(orderEntityList);
        }


        if (orderEntities.isEmpty()){
            return new Result<List<OrderDTO>>().ok(new ArrayList<>());
        }


        ArrayList<OrderDTO> list = new ArrayList<>();
        for (OrderEntity orderEntity : orderEntities) {

            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(orderEntity,orderDTO);
            //申请人用户信息
            Long itemUserId = orderEntity.getItemUserId();
            UserDTO userDTO = userService.get(itemUserId);
            orderDTO.setUser(userDTO);
            //申请人房源信息
            Long userHouseId = orderEntity.getUserHouseId();
            HouseDTO houseDTO = itemService.get(userHouseId);
            orderDTO.setItem(houseDTO);
            list.add(orderDTO);
        }
        return new Result<List<OrderDTO>>().ok(list);
    }

    @GetMapping("hex")
    @Operation(summary = "信息")
    public Result<HexDto> get(@RequestParam("hex") String hex){
        HexDto hexDto = new HexDto();
        //通过hex查询订单
        LambdaQueryWrapper<OrderEntity> lwq = new LambdaQueryWrapper<>();
        lwq.eq(OrderEntity::getHex,hex);
        OrderEntity orderEntity = orderDao.selectOne(lwq);
        if (orderEntity ==null){
            return new Result<HexDto>().error("查询不到相关信息");
        }
        //可以查到
        //1.A用户信息和房源编号 甲
        Long itemIdA = orderEntity.getItemId();
        hexDto.setHouseA(itemService.get(itemIdA));
        Long itemUserIdA = orderEntity.getItemUserId();
        hexDto.setUserA(userService.get(itemUserIdA));
        //2.B用户信息和房源编号 乙
        Long userIdB = orderEntity.getUserId();
        hexDto.setUserB(userService.get(userIdB));
        Long userHouseIdB = orderEntity.getUserHouseId();
        hexDto.setHouseB(itemService.get(userHouseIdB));
        hexDto.setDto(orderEntity);
        return new Result<HexDto>().ok(hexDto);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    public Result<OrderDTO> get(@PathVariable("id") Long id){
        OrderDTO data = orderService.get(id);
        return new Result<OrderDTO>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @Login
    public Result save(@RequestBody OrderDTO dto,@Parameter(hidden = true) @RequestAttribute("userId") Long userId){
        dto.setUserId(userId);
        //判断是否已经申请
        LambdaQueryWrapper<OrderEntity> lwq = new LambdaQueryWrapper<>();
        lwq.eq(OrderEntity::getUserId,userId);
        lwq.eq(OrderEntity::getItemId,dto.getItemId());
        if (orderDao.exists(lwq)){
            return new Result().error("不能重复申请");
        }
        //房源用户编号
        Long itemId = dto.getItemId();
        HouseDTO houseDTO = itemService.get(itemId);
        dto.setItemUserId(houseDTO.getUserId());
        orderService.save(dto);
        return new Result();
    }
    @PutMapping
    @Operation(summary = "修改")
    public Result update(@RequestBody OrderDTO dto){
        orderService.update(dto);
        return new Result();
    }
    @DeleteMapping("{id}")
    @Operation(summary = "删除")
    public Result delete(@PathVariable Long id) {
        Long[] ids = new Long[]{id};
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        orderService.delete(ids);
        return new Result();
    }

}
