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.IotMeasureCertPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.cert.vo.IotMeasureCertRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.cert.vo.IotMeasureCertSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.qhse.cert.IotMeasureCertDO;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.cert.IotMeasureCertMapper;
import cn.iocoder.yudao.module.pms.service.qhse.cert.IotMeasureCertService;
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.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
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 = "管理后台 - 计量器具-证书管理")
@RestController
@RequestMapping("/rq/iot-measure-cert")
@Validated
public class IotMeasureCertController {

    @Resource
    private IotMeasureCertService iotMeasureCertService;
    @Autowired
    private DeptApi deptApi;
    @Autowired
    private AdminUserApi adminUserApi;
    @Autowired
    private DictDataService dictDataService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private IotMeasureCertMapper iotMeasureCertMapper;

    @PostMapping("/create")
    @Operation(summary = "创建计量器具-证书管理")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-cert:create')")
    public CommonResult<Long> createIotMeasureCert(@Valid @RequestBody IotMeasureCertSaveReqVO createReqVO) {
        return success(iotMeasureCertService.createIotMeasureCert(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新计量器具-证书管理")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-cert:update')")
    public CommonResult<Boolean> updateIotMeasureCert(@Valid @RequestBody IotMeasureCertSaveReqVO updateReqVO) {
        iotMeasureCertService.updateIotMeasureCert(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除计量器具-证书管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-cert:delete')")
    public CommonResult<Boolean> deleteIotMeasureCert(@RequestParam("id") Long id) {
        iotMeasureCertService.deleteIotMeasureCert(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得计量器具-证书管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-cert:query')")
    public CommonResult<IotMeasureCertRespVO> getIotMeasureCert(@RequestParam("id") Long id) {
        IotMeasureCertDO iotMeasureCert = iotMeasureCertService.getIotMeasureCert(id);
        return success(BeanUtils.toBean(iotMeasureCert, IotMeasureCertRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得计量器具-证书管理分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-cert:query')")
    public CommonResult<PageResult<IotMeasureCertRespVO>> getIotMeasureCertPage(@Valid IotMeasureCertPageReqVO pageReqVO) {
        PageResult<IotMeasureCertDO> pageResult = iotMeasureCertService.getIotMeasureCertPage(pageReqVO);
        List<IotMeasureCertRespVO> collect = pageResult.getList().stream().map(e -> {
            IotMeasureCertRespVO iotMeasureCertRespVO = new IotMeasureCertRespVO();
            BeanUtils.copyProperties(e, iotMeasureCertRespVO);
            if (Objects.nonNull(iotMeasureCertRespVO.getDeptId())) {
                DeptRespDTO dept = deptApi.getDept(iotMeasureCertRespVO.getDeptId());
                if(Objects.nonNull(dept)){
                    iotMeasureCertRespVO.setDeptName(dept.getName());
                }
            }
            return iotMeasureCertRespVO;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出计量器具-证书管理 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-cert:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotMeasureCertExcel(@Valid IotMeasureCertPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotMeasureCertDO> list = iotMeasureCertService.getIotMeasureCertPage(pageReqVO).getList();
        List<IotMeasureCertRespVO> bean = BeanUtils.toBean(list, IotMeasureCertRespVO.class);
        List<DictDataDO> personCert = dictDataService.getDictDataListByDictType("person_cert");
        List<DictDataDO> orgCert = dictDataService.getDictDataListByDictType("org_cert");
        bean.forEach(e ->{
            if (Objects.nonNull(e.getDeptId())) {
                DeptRespDTO dept = deptApi.getDept(e.getDeptId());
                if (Objects.nonNull(dept)){
                    e.setDeptName(dept.getName());
                }
            }
            if (Objects.nonNull(e.getUserId())) {
                AdminUserRespDTO user = adminUserApi.getUser(e.getUserId());
                if (Objects.nonNull(user)) {
                    e.setUserName(user.getNickname());
                }
            }
            if ("personal".equals(e.getType())) {
                e.setType("个人证书");
                personCert.stream().filter(f -> f.getValue().equals(e.getClassify())).findFirst().ifPresent(f -> e.setClassify(f.getLabel()));
            } else {
                e.setType("组织证书");
                orgCert.stream().filter(f -> f.getValue().equals(e.getClassify())).findFirst().ifPresent(f -> e.setClassify(f.getLabel()));
            }
        });
        // 导出 Excel
        ExcelUtils.write(response, "计量器具-证书管理.xls", "数据", IotMeasureCertRespVO.class, bean);
    }

    @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);
        }
        //到期
        IotMeasureCertPageReqVO reqVO = new IotMeasureCertPageReqVO();
        reqVO.setExpired(true);
        long expired = iotMeasureCertMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        reqVO.setExpired(null);
        reqVO.setAlertWarn(true);
        //90天预警
        long warn = iotMeasureCertMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        reqVO.setAlertWarn(null);
        reqVO.setType("personal");
        Long personal = iotMeasureCertMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        reqVO.setType("organization");
        Long org = iotMeasureCertMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        reqVO.setType(null);
        Long total = iotMeasureCertMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        return success(ImmutableMap.of("expired", expired, "warn", warn,"personal", personal,"organization", org,"total", total));
    }
}