/*
* Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved.
*
*/
package net.northking.cctp.device.api.model.service;

import net.northking.cctp.common.cache.EntityNameCache;
import net.northking.cctp.common.cache.EntityNameCatalog;
import net.northking.cctp.common.db.BasicService;
import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.db.annotation.DatabaseReadOnly;
import net.northking.cctp.common.db.annotation.DatabaseWriteOnly;
import net.northking.cctp.common.db.excel.AbstractExcelService;
import net.northking.cctp.common.db.excel.ExcelHeader;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.util.UUIDUtil;

import net.northking.cctp.device.constants.DeviceConstants;
import net.northking.cctp.device.constants.DeviceError;
import net.northking.cctp.device.db.entity.CdMobileBrand;
import net.northking.cctp.device.db.entity.CdMobileDevice;
import net.northking.cctp.device.db.service.CdDeviceModelService;
import net.northking.cctp.device.db.entity.CdDeviceModel;


import net.northking.cctp.device.db.service.CdMobileBrandService;
import net.northking.cctp.device.db.service.CdMobileDeviceService;
import net.northking.cctp.device.dto.brand.CdMobileBrandDetailDto;
import net.northking.cctp.device.dto.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备型号管理表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

@Service
@ConditionalOnMissingBean(name = "CdDeviceModelApiServiceImpl")
public class CdDeviceModelApiServiceImpl extends AbstractExcelService<CdDeviceModel> implements CdDeviceModelApiService
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(CdDeviceModelApiServiceImpl.class);

  @Autowired
  private CdDeviceModelService cdDeviceModelService;

  @Autowired
  private CdMobileDeviceService cdMobileDeviceService;

  @Autowired
  private CdMobileBrandService cdMobileBrandService;

  @Autowired
  private EntityNameCache entityNameCache;

  //= Excel 导入导出相关代码 start ==================//
  @Override
  public BasicService<CdDeviceModel> getService()
  {
    return this.cdDeviceModelService;
  }

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("机型id", "id", String.class);
    ExcelHeader modelName = new ExcelHeader("机型名称", "modelName", String.class);
    ExcelHeader brandId = new ExcelHeader("所属品牌", "brandId", String.class);
    ExcelHeader prodouctName = new ExcelHeader("产品名称", "prodouctName", String.class);
    ExcelHeader screenSize = new ExcelHeader("屏幕尺寸", "screenSize", String.class);
    ExcelHeader resolution = new ExcelHeader("分辨率", "resolution", String.class);
    ExcelHeader type = new ExcelHeader("类型", "type", String.class);
    ExcelHeader modelImg = new ExcelHeader("机型图片", "modelImg", byte[].class);
    ExcelHeader systemVersion = new ExcelHeader("系统版本", "systemVersion", String.class);
    ExcelHeader cpuCoreNum = new ExcelHeader("cpu核心数", "cpuCoreNum", Integer.class);
    ExcelHeader cpuModel = new ExcelHeader("cpu型号", "cpuModel", String.class);
    ExcelHeader cpuBrand = new ExcelHeader("cpu品牌", "cpuBrand", String.class);
    ExcelHeader ramSize = new ExcelHeader("内存大小", "ramSize", String.class);
    ExcelHeader createdBy = new ExcelHeader("创建人", "createdBy", String.class);
    ExcelHeader createdTime = new ExcelHeader("创建时间", "createdTime", Date.class);
    ExcelHeader updatedBy = new ExcelHeader("更新人", "updatedBy", String.class);
    ExcelHeader updatedTime = new ExcelHeader("更新时间", "updatedTime", Date.class);
    return new ExcelHeader[]{};
  }

  /**
   * Excel导入，入库之前的处理
   * @param records 从Excel读取到的记录
   * @return 待入库的记录
   */
  @Override
  protected List<CdDeviceModel> beforeInsertBatch(List<CdDeviceModel> records)
  {
    for (CdDeviceModel record : records)
    {
      record.setId(UUIDUtil.create32UUID());
    }
    return records;
  }

  /**
   * 写入Excel之前的处理<br>
   * 数据的特殊处理在此处加工处理
   *
   * @param record 来自数据库记录
   * @return 待写入Excel的记录
   */
  @Override
  protected CdDeviceModel beforeWriteExcel(CdDeviceModel record)
  {
    return record;
  }

  @Override
  @DatabaseReadOnly
  public Pagination<CdDeviceModelDetailDto> pagingQuery(QueryByPage<CdDeviceModelQueryDto> queryByPage)
  {
    return this.cdDeviceModelService.pageQuery(queryByPage);
  }

  @Override
  @DatabaseWriteOnly
  public String add(CdDeviceModelAddDto dto)
  {
    //设备名称不能重名
    CdDeviceModel deviceModel = new CdDeviceModel();
    deviceModel.setModelName(dto.getModelName());
    List<CdDeviceModel> query = this.cdDeviceModelService.query(deviceModel);
    if (query.size()>0){
      throw new PlatformRuntimeException(DeviceError.MODEL_IS_EXIST,dto.getModelName());
    }
    String uuid = UUIDUtil.create32UUID();
    CdDeviceModel entity = new CdDeviceModel();
    BeanUtils.copyProperties(dto, entity);
    entity.setId(uuid);
     this.cdDeviceModelService.insert(entity);
    return uuid;
  }

  @Override
  @DatabaseWriteOnly
  public Integer updateByPK(CdDeviceModelUpdateDto dto) throws IllegalAccessException
  {
    //修改后的设备名称不能重名
    CdDeviceModel entity = new CdDeviceModel();
    BeanUtils.copyProperties(dto, entity);
    return this.cdDeviceModelService.updateByPrimaryKey(entity);
  }

  @Override
  @DatabaseReadOnly
  public CdDeviceModelDetailDto findByPK(String uuid)
  {
    CdDeviceModel example = new CdDeviceModel();
    example.setId(uuid);
    List<CdDeviceModel> entitys = this.cdDeviceModelService.query(example);
    if (entitys.isEmpty())
    {
      return null;
    }

    CdDeviceModelDetailDto dto = new CdDeviceModelDetailDto();
    BeanUtils.copyProperties(entitys.get(0), dto);
    String created = entityNameCache.translateById(EntityNameCatalog.MONSTER_USER, dto.getCreatedBy());
    String updated = entityNameCache.translateById(EntityNameCatalog.MONSTER_USER, dto.getUpdatedBy());
    dto.setCreatedBy(created);
    dto.setUpdatedBy(updated);

    CdMobileBrand brand = this.cdMobileBrandService.findByPrimaryKey(dto.getBrandId());
    dto.setBrandName(brand.getBrandNameCn());


    return dto;
  }

  @Override
  @DatabaseWriteOnly
  public Integer deleteByPK(String uuid)
  {
    //查询是否存在关联
    CdMobileDevice device = new CdMobileDevice();
    device.setModelId(uuid);
    List<CdMobileDevice> list = this.cdMobileDeviceService.query(device);
    if (list.size()>0){
      throw new PlatformRuntimeException(DeviceError.MODEL_DEVICE_EXIST);
    }
    CdDeviceModel entity = new CdDeviceModel();
    entity.setId(uuid);
    return this.cdDeviceModelService.deleteByExample(entity);
  }

  @Override
  public List<String> addBatch(List<CdDeviceModelAddDto> batch)
  {
    List<String> result = new ArrayList<>();
    for (CdDeviceModelAddDto dto : batch)
    {
      result.add(this.add(dto));
    }
    return result;
  }


  @Override
  public DeviceSelectDto getDeviceCondition(Map<String, Object> queryMap) {
    DeviceSelectDto result = new DeviceSelectDto();

    Set<CdMobileBrandDetailDto> brandList = new HashSet<>();

    Set<SystemVersionDto> versionList = new HashSet<>();

    Set<String> resolutionList = new HashSet<>();

    List<Map<String, String>> conditions = this.cdDeviceModelService.getDeviceCondition(queryMap);
    for (Map<String, String> condition : conditions) {
      CdMobileBrandDetailDto deviceBrandDetailDto = new CdMobileBrandDetailDto();
      //品牌赋值
      deviceBrandDetailDto.setId(condition.get(DeviceConstants.DEVICE_BRAND_ID));
      deviceBrandDetailDto.setBrandNameCn(condition.get(DeviceConstants.DEVICE_BRAND_NAME));
      brandList.add(deviceBrandDetailDto);

      //操作系统赋值
      SystemVersionDto systemVersionDto = new SystemVersionDto();
      systemVersionDto.setVersionType(condition.get(DeviceConstants.DEVICE_PLATFORM));
      systemVersionDto.setVersionCode(condition.get(DeviceConstants.DEVICE_PLATFORM_VERSION));

      //汇总系统
      versionList.add(systemVersionDto);

      //分辨率赋值
      resolutionList.add(condition.get(DeviceConstants.DEVICE_RESOLUTION));
    }

    //排序去重
    brandList = brandList.stream().collect(Collectors.toCollection(TreeSet::new));

    versionList = versionList.stream().collect(Collectors.toCollection(TreeSet::new));

    resolutionList = resolutionList.stream().sorted(new Comparator<String>() {
      @Override
      public int compare(String o1, String o2) {

        if (StringUtils.isEmpty(o2) || StringUtils.isEmpty(o1)) {
          return 1;
        }

        String[] split1 = o1.split("\\*");
        String[] split2 = o2.split("\\*");

        if (Long.valueOf(split1[0]) > Long.valueOf(split2[0])) {
          return -1;
        } else if (Long.valueOf(split1[0]) < Long.valueOf(split2[0])) {
          return 1;
        } else {
          if (Long.valueOf(split1[1]) > Long.valueOf(split2[1])) {
            return -1;
          } else if (Long.valueOf(split1[1]) < Long.valueOf(split2[1])) {
            return 1;
          } else {
            return 0;
          }
        }
      }
    }).collect(Collectors.toCollection(TreeSet::new));

    result.setBrandList(brandList);
    result.setVersionList(versionList);
    result.setResolutionList(resolutionList);
    return result;
  }


}
