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.CaseDao;
import io.modules.item.dao.DoctorsDao;
import io.modules.item.dao.OrderDao;
import io.modules.item.dto.AuditDTO;
import io.modules.item.entity.AuditEntity;
import io.modules.item.entity.CaseEntity;
import io.modules.item.entity.DoctorsEntity;
import io.modules.item.entity.OrderEntity;
import io.modules.item.service.AuditService;
import io.modules.item.service.CaseService;
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.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;

/**
 * 授权表
 *
 * @author Mark #
 * @since 1.0.0 2025-05-13
 */
@RestController
@RequestMapping("api/audit")
@Tag(name = "授权表")
@CrossOrigin
public class AuditController {
    @Autowired
    private AuditService auditService;


    @Autowired
    private OrderDao orderDao;

    @Autowired
    private DoctorsDao doctorsDao;

    @Autowired
    private AuditDao auditDao;


    @Autowired
    private CaseDao caseDao;


    @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<AuditDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
        PageData<AuditDTO> page = auditService.page(params);
        return new Result<PageData<AuditDTO>>().ok(page);
    }

    @Login
    @GetMapping("list")
    public Result<List<AuditDTO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> params, @Parameter(hidden = true) @RequestAttribute("userId") Long userId) {

        params.put("userId", userId.toString());

        List<AuditDTO> page = auditService.list(params);
        List<AuditDTO> collect = page.stream().map(e -> {
            DoctorsEntity doctorsEntity = doctorsDao.selectById(e.getItemId());

            if (doctorsEntity != null) {
                e.setDoctors(doctorsEntity);
            }
//            主治医生
            OrderEntity orderEntity = orderDao.selectById(e.getOrderId());
            if (orderEntity != null) {
                DoctorsEntity doctorsEntity1 = doctorsDao.selectById(orderEntity.getItemId());

                if (doctorsEntity1 != null) {
                    e.setOneDoctors(doctorsEntity1);
                }
            }


            return e;
        }).collect(Collectors.toList());

        return new Result<List<AuditDTO>>().ok(collect);
    }


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

    @PostMapping
    @Operation(summary = "保存")
    public Result save(@RequestBody AuditDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        LambdaQueryWrapper<AuditEntity> lwq = new LambdaQueryWrapper<>();
        lwq.eq(AuditEntity::getItemId, dto.getItemId());
        lwq.eq(AuditEntity::getOrderId, dto.getOrderId());
        lwq.eq(AuditEntity::getStatus, "未授权");
        if (auditDao.exists(lwq)) {
            return new Result().error("您已经申请，不能重复申请");
        }
        auditService.save(dto);
        return new Result();
    }

    @PutMapping
    @Operation(summary = "修改")
    public Result update(@RequestBody AuditDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        //查询病例密钥
        if (dto.getStatus().equals("同意授权")) {
            OrderEntity orderEntity = orderDao.selectById(dto.getOrderId());
            if (orderEntity == null) {
                return new Result().error("没查询到对应的订单");
            }
            LambdaQueryWrapper<CaseEntity> lwq = new LambdaQueryWrapper<>();
            lwq.eq(CaseEntity::getOrderId, orderEntity.getId());
            CaseEntity caseEntity = caseDao.selectOne(lwq);
            if (caseEntity == null) {
                return new Result().error("没查询到对应的病例");
            }
            dto.setHex(caseEntity.getHex());
            AuditEntity auditEntity = new AuditEntity();
            BeanUtils.copyProperties(dto,auditEntity);
            auditService.updateById(auditEntity);
            return new Result();
        }
        dto.setHex("");
        auditService.update(dto);
        return new Result();
    }

    @DeleteMapping
    @Operation(summary = "删除")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        auditService.delete(ids);

        return new Result();
    }


}
