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.CertificatesDao;
import io.modules.item.dto.CertificatesDTO;
import io.modules.item.dto.UserDTO;
import io.modules.item.entity.CertificatesEntity;
import io.modules.item.service.CertificatesService;
import io.modules.item.service.FrontUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
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.web.bind.annotation.*;

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

/**
 * 证书表
 */
@RestController
@RequestMapping("/api/certificate")
@Tag(name="证书表")
@CrossOrigin
public class CertificatesController {
    @Autowired
    private CertificatesService certificatesService;
    @Autowired
    private CertificatesDao certificatesDao;


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

    @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<CertificatesDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params,@Parameter(hidden = true) @RequestAttribute("userId") Long userId){
        params.put("userId",userId);
        PageData<CertificatesDTO> page = certificatesService.page(params);
        List<CertificatesDTO> collect = page.getList().stream().map(e -> {
            // 拼接域名
            e.setImg(uploadUrl + e.getImg());

            UserDTO userDTO = userService.get( e.getUserId());
            e.setUser(userDTO);
            return e;  // 返回修改后的对象
        }).collect(Collectors.toList());
        page.setList(collect);
        return new Result<PageData<CertificatesDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    public Result<CertificatesEntity> get(@PathVariable("id") String id){
        LambdaQueryWrapper<CertificatesEntity> lwq = new LambdaQueryWrapper<>();
        lwq.eq(CertificatesEntity::getBlockchainTxId,id);
        CertificatesEntity list = certificatesDao.selectOne(lwq);
        if (list == null){
            return new Result<CertificatesEntity>().error("没有查询到");
        }
        list.setImg(uploadUrl + list.getImg());
        return new Result<CertificatesEntity>().ok(list);
    }

    @Login
    @PostMapping
    @Operation(summary = "保存")
    public Result save(@RequestBody CertificatesDTO dto,@Parameter(hidden = true) @RequestAttribute("userId") Long userId){
        LambdaQueryWrapper<CertificatesEntity> lwq = new LambdaQueryWrapper<>();
        lwq.eq(CertificatesEntity::getCertificateNumber,dto.getCertificateNumber());
        List<CertificatesEntity> list = certificatesDao.selectList(lwq);
        if (!list.isEmpty()){
            return new Result().error("证书编号有重复");
        }
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setImg(dto.getImg().replace(uploadUrl,""));
        dto.setUserId(userId);
        certificatesService.save(dto);
        return new Result();
    }

    @PutMapping
    @Operation(summary = "修改")
    public Result update(@RequestBody CertificatesDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        dto.setImg(dto.getImg().replace(uploadUrl,""));
        certificatesService.update(dto);
        return new Result();
    }

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

}
