package com.energy.manage.service.service.units.impl;


import cn.hutool.core.bean.BeanUtil;
import com.energy.manage.common.base.BaseServiceImpl;
import com.energy.manage.common.base.Page;
import com.energy.manage.common.constant.redis.ManagerRedisKeyConstant;
import com.energy.manage.common.enums.DeleteStatusEnum;
import com.energy.manage.common.enums.IdPrefixEnum;
import com.energy.manage.common.po.units.UnitDictBrandModelPO;
import com.energy.manage.common.po.units.UnitDictConstantsPO;
import com.energy.manage.common.util.IdGeneratorUtil;
import com.energy.manage.service.domain.dto.units.*;
import com.energy.manage.service.domain.vo.units.UnitDictBrandModelVo;
import com.energy.manage.service.domain.vo.units.UnitDictConstantsVo;
import com.energy.manage.service.mappers.units.UnitDictBrandModelMapper;
import com.energy.manage.service.mappers.units.UnitDictConstantsMapper;
import com.energy.manage.service.service.cache.CacheService;
import com.energy.manage.service.service.dict.DictConstantsService;
import com.energy.manage.service.service.units.UnitDictConstantsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * 部件字典表接口
 */
@Slf4j
@Service
public class UnitDictConstantsServiceImpl extends BaseServiceImpl<UnitDictConstantsPO> implements UnitDictConstantsService {

    @Autowired
    private UnitDictConstantsMapper dictConstantsMapper;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private DictConstantsService dictConstantsService;

    @Autowired
    private UnitDictBrandModelMapper unitDictBrandModelMapper;

    // 定义字典中部件模块类型
    private final int unit_module_number = 3;

