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

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
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.measure.vo.IotMeasureBookPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.measure.vo.IotMeasureBookRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.measure.vo.IotMeasureBookSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.qhse.measure.vo.QhseMeasureExportVO;
import cn.iocoder.yudao.module.pms.controller.admin.stat.DeptUtil;
import cn.iocoder.yudao.module.pms.dal.dataobject.qhse.measure.IotMeasureBookDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.qhse.measure.IotMeasureDetectDO;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.measure.IotMeasureBookMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.qhse.measure.IotMeasureDetectMapper;
import cn.iocoder.yudao.module.pms.service.qhse.ChineseLetterUtil;
import cn.iocoder.yudao.module.pms.service.qhse.measure.IotMeasureBookService;
import cn.iocoder.yudao.module.pms.service.qhse.measure.IotMeasureDetectService;
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.controller.admin.user.vo.user.UserImportRespVO;
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.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
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 org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.extra.pinyin.PinyinUtil.isChinese;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.pms.service.qhse.ChineseLetterUtil.getFirstLetterPinyin;


@Tag(name = "管理后台 - 计量器具台账")
@RestController
@RequestMapping("/rq/iot-measure-book")
@Validated
public class IotMeasureBookController {

    @Resource
    private IotMeasureBookService iotMeasureBookService;
    @Autowired
    private IotMeasureBookMapper iotMeasureBookMapper;
    @Autowired
    private DeptService deptService;
    @Autowired
    private DictDataService dictDataService;
    @Autowired
    private DeptApi deptApi;
    @Autowired
    private DeptUtil deptUtil;
    @Autowired
    private IotMeasureDetectMapper iotMeasureDetectMapper;
    @Autowired
    private IotMeasureDetectService iotMeasureDetectService;

    @PostMapping("/create")
    @Operation(summary = "创建计量器具台账")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-book:create')")
    public CommonResult<Long> createIotMeasureBook(@Valid @RequestBody IotMeasureBookSaveReqVO createReqVO) {
        return success(iotMeasureBookService.createIotMeasureBook(createReqVO));
    }

