package com.sckw.slope.detection.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.DeviceEnum;
import com.sckw.core.model.enums.DictEnum;
import com.sckw.core.model.enums.MessageLogEnum;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.response.HttpResult;
import com.sckw.slope.detection.dao.mysql.KwsDeviceModelMapper;
import com.sckw.slope.detection.dao.mysql.KwsDeviceModelPartMapper;
import com.sckw.slope.detection.dao.mysql.KwsIntegrationMapper;
import com.sckw.slope.detection.model.dos.mysql.KwsDeviceModel;
import com.sckw.slope.detection.model.dto.HeaderData;
import com.sckw.slope.detection.model.dto.SystemDict;
import com.sckw.slope.detection.model.param.DeviceModelAdd;
import com.sckw.slope.detection.model.param.DeviceModelQuery;
import com.sckw.slope.detection.model.vo.DeviceModelVo;
import com.sckw.slope.detection.model.vo.DevicePartModelVo;
import com.sckw.slope.detection.model.vo.IntegrationItemVO;
import com.sckw.slope.detection.service.repository.KwsDeviceModelRepository;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author sky
 * @description 设备model service
 * @date 2023-10-31 10:10:27
 */
@Slf4j
@Service
public class DeviceModelService {

    @Autowired
    CommonService commonService;

    @Autowired
    KwsDeviceModelMapper kwsDeviceModelMapper;

    @Autowired
    KwsDeviceModelPartMapper kwsDeviceModelPartMapper;

    @Autowired
    KwsIntegrationMapper kwsIntegrationMapper;

    /**
     * 项目管理分页查询
     *
     * @param deviceModelQuery 请求分页
     * @param response         http流
     * @return 返回值
     */
    public PageRes select(DeviceModelQuery deviceModelQuery, HttpServletRequest response) {
        PageHelper.startPage(deviceModelQuery.getPage(), deviceModelQuery.getPageSize());
        HeaderData headerData = commonService.getHeaderData(response);
        deviceModelQuery.setMountainId(headerData.getMountainId());
        List<DeviceModelVo> list = kwsDeviceModelMapper.selectListAll(deviceModelQuery);
        PageInfo<DeviceModelVo> pageInfo = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(pageInfo, list);
        }
        Map<String, SystemDict> dictList = commonService.getDictList(null, new HashMap<String, String>() {{
            put("code", DictEnum.DEVICE_TYPE.getCodeType());
            put("type", "1");
        }});

        for (DeviceModelVo vo : list) {
            vo.setStatusText(DeviceEnum.getName(vo.getStatus()));
            for (SystemDict value : dictList.values()) {
                if (vo.getDeviceType().equals(value.getValue())) {
                    vo.setDeviceType(value.getLabel());
                }
            }
        }

