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.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.modules.item.dao.AuditDao;
import io.modules.item.dao.DoctorsDao;
import io.modules.item.dao.FrontUserDao;
import io.modules.item.dao.OrderDao;
import io.modules.item.dto.DoctorsDTO;
import io.modules.item.dto.OrderDTO;
import io.modules.item.dto.UserDTO;
import io.modules.item.entity.AuditEntity;
import io.modules.item.entity.DoctorsEntity;
import io.modules.item.entity.FrontUserEntity;
import io.modules.item.entity.OrderEntity;
import io.modules.item.service.DoctorsService;
import io.modules.item.service.OrderService;
import io.modules.item.service.UserService;
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.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.NumberUtils;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 订单表
 */
@RestController
@RequestMapping("api/order")
@Tag(name = "订单表")
@CrossOrigin
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private AuditDao auditDao;

    @Autowired
    private DoctorsService doctorsService;

    @Autowired
    private FrontUserDao frontUserDao;

    @Autowired
    private UserService userService;

    @Value("${upload.url}")
    private String uploadUrl;

    @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")
    })
    @Login
    public Result<PageData<OrderDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params, @Parameter(hidden = true) @RequestAttribute("userId") Long userId) {
        params.put("userId", String.valueOf(userId));
        //分页
        PageData<OrderDTO> page = orderService.page(params);
        List<OrderDTO> collect = page.getList().stream().map(e -> {
            DoctorsDTO doctorsDTO = doctorsService.get(e.getItemId());
            if (doctorsDTO != null) {
                doctorsDTO.setImg(uploadUrl + doctorsDTO.getImg());
                e.setDoctors(doctorsDTO);
            }
            return e;
        }).collect(Collectors.toList());
        page.setList(collect);
        return new Result<PageData<OrderDTO>>().ok(page);
    }

    @GetMapping("list")
    public Result<List<OrderDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
        Long itemId = NumberUtils.parseNumber(params.get("itemId").toString(), Long.class);

        System.out.println(itemId);
        //分页
        List<OrderDTO> page = orderService.list(params);
        List<OrderDTO> collect = page.stream().map(e -> {
            Long userId = e.getUserId();
            UserDTO dto = userService.get(userId);
            if (dto != null) {
                e.setUser(dto);
            }
            //查看授权状态
            LambdaQueryWrapper<AuditEntity> lwq = new LambdaQueryWrapper<>();
            lwq.eq(AuditEntity::getOrderId,e.getId());
            lwq.eq(AuditEntity::getItemId,itemId);
            AuditEntity auditEntity = auditDao.selectOne(lwq);
            if (auditEntity !=null){
                e.setAudit(auditEntity);
            }
            return e;
        }).collect(Collectors.toList());
        return new Result<List<OrderDTO>>().ok(collect);
    }


    @GetMapping("log")
    @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>> log(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
        PageData<OrderDTO> page = orderService.page(params);
        List<OrderDTO> collect = page.getList().stream().map(e -> {
            DoctorsDTO doctorsDTO = doctorsService.get(e.getItemId());
            if (doctorsDTO != null) {
                doctorsDTO.setImg(uploadUrl + doctorsDTO.getImg());
                e.setDoctors(doctorsDTO);
            }

            FrontUserEntity frontUserEntity = frontUserDao.selectById(e.getUserId());
            if (frontUserEntity != null) {
                e.setUserDTO(frontUserEntity);
            }
            return e;
        }).collect(Collectors.toList());

        page.setList(collect);
        return new Result<PageData<OrderDTO>>().ok(page);
    }


    @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) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setUserId(userId);
        orderService.save(dto);
        return new Result();
    }

    @PutMapping
    @Operation(summary = "修改")
    public Result update(@RequestBody OrderDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        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();
    }
}