    @GetMapping("/import-template")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtils.downloadTemplate(response, "计量器具导入模板", IotMeasureBookRespVO.class);
    }

    @PostMapping("/import")
    @Operation(summary = "导入用户")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public CommonResult<UserImportRespVO> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        List<IotMeasureBookRespVO> list = ExcelUtils.readExcel(file, IotMeasureBookRespVO.class);
        return success(iotMeasureBookService.importBookList(list));
    }

    @PutMapping("/update")
    @Operation(summary = "更新计量器具台账")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-book:update')")
    public CommonResult<Boolean> updateIotMeasureBook(@Valid @RequestBody IotMeasureBookSaveReqVO updateReqVO) {
        iotMeasureBookService.updateIotMeasureBook(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除计量器具台账")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-book:delete')")
    public CommonResult<Boolean> deleteIotMeasureBook(@RequestParam("id") Long id) {
        iotMeasureBookService.deleteIotMeasureBook(id);
        iotMeasureDetectMapper.deleteByMap(ImmutableMap.of("measure_id", id));
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得计量器具台账")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-book:query')")
    public CommonResult<IotMeasureBookRespVO> getIotMeasureBook(@RequestParam("id") Long id) {
        IotMeasureBookDO iotMeasureBook = iotMeasureBookService.getIotMeasureBook(id);
        return success(BeanUtils.toBean(iotMeasureBook, IotMeasureBookRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得计量器具台账分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-book:query')")
    public CommonResult<PageResult<IotMeasureBookRespVO>> getIotMeasureBookPage(@Valid IotMeasureBookPageReqVO pageReqVO) {
        PageResult<IotMeasureBookDO> pageResult = iotMeasureBookService.getIotMeasureBookPage(pageReqVO);
        List<IotMeasureBookRespVO> collect = pageResult.getList().stream().map(e -> {
            IotMeasureBookRespVO iotMeasureBookRespVO = new IotMeasureBookRespVO();
            BeanUtils.copyProperties(e, iotMeasureBookRespVO);
            if (Objects.nonNull(iotMeasureBookRespVO.getDeptId())) {
                DeptRespDTO dept = deptApi.getDept(iotMeasureBookRespVO.getDeptId());
                if(Objects.nonNull(dept)){
                    iotMeasureBookRespVO.setDeptName(dept.getName());
                }
            }
            return iotMeasureBookRespVO;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出计量器具台账 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-measure-book:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotMeasureBookExcel(@Valid IotMeasureBookPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotMeasureBookDO> list = iotMeasureBookService.getIotMeasureBookPage(pageReqVO).getList();
        // 转换VO
        List<QhseMeasureExportVO> results = BeanUtils.toBean(list, QhseMeasureExportVO.class);
        // 一次性查询所有检测记录
        List<IotMeasureDetectDO> allDetectList = iotMeasureDetectMapper.selectList();
        List<DictDataDO> dictType = dictDataService.getDictDataListByDictType("measure_type");
        // 优化：按 measureId 分组，避免循环反复filter
        Map<Long, List<IotMeasureDetectDO>> detectGroupMap = allDetectList.stream()
                .collect(Collectors.groupingBy(IotMeasureDetectDO::getMeasureId));

        // 统一日期格式化器（提取到循环外）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<DeptRespDTO> deptList = deptApi.getDeptList();

        results.forEach(e -> {
            dictType.stream().filter(g -> g.getValue().equals(e.getClassify())).findAny().ifPresent(g->{
                e.setClassify(g.getLabel());
            });
            deptList.stream().filter(g ->g.getId().equals(e.getDeptId())).findAny().ifPresent(g->{
                e.setDeptName(g.getName());
            });
            String buyDateStr = null;
            String buyDate = e.getBuyDate();
            if (StringUtils.isNotBlank(buyDate)) {
                try {
                    long timeStamp = Long.parseLong(buyDate);
                    Date date = new Date(timeStamp);
                    buyDate = sdf.format(date);
                } catch (NumberFormatException ex) {
                    // 时间戳格式非法，忽略
                }
            }
            e.setBuyDate(buyDate);
            // 根据id获取对应检测记录
            List<IotMeasureDetectDO> detectDOS = detectGroupMap.get(e.getId());
            if (CollUtil.isEmpty(detectDOS)) {
                return;
            }
            // 取创建时间最新一条
            detectDOS.stream()
                    .max(Comparator.comparing(IotMeasureDetectDO::getCreateTime))
                    .ifPresent(latestDetect -> {
                        String detectDateStr = null;
                        String detectDate = latestDetect.getDetectDate();
                        if (StringUtils.isNotBlank(detectDate)) {
                            try {
                                long timeStamp = Long.parseLong(detectDate);
                                Date date = new Date(timeStamp);
                                detectDateStr = sdf.format(date);
                            } catch (NumberFormatException ex) {
                                // 时间戳格式非法，忽略
                            }
                        }
                        e.setDetectDate(detectDateStr);
                        e.setDetectOrg(latestDetect.getDetectOrg());
                        e.setDetectContent(latestDetect.getDetectContent());
                        e.setValidityPeriod(latestDetect.getValidityPeriod());
                        e.setDetectAmount(latestDetect.getDetectAmount());
                        e.setMeasureCertNo(latestDetect.getMeasureCertNo());
                        e.setDetectStandard(latestDetect.getDetectStandard());
                    });
            // 删掉原来的 results.add(e); 这一行是报错根源
        });
        // 导出 Excel
        ExcelUtils.write(response, "计量器具台账.xls", "数据", QhseMeasureExportVO.class, results);
    }


    @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);
        }
        //到期
        IotMeasureBookPageReqVO reqVO = new IotMeasureBookPageReqVO();
        reqVO.setExpired(true);
        reqVO.setAlertWarn(null);
        long expired = iotMeasureBookMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        reqVO.setExpired(null);
        reqVO.setAlertWarn(true);
        //90天预警
        long warn = iotMeasureBookMapper.selectCountByDeptAndExpireAndWarn(reqVO, ids);
        reqVO.setAlertWarn(null);
        List<IotMeasureBookDO> iotMeasureBookDOS = iotMeasureBookMapper.selectListByDept(reqVO, ids);
        Map<String, Long> classifyCountMap = iotMeasureBookDOS.stream()
                .collect(Collectors.groupingBy(
                        IotMeasureBookDO::getClassify,
                        Collectors.counting()  // 直接统计每个分组的数量
                ));
        List<ClassifyMeasureBookStatVo> results = new ArrayList<>();
        List<DictDataDO> dictType = dictDataService.getDictDataListByDictType("measure_type");
        classifyCountMap.forEach((key, value) -> dictType.stream().filter(e -> e.getValue().equals(key)).findFirst().ifPresent(f ->{
            ClassifyMeasureBookStatVo statVo = new ClassifyMeasureBookStatVo();
            statVo.setClassify(f.getLabel());
            statVo.setCount(value);
            statVo.setSort(f.getSort());
            results.add(statVo);
        }));

        return success(ImmutableMap.of("expired", expired, "warn", warn, "classify", results));
    }

    @Data
    public static class ClassifyMeasureBookStatVo {
        private String classify;
        private Long count;
        private Integer sort;
    }


    @GetMapping("/init")
    @PermitAll
    public void init() {
        List<DeptRespDTO> deptList = deptApi.getDeptList();
        deptList.stream().filter(e -> "2".equals(e.getType())||"3".equals(e.getType())).forEach(f ->{
            //获取该部门下的所有证书
            List<IotMeasureBookDO> iotMeasureBookDOS = iotMeasureBookMapper.selectList("dept_id", f.getId());
            Map<String, List<IotMeasureBookDO>> collect = iotMeasureBookDOS.stream().collect(Collectors.groupingBy(IotMeasureBookDO::getClassify));
            String code;

            if (Objects.nonNull(f.getId())) {
                DeptRespDTO dept = deptApi.getDept(f.getId());
                if (Objects.nonNull(dept)) {
                    //获取队伍代码大写
                    String convert = ChineseLetterUtil.convert(dept.getName());
                    //获取公司代码大写
                    String company = deptUtil.getCompanyCode(f.getId()).toUpperCase();
                    //获取项目部代码大写
                    String jsaNo = getJSANo(f.getId());
                    StringBuilder sb = new StringBuilder();
                    if (jsaNo != null && !jsaNo.trim().isEmpty()) {
                        for (char c : jsaNo.toCharArray()) {
                            if (isChinese(c)) {
                                // 中文转拼音首字母（大写）
                                sb.append(getFirstLetterPinyin(c));
                            } else {
                                // 非中文直接保留
                                sb.append(c);
                            }
                        }
                    }
                    if (StringUtils.isBlank(jsaNo)){throw new ServiceException(new ErrorCode(2,"获取项目部编号失败"));}
                    code = company+sb.toString()+convert;
                } else {
                    code = "";
                }
            } else {
                code = "";
            }
            if (StringUtils.isNotBlank(code)) {
                collect.forEach((key, value) -> {
                    for (int i = 0; i < value.size(); i++) {
                        IotMeasureBookDO iotMeasureBookDO = value.get(i);
                        iotMeasureBookDO.setMeasureCode(code+key+(i+1));
                        iotMeasureBookMapper.updateById(iotMeasureBookDO);
                    }
                });
            }
        });
    }

    public String getJSANo(Long loginUserDeptId) {
        String companyCode = deptUtil.getCompanyCode(loginUserDeptId);
        if ("jt".equals(companyCode)) {
            return "";
        }
        DeptRespDTO dept = deptApi.getDept(loginUserDeptId);
        if (Objects.isNull(dept)) {
            return "";
        }
        Long parentId = dept.getParentId();
        if (Objects.isNull(parentId)) {
            return "";
        }
        DeptRespDTO dept1 = deptApi.getDeptNoPermission(parentId);
        if (Objects.isNull(dept1)) {
            return "";
        }
        String name = dept1.getName();
        if (name.contains("项目部")) {
            companyCode = StringUtils.substringBeforeLast(name, "项目部");
        } else {
            companyCode = ChineseLetterUtil.convert(name);
        }

        return companyCode;
    }
}