        return PageRes.build(pageInfo, list);
    }

    /**
     * 设备型号新增
     *
     * @param deviceModelAdd 请求参数
     * @param request        http流
     * @return 返回值
     */
    @Transactional
    public HttpResult add(DeviceModelAdd deviceModelAdd, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        KwsDeviceModel deviceModel = new KwsDeviceModel();
        BeanUtils.copyProperties(deviceModelAdd, deviceModel);
        LocalDateTime now = LocalDateTime.now();
        deviceModel.setCreateBy(Long.parseLong(headerData.getCreateBy()));
        deviceModel.setCreateTime(now);
        deviceModel.setStatus(DeviceEnum.IDENTIFYING.getCode());
        deviceModel.setUpdateBy(Long.parseLong(headerData.getUpdateBy()));
        deviceModel.setUpdateTime(now);
        deviceModel.setDelFlag(NumberConstant.ZERO);
        deviceModel.setMountainId(headerData.getMountainId());
        kwsDeviceModelMapper.insert(deviceModel);
        //新增log
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("name", deviceModel.getName());
        commonService.insertLog(MessageLogEnum.MODEL_ADD, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok();
    }

    public HttpResult detail(Long id, HttpServletRequest response) {
        KwsDeviceModel device = kwsDeviceModelMapper.selectOne(new LambdaQueryWrapper<KwsDeviceModel>()
                .eq(KwsDeviceModel::getId, id));
        DeviceModelVo vo = new DeviceModelVo();
        BeanUtils.copyProperties(device, vo);
        vo.setStatusText(DeviceEnum.getName(vo.getStatus()));
        //获取要数
        List<DevicePartModelVo> deviceModelPart = kwsDeviceModelPartMapper.selectByModelId(vo.getId());
        //获取字典
        Map<String, SystemDict> dictList = commonService.getDictList(null, new HashMap<String, String>() {{
            put("code", DictEnum.MODEL_PART.getCodeType());
            put("type", "1");
        }});
        //获取集成要素-start
        List<String> partData = new ArrayList<>();
        List<String> intList = new ArrayList<>();
        //Map<String,IntegrationItemVO> map = new HashMap<>();
        List<IntegrationItemVO> dataList = new ArrayList<>();
        for (DevicePartModelVo part : deviceModelPart) {
            for (SystemDict value : dictList.values()) {
                if (part.getPartName().equals(value.getValue())) {
                    partData.add(value.getLabel());
                    //查询对应的集成要素
                    List<IntegrationItemVO> integrationItemVO = kwsIntegrationMapper.getDataByFindInSet(value.getValue());
                    for (IntegrationItemVO intvo : integrationItemVO) {
                        if (!intList.contains(intvo.getId())) {//判断是否存在
                            intList.add(intvo.getId());
                            dataList.add(intvo);
                        }
                    }
                }
            }
        }
        //获取集成要素-end
        List<SystemDict> systemDict = new ArrayList<>();
        for (SystemDict value : dictList.values()) {
            systemDict.add((value));
        }
        //获取设备型号名称
        Map<String, SystemDict> deviceTypeList = commonService.getDictList(null, new HashMap<String, String>() {{
            put("code", DictEnum.DEVICE_TYPE.getCodeType());
            put("type", "1");
        }});


        for (SystemDict value : deviceTypeList.values()) {
            if (vo.getDeviceType().equals(value.getValue())) {
                vo.setDeviceTypeName(value.getLabel());
            }
        }
        vo.setPart(partData);
        vo.setIntegration(dataList);
        vo.setSystemDict(systemDict);
        return HttpResult.ok(vo);
    }


    @Autowired
    KwsDeviceModelRepository deviceModelRepository;

    @Transactional
    public HttpResult update(DeviceModelAdd deviceAdd, HttpServletRequest response) {
        KwsDeviceModel device = new KwsDeviceModel();
        BeanUtils.copyProperties(deviceAdd, device);
        device.setId(deviceAdd.getId());
        LocalDateTime now = LocalDateTime.now();
        device.setUpdateBy(Long.parseLong(commonService.getHeaderData(response).getUpdateBy()));
        device.setUpdateTime(now);
        deviceModelRepository.updateById(device);
        //新增log
        HeaderData headerData = commonService.getHeaderData(response);
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("name", device.getName());
        commonService.insertLog(MessageLogEnum.MODEL_UPDATE, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok();
    }

    @Transactional
    public HttpResult dels(String ids, HttpServletRequest response) {
        KwsDeviceModel has = kwsDeviceModelMapper.selectOne(new LambdaQueryWrapper<KwsDeviceModel>()
                .eq(KwsDeviceModel::getId, ids)
                .eq(KwsDeviceModel::getDelFlag, 0)
        );
        if (Objects.isNull(has)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.MODEL_NOT_EXISTS);
        }
        HeaderData headerData = commonService.getHeaderData(response);
        //List<Long> list = StringUtils.splitStrToList(ids, Long.class);
        int update = kwsDeviceModelMapper.update(null, new LambdaUpdateWrapper<KwsDeviceModel>()
                .eq(KwsDeviceModel::getId, ids)
                .eq(KwsDeviceModel::getMountainId, headerData.getMountainId())
                .set(KwsDeviceModel::getDelFlag, NumberConstant.ONE));
        if (update < 1) {
            throw new BusinessException("删除型号异常");
        }
        //新增log

        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("name", has.getName());
        commonService.insertLog(MessageLogEnum.MODEL_DELETE, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok("删除型号成功");
    }

    /**
     * 查询设备型号数据
     *
     * @param request
     * @return
     */
    public HttpResult findModelList(HttpServletRequest request) {
        List<KwsDeviceModel> kwsDeviceModels = kwsDeviceModelMapper.selectList(new LambdaQueryWrapper<KwsDeviceModel>()
                .eq(KwsDeviceModel::getDelFlag, NumberConstant.ZERO)
                .orderByDesc(KwsDeviceModel::getCreateTime)
        );
        return HttpResult.ok(kwsDeviceModels);
    }

}
