package org.wcs.serve.service.impl;

import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.wcs.constant.enums.database.BaseErroorEquipmentTypeEnum;
import org.wcs.factory.AppServeResponseFactory;
import org.wcs.mapper.intf.AppBaseErrInfoService;
import org.wcs.model.bo.tuple.Tuple2;
import org.wcs.model.dto.serve.baseError.QueryBaseErrorReq;
import org.wcs.model.dto.serve.baseError.UpdateBaseErrorReq;
import org.wcs.model.po.app.AppBaseErrInfo;
import org.wcs.model.vo.serve.AppServeDataResponse;
import org.wcs.model.vo.serve.AppServeResponse;
import org.wcs.model.dto.serve.baseError.AddBaseErrorReq;
import org.wcs.model.vo.serve.baseError.BaseErrorImport;
import org.wcs.model.vo.serve.baseError.QueryBaseErrorVo;
import org.wcs.model.vo.serve.common.PageDataResponse;
import org.wcs.plugin.excel.ExcelPoi;
import org.wcs.serve.service.intf.IBaseErrorService;
import org.wcs.utils.AppBeanUtils;
import org.wcs.utils.AppStringUtils;
import org.wcs.utils.AppUUIDUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class BaseErrorService implements IBaseErrorService {

    private final ExcelPoi excelPoi;
    private final AppBaseErrInfoService baseErrInfoService;

    /**
     * 下载导入模板
     * @param response 响应
     */
    @Override
    public void downLoadImportExample(HttpServletResponse response) {
        List<BaseErrorImport> importList = new ArrayList<>();
        BaseErrorImport import1 = new BaseErrorImport();
        import1.setEquipmentName("设备类型，仅支持数字：0-堆垛机；1-托盘线；2-箱式线；3-小车");
        import1.setErrCode("错误码,支持数字和字符串");
        import1.setErrLevel("错误等级，仅支持数字：0-普通；1-注意；2-紧急；3-崩溃");
        import1.setErrType("错误类型，仅支持数字：0-通讯异常；1-电源异常；2-硬件异常");
        import1.setErrMsg("错误信息，不超过100个字符");
        import1.setSuggest("建议，不超过100个字符");
        import1.setRemark("备注，可不填;【导入前删除本行】");
        importList.add(import1);
        try {
            excelPoi.doWriteExcel("错误码导入模板", response, importList, BaseErrorImport.class);
        } catch (Exception e) {
            log.error("下载导入模板失败", e);
        }
    }

    /**
     * 查询基础错误列表
     * @param request 请求参数
     * @param pageSize 页大小
     * @param pageIndex 页索引
     * @return 基础错误列表
     */
    @Override
    public AppServeDataResponse<PageDataResponse<QueryBaseErrorVo>> queryBaseErrorList(QueryBaseErrorReq request, Integer pageSize, Integer pageIndex) {
        if(request == null || pageSize == null || pageIndex == null || pageSize <= 0 || pageIndex <= 0) {
            return AppServeResponseFactory.fail("参数错误", null);
        }
        Tuple2<Long, List<AppBaseErrInfo>> baseErrorListPageData = baseErrInfoService.queryBaseErrorList(request, pageSize, pageIndex);
        if(baseErrorListPageData == null) {
            return AppServeResponseFactory.fail("查询失败，数据服务异常", null);
        }
        PageDataResponse<QueryBaseErrorVo> pageDataResponse = new PageDataResponse<>();
        pageDataResponse.setPageIndex(pageIndex);
        pageDataResponse.setPageSize(pageSize);
        pageDataResponse.setTotalCount(baseErrorListPageData.getItem1());
        pageDataResponse.setData(AppBeanUtils.copyListProperties(baseErrorListPageData.getItem2(), QueryBaseErrorVo::new));
        return AppServeResponseFactory.success("查询成功", pageDataResponse);
    }

    /**
     * 添加基础错误
     * @param request 添加基础错误请求参数
     * @return 添加结果
     */
    @Override
    public AppServeResponse addBaseError(AddBaseErrorReq request) {
        List<AppBaseErrInfo> appBaseErrInfos = baseErrInfoService.queryBaseErrorList(request.getEquipmentType(), request.getErrCode());
        if(appBaseErrInfos == null) {
            return AppServeResponseFactory.fail("数据服务异常");
        }
        if(!appBaseErrInfos.isEmpty()) {
            return AppServeResponseFactory.fail("该资料已存在，请先核实");
        }
        AppBaseErrInfo appBaseErrInfo = new AppBaseErrInfo();
        appBaseErrInfo.setId(AppUUIDUtils.getNewUUID());
        appBaseErrInfo.setEquipmentType(request.getEquipmentType());
        appBaseErrInfo.setErrCode(request.getErrCode());
        appBaseErrInfo.setErrLevel(request.getErrLevel());
        appBaseErrInfo.setErrType(request.getErrType());
        appBaseErrInfo.setErrMsg(request.getErrMsg());
        appBaseErrInfo.setSuggest(request.getSuggest());
        appBaseErrInfo.setRemark(request.getRemark());
        if(baseErrInfoService.addBaseError(appBaseErrInfo) <= 0) {
            return AppServeResponseFactory.fail("添加失败，数据服务异常");
        }
        return AppServeResponseFactory.success();
    }

    /**
     * 导入基础错误
     * @param fileUpload 文件上传
     */
    @Override
    public AppServeResponse importBaseError(MultipartFile fileUpload) {
        if(fileUpload == null) {
            log.error("导入基础错误失败，请上传文件");
            return AppServeResponseFactory.fail("请上传文件");
        }
        String originalFilename = fileUpload.getOriginalFilename();
        if(originalFilename == null || !originalFilename.endsWith(".xlsx")) {
            log.error("导入基础错误失败，请上传正确的文件，传入的文件名称：{}", originalFilename);
            return AppServeResponseFactory.fail("请上传正确的文件");
        }
        try {
            List<BaseErrorImport> importList = excelPoi.doReadExcelOnlyHeader(fileUpload, BaseErrorImport.class);
            if(importList == null || importList.isEmpty()) {
                log.error("导入基础错误失败，疑似文件格式不正确，传入的文件名称：{}", originalFilename);
                return AppServeResponseFactory.fail("请上传正确的文件");
            }
            List<AppBaseErrInfo> appBaseErrInfos = new ArrayList<>();
            for (BaseErrorImport baseErrorImport : importList) {
                if(AppStringUtils.isEmpty(baseErrorImport.getEquipmentName()) || AppStringUtils.isEmpty(baseErrorImport.getErrCode())
                        || AppStringUtils.isEmpty(baseErrorImport.getErrLevel()) || AppStringUtils.isEmpty(baseErrorImport.getErrType())) {
                    continue;
                }
                AppBaseErrInfo appBaseErrInfo = new AppBaseErrInfo();
                appBaseErrInfo.setId(AppUUIDUtils.getNewUUID());
                appBaseErrInfo.setEquipmentType(Integer.valueOf(baseErrorImport.getEquipmentName()));
                appBaseErrInfo.setErrCode(baseErrorImport.getErrCode());
                appBaseErrInfo.setErrLevel(Integer.valueOf(baseErrorImport.getErrLevel()));
                appBaseErrInfo.setErrType(Integer.valueOf(baseErrorImport.getErrType()));
                appBaseErrInfo.setErrMsg(baseErrorImport.getErrMsg());
                appBaseErrInfo.setSuggest(baseErrorImport.getSuggest());
                appBaseErrInfo.setRemark(baseErrorImport.getRemark());
                appBaseErrInfos.add(appBaseErrInfo);
            }
            boolean insertResult = baseErrInfoService.addBaseErrorList(appBaseErrInfos);
            if(!insertResult) {
                log.error("导入基础错误失败，数据服务异常");
                return AppServeResponseFactory.fail("导入失败，数据服务异常");
            }
            log.info("导入基础错误成功，导入文件名称：{}", originalFilename);
            return AppServeResponseFactory.success();
        } catch (Exception e) {
            log.error("解析导入模板失败", e);
            return AppServeResponseFactory.fail("导入失败，请检查文件格式");
        }
    }

    /**
     * 根据设备型号删除基础错误
     * @param equipmentType 设备类型
     * @return 删除结果
     */
    @Override
    public AppServeResponse deleteBaseErrorByEquipmentType(Integer equipmentType) {
        if(equipmentType == null) {
            return AppServeResponseFactory.fail("参数错误", null);
        }
        String name = BaseErroorEquipmentTypeEnum.getName(equipmentType);
        if(name == null) {
            return AppServeResponseFactory.fail("参数错误，传入的设备类型不合法", null);
        }
        int deleteRows = baseErrInfoService.deleteBaseErrorByEquipmentType(equipmentType);
        if(deleteRows <= 0) {
            return AppServeResponseFactory.fail("删除失败，数据服务异常");
        }
        return AppServeResponseFactory.success();
    }

    /**
     * 根据id删除基础错误
     * @param id id
     * @return 删除结果
     */
    @Override
    public AppServeResponse deleteBaseErrorById(String id) {
        if(id == null) {
            return AppServeResponseFactory.fail("参数错误", null);
        }
        List<AppBaseErrInfo> appBaseErrInfoList = baseErrInfoService.queryById(id);
        if(appBaseErrInfoList == null) {
            return AppServeResponseFactory.fail("数据服务异常");
        }
        if(appBaseErrInfoList.isEmpty()) {
            return AppServeResponseFactory.fail("该资料不存在，请刷新后再试");
        }
        int deleteRows = baseErrInfoService.deleteById(id);
        if(deleteRows <= 0) {
            return AppServeResponseFactory.fail("删除失败，数据服务异常");
        }
        return AppServeResponseFactory.success();
    }

    /**
     * 修改基础错误
     * @param request 修改基础错误请求
     * @return 修改结果
     */
    @Override
    public AppServeResponse updateBaseError(UpdateBaseErrorReq request) {
        List<AppBaseErrInfo> appBaseErrInfoList = baseErrInfoService.queryById(request.getId());
        if(appBaseErrInfoList == null) {
            return AppServeResponseFactory.fail("数据服务异常");
        }
        if(appBaseErrInfoList.isEmpty()) {
            return AppServeResponseFactory.fail("该资料不存在，请刷新后再试");
        }
        AppBaseErrInfo appBaseErrInfo = new AppBaseErrInfo();
        appBaseErrInfo.setId(request.getId());
        appBaseErrInfo.setEquipmentType(request.getEquipmentType());
        appBaseErrInfo.setErrCode(request.getErrCode());
        appBaseErrInfo.setErrLevel(request.getErrLevel());
        appBaseErrInfo.setErrType(request.getErrType());
        appBaseErrInfo.setErrMsg(request.getErrMsg());
        appBaseErrInfo.setSuggest(request.getSuggest());
        appBaseErrInfo.setRemark(request.getRemark());
        int updateRows = baseErrInfoService.updateBaseError(appBaseErrInfo);
        if(updateRows <= 0) {
            return AppServeResponseFactory.fail("修改失败，数据服务异常");
        }
        return AppServeResponseFactory.success();
    }

    /**
     * 根据设备型号查询基础错误
     * @param equipmentType 设备型号
     * @param errCode 错误码
     * @return 查询结果
     */
    @Override
    public AppServeDataResponse<QueryBaseErrorVo> getBaseError(Integer equipmentType, String errCode) {
        List<AppBaseErrInfo> appBaseErrInfos = baseErrInfoService.queryByEquipmentTypeAndErrorCode(equipmentType, errCode);
        if(appBaseErrInfos == null) {
            return AppServeResponseFactory.fail("数据服务异常", null);
        }
        if(appBaseErrInfos.isEmpty()) {
            return AppServeResponseFactory.fail("该资料不存在，请刷新后再试", null);
        }
        AppBaseErrInfo first = appBaseErrInfos.getFirst();
        QueryBaseErrorVo queryBaseErrorVo = new QueryBaseErrorVo();
        AppBeanUtils.copyProperties(first, queryBaseErrorVo);
        return AppServeResponseFactory.success(queryBaseErrorVo);
    }
}
