package com.zcxk.rmcp.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.zcxk.core.common.enums.StatusEnum;
import com.zcxk.core.common.exception.BusinessException;
import com.zcxk.core.oauth2.pojo.LoginUser;
import com.zcxk.core.oauth2.util.UserUtil;
import com.zcxk.core.mysql.pageing.Pagination;
import com.zcxk.core.utils.ZoniotIntegerUtils;
import com.zcxk.core.utils.ZoniotStringUtils;
import com.zcxk.rmcp.api.dto.meterreplace.MeterReplacePageDto;
import com.zcxk.rmcp.api.dto.meterreplace.WaterMeterReplaceInputDto;
import com.zcxk.rmcp.api.enums.ReplaceMethodEnum;
import com.zcxk.rmcp.api.enums.RmcpErrorEnum;
import com.zcxk.rmcp.api.vo.MeterReplaceVo;
import com.zcxk.rmcp.core.dao.DeviceMapper;
import com.zcxk.rmcp.core.dao.ProductMapper;
import com.zcxk.rmcp.core.entity.Device;
import com.zcxk.rmcp.core.entity.Product;
import com.zcxk.rmcp.web.service.MeterReplaceLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.zcxk.rmcp.core.entity.MeterReplaceLog;
import com.zcxk.rmcp.core.dao.MeterReplaceLogMapper;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 
 * @author linqingwei
 * @date 2021-07-20 17:17
 */
@Service
@Slf4j
public class MeterReplaceLogServiceImpl implements MeterReplaceLogService {

    @Resource
    private MeterReplaceLogMapper meterReplaceLogMapper;

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private ProductMapper productMapper;


    @Override
    public int insertSelective(MeterReplaceLog record) {
        return meterReplaceLogMapper.insertSelective(record);
    }