    // 定义字典中部件类型
    private final int associated_function_type_number = 5;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUnitDict(UnitDictConstantsDto unitDictConstantsDto) {

        UnitDictConstantsPO unitDictConstantsPO = new UnitDictConstantsPO();
        BeanUtil.copyProperties(unitDictConstantsDto, unitDictConstantsPO);
        unitDictConstantsPO.setDelState(DeleteStatusEnum.NODELETE.getCode());
        String contentsTypeCode = IdPrefixEnum.UNIT_DICT_TYPE_CODE.getCode().concat(IdGeneratorUtil.zeroFillUtil(cacheService.incr(ManagerRedisKeyConstant.build(ManagerRedisKeyConstant.IDGENERATOR_CONSTANTS_KEY, IdPrefixEnum.UNIT_DICT_TYPE_CODE.getCode()))));

        // 初始化字典值
        long contentsValue = 0;
        UnitDictConstantsPO po = new UnitDictConstantsPO();
        po.setParentId(0L);
        int count = dictConstantsMapper.selectCount(po);
        if (count == 0) {
            contentsValue = cacheService.incrBy(ManagerRedisKeyConstant.IDGENERATOR_UDTC_KEY, 1000L);
        }
        contentsValue = cacheService.incr(ManagerRedisKeyConstant.IDGENERATOR_UDTC_KEY);

        unitDictConstantsPO.setContentsValue(Integer.valueOf(String.valueOf(contentsValue)));
        unitDictConstantsPO.setContentsType(contentsTypeCode);
        unitDictConstantsPO.setCreateTime(new Date());
        unitDictConstantsPO.setUpdateTime(new Date());

        return dictConstantsMapper.insertUseGeneratedKeys(unitDictConstantsPO) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUnitDict(UnitDictConstantsUpdateDto unitDictConstantsUpdateDto) {

        UnitDictConstantsPO po = new UnitDictConstantsPO();
        po.setContentsName(unitDictConstantsUpdateDto.getContentsName());
        po.setUpdateTime(new Date());
        po.setUpdateBy(unitDictConstantsUpdateDto.getUpdateBy());
        Example queryExample = new Example(UnitDictConstantsPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("id", unitDictConstantsUpdateDto.getId());
        return dictConstantsMapper.updateByExampleSelective(po, queryExample) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delUnitDict(UnitDictConstantsDelDto unitDictConstantsDelDto) {
        UnitDictConstantsPO po = new UnitDictConstantsPO();
        po.setDelState(DeleteStatusEnum.DELETE.getCode());
        po.setUpdateTime(new Date());
        po.setUpdateBy(unitDictConstantsDelDto.getUpdateBy());
        Example queryExample = new Example(UnitDictConstantsPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        // 当删除字典时同类型属性也删除
        criteria.andEqualTo("contentsType", unitDictConstantsDelDto.getContentsType());
        return dictConstantsMapper.updateByExampleSelective(po, queryExample) > 0;
    }

    @Override
    public Page<UnitDictConstantsVo> getUnitDictConstantsPage(UnitDictConstantsPageDto unitDictConstantsPageDto) {

        PageHelper.startPage(unitDictConstantsPageDto.getPageNum(), unitDictConstantsPageDto.getPageSize());
        Example queryExample = new Example(UnitDictConstantsPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        queryExample.setOrderByClause("unit_module asc");
        if (!StringUtils.isEmpty(unitDictConstantsPageDto.getContentsName())) {
            criteria.andLike("contentsName", "%" + unitDictConstantsPageDto.getContentsName() + "%");
        }

        criteria.andEqualTo("delState", DeleteStatusEnum.NODELETE.getCode());
        criteria.andEqualTo("parentId", 0);
        List<UnitDictConstantsPO> list = dictConstantsMapper.selectByExample(queryExample);

        UnitDictConstantsVo vo = null;
        List<UnitDictConstantsVo> unitDictConstantsVoArrayList = Lists.newArrayList();
        for (UnitDictConstantsPO po : list) {
            vo = new UnitDictConstantsVo();
            BeanUtil.copyProperties(po, vo);
            vo.setUnitModuleName(dictConstantsService.getDictConstantsMap(this.unit_module_number).get(po.getUnitModule()));
            vo.setAssociatedFunctionTypeName(dictConstantsService.getDictConstantsMap(this.associated_function_type_number).get(po.getAssociatedFunctionType()));
            unitDictConstantsVoArrayList.add(vo);
        }

        Long total = org.apache.commons.collections.CollectionUtils.isEmpty(list) ? 0L : new PageInfo<>(list).getTotal();
        return Page.build(unitDictConstantsPageDto.getPageNum(), unitDictConstantsPageDto.getPageSize(), total, unitDictConstantsVoArrayList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUnitDictProperty(UnitDictConstantsDto unitDictConstantsDto) {

        UnitDictConstantsPO unitDictConstantsPO = new UnitDictConstantsPO();
        BeanUtil.copyProperties(unitDictConstantsDto, unitDictConstantsPO);
        unitDictConstantsPO.setDelState(DeleteStatusEnum.NODELETE.getCode());

        // 初始化字典值
        long contentsValue = cacheService.incr(ManagerRedisKeyConstant.build(ManagerRedisKeyConstant.IDGENERATOR_UDPC_KEY, unitDictConstantsDto.getContentsType()));

        unitDictConstantsPO.setContentsValue(Integer.valueOf(String.valueOf(contentsValue)));
        unitDictConstantsPO.setCreateTime(new Date());
        unitDictConstantsPO.setUpdateTime(new Date());

        return dictConstantsMapper.insertUseGeneratedKeys(unitDictConstantsPO) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delUnitDictProperty(UnitDictConstantsPDelDto unitDictConstantsPDelDto) {

        UnitDictConstantsPO po = new UnitDictConstantsPO();
        po.setDelState(DeleteStatusEnum.DELETE.getCode());
        po.setUpdateTime(new Date());
        po.setUpdateBy(unitDictConstantsPDelDto.getUpdateBy());
        Example queryExample = new Example(UnitDictConstantsPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("id", unitDictConstantsPDelDto.getId());
        return dictConstantsMapper.updateByExampleSelective(po, queryExample) > 0;

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUnitDictProperty(UnitDictConstantsUpdateDto unitDictConstantsUpdateDto) {

        UnitDictConstantsPO po = new UnitDictConstantsPO();
        po.setContentsName(unitDictConstantsUpdateDto.getContentsName());
        po.setUpdateTime(new Date());
        po.setUpdateBy(unitDictConstantsUpdateDto.getUpdateBy());
        Example queryExample = new Example(UnitDictConstantsPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("id", unitDictConstantsUpdateDto.getId());
        return dictConstantsMapper.updateByExampleSelective(po, queryExample) > 0;
    }


    @Override
    public List<UnitDictConstantsVo> getUnitDictConstantsList(String contentsType) {
        Example queryExample = new Example(UnitDictConstantsPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("delState", DeleteStatusEnum.NODELETE.getCode());
        criteria.andEqualTo("contentsType", contentsType);
        criteria.andGreaterThan("parentId", 0);
        List<UnitDictConstantsPO> list = dictConstantsMapper.selectByExample(queryExample);
        UnitDictConstantsVo vo = null;
        List<UnitDictConstantsVo> unitDictConstantsVoArrayList = Lists.newArrayList();
        for (UnitDictConstantsPO po : list) {
            vo = new UnitDictConstantsVo();
            BeanUtil.copyProperties(po, vo);
            unitDictConstantsVoArrayList.add(vo);
        }
        return unitDictConstantsVoArrayList;
    }

    @Override
    public UnitDictConstantsVo getUnitDictConstants(Integer id) {
        UnitDictConstantsVo vo = new UnitDictConstantsVo();
        UnitDictConstantsPO po = dictConstantsMapper.selectByPrimaryKey(id);
        BeanUtil.copyProperties(po, vo);
        return vo;
    }

    @Override
    public Page<UnitDictBrandModelVo> getUnitDictBrandModelPage(UnitDictBrandModelPageDto unitDictBrandModelPageDto) {

        PageHelper.startPage(unitDictBrandModelPageDto.getPageNum(), unitDictBrandModelPageDto.getPageSize());
        Example queryExample = new Example(UnitDictBrandModelPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        if (!StringUtils.isEmpty(unitDictBrandModelPageDto.getManufacture())) {
            criteria.andLike("manufacture", "%" + unitDictBrandModelPageDto.getManufacture() + "%");
        }
        if (!StringUtils.isEmpty(unitDictBrandModelPageDto.getModelNumber())) {
            criteria.andLike("modelNumber", "%" + unitDictBrandModelPageDto.getModelNumber() + "%");
        }
        // 部件类型
        criteria.andEqualTo("unitType", unitDictBrandModelPageDto.getContentsDictKey());
        List<UnitDictBrandModelPO> list = unitDictBrandModelMapper.selectByExample(queryExample);

        UnitDictBrandModelVo vo = null;
        List<UnitDictBrandModelVo> unitDictBrandModelVos = Lists.newArrayList();
        for (UnitDictBrandModelPO po : list) {
            vo = new UnitDictBrandModelVo();
            BeanUtil.copyProperties(po, vo);
            unitDictBrandModelVos.add(vo);
        }

        Long total = org.apache.commons.collections.CollectionUtils.isEmpty(list) ? 0L : new PageInfo<>(list).getTotal();
        return Page.build(unitDictBrandModelPageDto.getPageNum(), unitDictBrandModelPageDto.getPageSize(), total, unitDictBrandModelVos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUnitDictBrandModel(UnitDictBrandModelDto unitDictBrandModelDto) {
        UnitDictBrandModelPO po = new UnitDictBrandModelPO();
        BeanUtil.copyProperties(unitDictBrandModelDto, po);
        po.setCreateTime(new Date());

        return unitDictBrandModelMapper.insertUseGeneratedKeys(po) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUnitDictBrandModel(UnitDictBrandModelUpdateDto unitDictBrandModelUpdateDto) {
        UnitDictBrandModelPO po = new UnitDictBrandModelPO();
        po.setManufacture(unitDictBrandModelUpdateDto.getManufacture());
        po.setModelNumber(unitDictBrandModelUpdateDto.getModelNumber());
        Example queryExample = new Example(UnitDictBrandModelPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("id", unitDictBrandModelUpdateDto.getId());

        return unitDictBrandModelMapper.updateByExampleSelective(po, queryExample) > 0;
    }

    @Override
    public boolean updateUnitDictBrandParameterModel(UnitDictBrandModelParameterUpdateDto unitDictBrandModelParameterUpdateDto) {
        UnitDictBrandModelPO po = new UnitDictBrandModelPO();
        po.setRollsNumber(unitDictBrandModelParameterUpdateDto.getRollsNumbe());
        po.setRollsDiameter(unitDictBrandModelParameterUpdateDto.getRollsDiameter());
        po.setCircleDiameter(unitDictBrandModelParameterUpdateDto.getCircleDiameter());
        po.setThetaDeg(unitDictBrandModelParameterUpdateDto.getThetaDeg());
        po.setCreateTime(new Date());
        Example queryExample = new Example(UnitDictBrandModelPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("id", unitDictBrandModelParameterUpdateDto.getId());

        return unitDictBrandModelMapper.updateByExampleSelective(po, queryExample) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delUnitDictBrandModel(UnitDictBrandModelIdDto unitDictBrandModelIdDto) {
        return unitDictBrandModelMapper.deleteByPrimaryKey(unitDictBrandModelIdDto.getId()) > 0;
    }

    @Override
    public List<String> getUnitDictBrandModelList(UnitDictBrandModelDto unitDictBrandModelDto) {
        if (StringUtils.isEmpty(unitDictBrandModelDto.getManufacture())) {
            return unitDictBrandModelMapper.selectUnitManufactureByUnitType(unitDictBrandModelDto.getUnitType());
        }
        return unitDictBrandModelMapper.selectUnitModelNumberByManufacture(unitDictBrandModelDto.getUnitType(),
                unitDictBrandModelDto.getManufacture());
    }

    @Override
    public boolean verifyUnitDictBrandModel(UnitDictBrandModelDto dto) {
        Example queryExample = new Example(UnitDictBrandModelPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("unitType", dto.getUnitType());
        criteria.andEqualTo("manufacture", dto.getManufacture());
        criteria.andEqualTo("modelNumber", dto.getModelNumber());
        int count = unitDictBrandModelMapper.selectCountByExample(queryExample);
        return count > 0 ? true : false;
    }

    @Override
    public boolean verifyUnitDictModel(UnitDictConstantsDto unitDictConstantsDto) {
        Example queryExample = new Example(UnitDictConstantsPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("unitModule", unitDictConstantsDto.getUnitModule());
        criteria.andEqualTo("contentsDictKey", unitDictConstantsDto.getContentsDictKey());
        criteria.andEqualTo("associatedFunctionType", unitDictConstantsDto.getAssociatedFunctionType());
        return dictConstantsMapper.selectCountByExample(queryExample) > 0 ? true : false;
    }

//    /**
//     * 删除品牌对应型号
//     *
//     * @param brandKey
//     * @return
//     */
//    private void delBrandRedisKey(String brandKey) {
//        String brandlistKey = ManagerRedisKeyConstant.build(ManagerRedisKeyConstant.IDGENERATOR_UDPB_KEY, brandKey);
//        cacheService.delete(brandlistKey);
//    }

}
