package cn.iocoder.yudao.module.pms.controller.admin.qhse.devicecert;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.devicecert.vo.QhseDeviceCertPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.devicecert.vo.QhseDeviceCertRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.devicecert.vo.QhseDeviceCertSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.qhse.devicecert.QhseDeviceCertDO;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.devicecert.QhseDeviceCertMapper;
import cn.iocoder.yudao.module.pms.service.qhse.devicecert.QhseDeviceCertService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import com.google.common.collect.ImmutableMap;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - QHSE应检设备证书")
@RestController
@RequestMapping("/rq/qhse-device-cert")
@Validated
public class QhseDeviceCertController {

    @Resource
    private QhseDeviceCertService qhseDeviceCertService;
    @Autowired
    private DeptApi deptApi;
    @Autowired
    private DeptService deptService;
    @Autowired
    private QhseDeviceCertMapper qhseDeviceCertMapper;

    @PostMapping("/create")
    @Operation(summary = "创建QHSE应检设备证书")
    @PreAuthorize("@ss.hasPermission('rq:qhse-device-cert:create')")
    public CommonResult<Long> createQhseDeviceCert(@Valid @RequestBody QhseDeviceCertSaveReqVO createReqVO) {
        return success(qhseDeviceCertService.createQhseDeviceCert(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新QHSE应检设备证书")
    @PreAuthorize("@ss.hasPermission('rq:qhse-device-cert:update')")
    public CommonResult<Boolean> updateQhseDeviceCert(@Valid @RequestBody QhseDeviceCertSaveReqVO updateReqVO) {
        qhseDeviceCertService.updateQhseDeviceCert(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除QHSE应检设备证书")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:qhse-device-cert:delete')")
    public CommonResult<Boolean> deleteQhseDeviceCert(@RequestParam("id") Long id) {
        qhseDeviceCertService.deleteQhseDeviceCert(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得QHSE应检设备证书")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:qhse-device-cert:query')")
    public CommonResult<QhseDeviceCertRespVO> getQhseDeviceCert(@RequestParam("id") Long id) {
        QhseDeviceCertDO qhseDeviceCert = qhseDeviceCertService.getQhseDeviceCert(id);
        return success(BeanUtils.toBean(qhseDeviceCert, QhseDeviceCertRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得QHSE应检设备证书分页")
    @PreAuthorize("@ss.hasPermission('rq:qhse-device-cert:query')")
    public CommonResult<PageResult<QhseDeviceCertRespVO>> getQhseDeviceCertPage(@Valid QhseDeviceCertPageReqVO pageReqVO) {
        PageResult<QhseDeviceCertDO> pageResult = qhseDeviceCertService.getQhseDeviceCertPage(pageReqVO);
        List<QhseDeviceCertRespVO> collect = pageResult.getList().stream().map(e -> {
            QhseDeviceCertRespVO qhseDeviceCertRespVO = new QhseDeviceCertRespVO();
            BeanUtils.copyProperties(e, qhseDeviceCertRespVO);
            if (Objects.nonNull(qhseDeviceCertRespVO.getDeptId())) {
                DeptRespDTO dept = deptApi.getDept(qhseDeviceCertRespVO.getDeptId());
                if(Objects.nonNull(dept)){
                    qhseDeviceCertRespVO.setDeptName(dept.getName());
                }
            }
            return qhseDeviceCertRespVO;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出QHSE应检设备证书 Excel")
    @PreAuthorize("@ss.hasPermission('rq:qhse-device-cert:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportQhseDeviceCertExcel(@Valid QhseDeviceCertPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<QhseDeviceCertDO> list = qhseDeviceCertService.getQhseDeviceCertPage(pageReqVO).getList();
        List<DeptRespDTO> deptList = deptApi.getDeptList();
        list.forEach(e ->{
            if(Objects.nonNull(e)&&Objects.nonNull(e.getDeptId())){
                deptList.stream().filter(dept -> dept.getId().equals(e.getDeptId())).forEach(dept -> {
                    e.setDeptName(dept.getName());
                });
                if ("three".equals(e.getCertType())) {
                    e.setCertType("三类检测证书");
                }
                if ("four".equals(e.getCertType())) {
                    e.setCertType("四类检测证书");
                }
            }
        });
        // 导出 Excel
        ExcelUtils.write(response, "QHSE应检设备证书.xls", "数据", QhseDeviceCertRespVO.class,
                        BeanUtils.toBean(list, QhseDeviceCertRespVO.class));
    }


    @GetMapping("/stat")
    @Operation(summary = "设备应检证书统计")
    public CommonResult<ImmutableMap> generateNum(Long deptId) {
        Set<Long> ids = new HashSet<>();
        if (Objects.nonNull(deptId)) {
            ids = deptService.getChildDeptIdListFromCache(deptId);
            ids.add(deptId);
        }
        //到期
        QhseDeviceCertPageReqVO reqVO = new QhseDeviceCertPageReqVO();
        reqVO.setExpired(true);
        long expired = qhseDeviceCertMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        reqVO.setExpired(null);
        reqVO.setAlertWarn(true);
        //90天预警
        long warn = qhseDeviceCertMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        reqVO.setAlertWarn(null);
        Long total = qhseDeviceCertMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        return success(ImmutableMap.of("expired", expired, "warn", warn, "total", total));
    }
}