    @Override
    public int updateByPrimaryKeySelective(MeterReplaceLog record) {
        return meterReplaceLogMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public MeterReplaceVo findMeterReplace(Long id) {
        return meterReplaceLogMapper.findMeterReplace(id);
    }

    @Override
    public Pagination<MeterReplaceVo> pageMeterReplace(MeterReplacePageDto pageDto) {
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        List<MeterReplaceVo> list = listMeterReplace(pageDto);
        if (CollectionUtils.isEmpty(list)){
            return new Pagination<>();
        }
        return new Pagination<>(list);
    }

    @Override
    public List<MeterReplaceVo> listMeterReplace(MeterReplacePageDto pageDto) {
        List<MeterReplaceVo> list =  meterReplaceLogMapper.listMeterReplace(pageDto, UserUtil.getCurrentUser().getUserCondition());
        if (CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        for (MeterReplaceVo meterReplaceVo : list) {
            meterReplaceVo.setReplaceMethod(ReplaceMethodEnum.getMessage(Integer.parseInt(meterReplaceVo.getReplaceMethod())));
        }
        return list;
    }

    @Override
    public void submitWaterMeterReplace(WaterMeterReplaceInputDto waterMeterReplaceDto) {
        log.info("begin submitWaterMeterReplace waterMeterReplaceInputDto:{}", JSON.toJSON(waterMeterReplaceDto));
        Boolean remoteMeterFlag = false;
        Device device = deviceMapper.findById(waterMeterReplaceDto.getDeviceId());
        // 判断设备编号和电子号是否已经存在
        if (ZoniotStringUtils.isNotEmpty(waterMeterReplaceDto.getNewDeviceNo())) {
            int resultDeviceNo = deviceMapper.findByDeviceNoUnique(waterMeterReplaceDto.getDeviceId(), waterMeterReplaceDto.getNewDeviceNo());
            if (resultDeviceNo > 0) {
                throw BusinessException.builder(RmcpErrorEnum.RMCP_DEVICE_NO_NOT_EXISTED);
            }
        }
        if (ZoniotStringUtils.isNotEmpty(waterMeterReplaceDto.getNewMeterNo())) {
            int resultWaterMeterNo = deviceMapper.findByMeterNoUnique(waterMeterReplaceDto.getDeviceId(), waterMeterReplaceDto.getNewMeterNo());
            if (resultWaterMeterNo > 0) {
                throw BusinessException.builder(RmcpErrorEnum.RMCP_DEVICE_ELECTRONIC_NO_NOT_EXISTED);
            }
        }
        // 1. 添加换表记录
        insertSelective(waterMeterReplaceDto, device);
        // 2、更改设备信息
        updateDevice(waterMeterReplaceDto, device);

        // TODO  waterRelatedDeviceMapper.realDelByDeviceId(waterMeterReplaceInputDto.getDeviceId());
        /*if (remoteMeterFlag) {
            //先删除再插入
            waterRelatedDeviceMapper.realDelByDeviceId(waterMeterReplaceInputDto.getDeviceId());
            WaterRelatedDevice waterRelatedDevice = new WaterRelatedDevice();
            waterRelatedDevice.setDeviceId(waterMeterReplaceInputDto.getDeviceId());
            waterRelatedDevice.setConcentratorId(waterMeterReplaceInputDto.getConcentratorId());
            waterRelatedDevice.setCollectorId(waterMeterReplaceInputDto.getCollectorId());
            waterRelatedDevice.setChannelNumberId(waterMeterReplaceInputDto.getChannelNumberId());
            waterRelatedDevice.setPort(waterMeterReplaceInputDto.getPort());
            waterRelatedDevice.setIssueStatus(0);
            waterRelatedDevice.setStatus(1);
            //waterRelatedDevice.setRemark();
            waterRelatedDevice.setDateCreate(LocalDateTime.now());
            waterRelatedDevice.setDateUpdate(LocalDateTime.now());
            waterRelatedDevice.setUpdateBy(username);
            waterRelatedDevice.setCreateBy(username);
            waterRelatedDeviceMapper.insertSelective(waterRelatedDevice);
        }else {
            //删除
            waterRelatedDeviceMapper.realDelByDeviceId(waterMeterReplaceInputDto.getDeviceId());
        }*/

        /*// 3、推送换表信息
        WaterMeterReplaceData waterMeterReplaceData = new WaterMeterReplaceData();
        waterMeterReplaceData.setActive(active);
        waterMeterReplaceData.setDeviceId(waterMeterReplaceLog.getDeviceId());
        waterMeterReplaceData.setCustomerId(device.getCustomerId());
        waterMeterReplaceData.setCustomerCode("");
        waterMeterReplaceData.setNewWaterNo(waterMeterReplaceLog.getNewWaterNo());
        waterMeterReplaceData.setOldWaterNo(waterMeterReplaceLog.getOldWaterNo());
        waterMeterReplaceData.setNewBeginWsv(waterMeterReplaceLog.getNewBeginWsv());
        waterMeterReplaceData.setOldEndWsv(waterMeterReplaceLog.getOldEndWsv());
        waterMeterReplaceData.setNewDeviceNo(waterMeterReplaceLog.getNewDeviceNo());
        waterMeterReplaceData.setOldDeviceNo(waterMeterReplaceLog.getOldDeviceNo());
        waterMeterReplaceData.setDateCreate(new Date());

        String json = JacksonUtil.obj2String(waterMeterReplaceData);
        log.info("waterMeterReplaceData:" + json);
        kafkaTemplate.send(acceptMeterReplaceTopic,json);*/
        log.info("end submitWaterMeterReplace remoteMeterFlag = {}", remoteMeterFlag);
    }

    @Override
    public void delete(Long id) {
        meterReplaceLogMapper.updateStatus(Arrays.asList(id), StatusEnum.DELETE.getCode());
    }

    @Override
    public void deleteAll(List<Long> ids) {
        meterReplaceLogMapper.updateStatus(ids, StatusEnum.DELETE.getCode());
    }

    /**
    * @author Andy
    * @description 添加换表记录
    * @date 9:36 2021/7/21
    * @param waterMeterReplaceDto：换标记录, device, deviceTypeId]
    * @return void
    **/
    private void insertSelective(WaterMeterReplaceInputDto waterMeterReplaceDto, Device device){
        Integer deviceTypeId = waterMeterReplaceDto.getNewDeviceTypeId() != null ? waterMeterReplaceDto.getNewDeviceTypeId() : device.getProductId();
        LoginUser loginUser = UserUtil.getCurrentUser();
        String username  = loginUser.getUsername();
        String userPhone = loginUser.getPhoneNumber();
        MeterReplaceLog waterMeterReplaceLog = new MeterReplaceLog();
        waterMeterReplaceLog.setDeviceId(waterMeterReplaceDto.getDeviceId());
        waterMeterReplaceLog.setReplaceMethod(waterMeterReplaceDto.getReplaceMethod());
        waterMeterReplaceLog.setNewProductId(deviceTypeId);
        waterMeterReplaceLog.setOldProductId(device.getProductId());
        waterMeterReplaceLog.setNewMeterNo(waterMeterReplaceDto.getNewMeterNo());
        waterMeterReplaceLog.setOldMeterNo(device.getMeterNo());
        waterMeterReplaceLog.setNewBeginDegree(waterMeterReplaceDto.getNewBeginDegree());
        waterMeterReplaceLog.setOldEndDegree(waterMeterReplaceDto.getOldEndDegree());
        waterMeterReplaceLog.setNewDeviceNo(waterMeterReplaceDto.getNewDeviceNo());
        waterMeterReplaceLog.setOldDeviceNo(device.getDeviceNo());
        waterMeterReplaceLog.setReplaceUsername(username);
        waterMeterReplaceLog.setReplaceUserPhone(userPhone);
        waterMeterReplaceLog.setStatus(StatusEnum.OK.getCode());
        waterMeterReplaceLog.setCreateBy(username);
        waterMeterReplaceLog.setCreateDate(LocalDateTime.now());
        waterMeterReplaceLog.setUpdateBy(username);
        waterMeterReplaceLog.setUpdateDate(LocalDateTime.now());
        meterReplaceLogMapper.insertSelective(waterMeterReplaceLog);
    }

    /**
    * @author Andy
    * @description 更新设备信息
    * @date 9:39 2021/7/21
    * @param waterMeterReplaceDto：换表信息, device：设备信息]
    * @return void
    **/
    private void updateDevice(WaterMeterReplaceInputDto waterMeterReplaceDto, Device device){
        Device newDevice = new Device();
        newDevice.setId(device.getId());
        if (ZoniotStringUtils.isNotEmpty(waterMeterReplaceDto.getNewDeviceNo())) {
            newDevice.setDeviceNo(waterMeterReplaceDto.getNewDeviceNo());
        }
        if (ZoniotStringUtils.isNotEmpty(waterMeterReplaceDto.getNewMeterNo())) {
            newDevice.setMeterNo(waterMeterReplaceDto.getNewMeterNo());
        }
        if (ZoniotIntegerUtils.isNotEmpty(waterMeterReplaceDto.getNewDeviceTypeId())) {
            Product product = productMapper.findById(waterMeterReplaceDto.getNewDeviceTypeId());
            if (product != null) {
                newDevice.setCategoryId(product.getProductCategoryId());
            }
        }
        newDevice.setSealNo(waterMeterReplaceDto.getSealNo());
        newDevice.setUpdateDate(LocalDateTime.now());
        newDevice.setUpdateBy(UserUtil.getUsername());
        deviceMapper.updateByPrimaryKeySelective(newDevice);
    }
}
