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

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.cert.vo.QhseOrgCertPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.cert.vo.QhseOrgCertRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.cert.vo.QhseOrgCertSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.qhse.cert.QhseOrgCertDO;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.cert.QhseOrgCertMapper;
import cn.iocoder.yudao.module.pms.service.qhse.cert.QhseOrgCertService;
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-org-cert")
@Validated
public class QhseOrgCertController {

    @Resource
    private QhseOrgCertService qhseOrgCertService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private QhseOrgCertMapper qhseOrgCertMapper;
    @Autowired
    private DeptApi deptApi;

    @PostMapping("/create")
    @Operation(summary = "创建QHSE组织证书管理")
    @PreAuthorize("@ss.hasPermission('rq:qhse-org-cert:create')")
    public CommonResult<Long> createQhseOrgCert(@Valid @RequestBody QhseOrgCertSaveReqVO createReqVO) {
        return success(qhseOrgCertService.createQhseOrgCert(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新QHSE组织证书管理")
    @PreAuthorize("@ss.hasPermission('rq:qhse-org-cert:update')")
    public CommonResult<Boolean> updateQhseOrgCert(@Valid @RequestBody QhseOrgCertSaveReqVO updateReqVO) {
        qhseOrgCertService.updateQhseOrgCert(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除QHSE组织证书管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:qhse-org-cert:delete')")
    public CommonResult<Boolean> deleteQhseOrgCert(@RequestParam("id") Long id) {
        qhseOrgCertService.deleteQhseOrgCert(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得QHSE组织证书管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:qhse-org-cert:query')")
    public CommonResult<QhseOrgCertRespVO> getQhseOrgCert(@RequestParam("id") Long id) {
        QhseOrgCertDO qhseOrgCert = qhseOrgCertService.getQhseOrgCert(id);
        return success(BeanUtils.toBean(qhseOrgCert, QhseOrgCertRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得QHSE组织证书管理分页")
    @PreAuthorize("@ss.hasPermission('rq:qhse-org-cert:query')")
    public CommonResult<PageResult<QhseOrgCertRespVO>> getQhseOrgCertPage(@Valid QhseOrgCertPageReqVO pageReqVO) {
        PageResult<QhseOrgCertDO> pageResult = qhseOrgCertService.getQhseOrgCertPage(pageReqVO);
        List<QhseOrgCertRespVO> collect = pageResult.getList().stream().map(e -> {
            QhseOrgCertRespVO qhseOrgCertRespVO = new QhseOrgCertRespVO();
            BeanUtils.copyProperties(e, qhseOrgCertRespVO);
            if (Objects.nonNull(qhseOrgCertRespVO.getDeptId())) {
                DeptRespDTO dept = deptApi.getDept(qhseOrgCertRespVO.getDeptId());
                if(Objects.nonNull(dept)){
                    qhseOrgCertRespVO.setDeptName(dept.getName());
                }
            }
            return qhseOrgCertRespVO;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出QHSE组织证书管理 Excel")
    @PreAuthorize("@ss.hasPermission('rq:qhse-org-cert:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportQhseOrgCertExcel(@Valid QhseOrgCertPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<QhseOrgCertDO> list = qhseOrgCertService.getQhseOrgCertPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "QHSE组织证书管理.xls", "数据", QhseOrgCertRespVO.class,
                        BeanUtils.toBean(list, QhseOrgCertRespVO.class));
    }


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