package com.zcxk.rmcp.web.service.install.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.common.pojo.ResultMessage;
import com.zcxk.core.common.util.SnowflakeIdWorker;
import com.zcxk.core.mysql.pageing.Pagination;
import com.zcxk.core.oauth2.pojo.LoginUser;
import com.zcxk.core.oauth2.util.UserUtil;
import com.zcxk.rmcp.api.dto.BasePageDto;
import com.zcxk.rmcp.api.dto.install.InstallDeviceDto;
import com.zcxk.rmcp.api.dto.install.InstallInputDto;
import com.zcxk.rmcp.api.enums.DeviceStatusEnum;
import com.zcxk.rmcp.api.enums.RmcpErrorEnum;
import com.zcxk.rmcp.api.enums.ValveStatusEnum;
import com.zcxk.rmcp.core.dao.DeviceMapper;
import com.zcxk.rmcp.core.dao.InstallPlanMapper;
import com.zcxk.rmcp.core.dao.ProductMapper;
import com.zcxk.rmcp.core.entity.Device;
import com.zcxk.rmcp.core.entity.InstallPlan;
import com.zcxk.rmcp.core.entity.Product;
import com.zcxk.rmcp.api.dto.install.InstallQueryDto;
import com.zcxk.rmcp.web.excel.model.ExcelData;
import com.zcxk.rmcp.web.excel.model.InstallMeterData;
import com.zcxk.rmcp.web.service.DeviceService;
import com.zcxk.rmcp.web.service.install.InstallListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.zcxk.rmcp.core.entity.InstallList;
import com.zcxk.rmcp.core.dao.InstallListMapper;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 
 * @author linqingwei
 * @date 2021-07-21 9:44
 */
@Slf4j
@Service
public class InstallListServiceImpl implements InstallListService {

    @Resource
    private InstallListMapper installListMapper;
    @Resource
    private InstallPlanMapper installPlanMapper;
    @Resource
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SnowflakeIdWorker idWorker;
    @Resource
    private ProductMapper productMapper;

    @Override
    public int insertSelective(InstallList record) {
        record.setCreateDate(LocalDateTime.now());
        record.setCreateBy(UserUtil.getUsername());
        record.setUpdateDate(LocalDateTime.now());
        record.setUpdateBy(UserUtil.getUsername());
        return installListMapper.insertSelective(record);
    }

    @Override
    public int updateByPrimaryKeySelective(InstallList record) {
        record.setUpdateDate(LocalDateTime.now());
        record.setUpdateBy(UserUtil.getUsername());
        return installListMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    @Transactional
    public void installSave(InstallInputDto dto) {
        log.info("begin installSave dto : {}", JSON.toJSONString(dto));
        LoginUser loginUser = UserUtil.getCurrentUser();
        if (deviceMapper.findByDeviceNoUnique(dto.getDeviceId(), dto.getDeviceNo()) > 0) {
            throw BusinessException.builder(RmcpErrorEnum.RMCP_DEVICE_NO_UNIQUE_ERROR);
        }
        if (deviceMapper.findByMeterNoUnique(dto.getDeviceId(), dto.getMeterNo()) > 0) {
            throw BusinessException.builder(RmcpErrorEnum.RMCP_METER_NO_UNIQUE_ERROR);
        }
        if (dto.getDeviceId() != null) {
            //更新设备
            Device update = new Device();
            update.setId(dto.getDeviceId());
            update.setDeviceNo(dto.getDeviceNo());
            update.setMeterNo(dto.getMeterNo());
            update.setFileNo(dto.getFileNo());
            update.setSealNo(dto.getSealNo());
            update.setUserName(dto.getUserName());
            update.setUserPhone(dto.getUserPhone());
            update.setIdCard(dto.getIdCard());
            update.setOldEndDegree(dto.getOldEndDegree());
            update.setOldImageUrl(dto.getOldImageUrl());
            update.setInstallDate(LocalDateTime.now());
            update.setIsInstall(1);
            deviceService.updateByPrimaryKeySelective(update);

            //保存安装信息
            InstallList installList = new InstallList();
            installList.setId(dto.getId());
            installList.setIsInstalled(1);
            installList.setDeviceId(dto.getDeviceId());
            this.updateByPrimaryKeySelective(installList);
        }else {
            InstallList install = installListMapper.findById(dto.getId());
            InstallPlan installPlan = installPlanMapper.findById(install.getInstallPlanId());
            Product product = productMapper.findById(installPlan.getProductId());
            Device device = new Device();
            device.setId(idWorker.nextId());
            device.setTenantId(loginUser.getTenantId());
            device.setProductId(installPlan.getProductId());
            device.setCategoryId(product.getProductCategoryId());
            device.setCompanyOrgId(installPlan.getCompanyOrgId());
            device.setDeptOrgId(installPlan.getDeptOrgId());
            device.setCommunityId(installPlan.getCommunityId());
            device.setDeviceNo(dto.getDeviceNo());
            device.setMeterNo(dto.getMeterNo());
            device.setFileNo(dto.getFileNo());
            device.setSealNo(dto.getSealNo());
            device.setUserName(dto.getUserName());
            device.setUserPhone(dto.getUserPhone());
            device.setIdCard(dto.getIdCard());
            device.setOldEndDegree(dto.getOldEndDegree());
            device.setOldImageUrl(dto.getOldImageUrl());
            device.setInstallDate(LocalDateTime.now());
            device.setIsInstall(1);
            device.setDeviceStatus(DeviceStatusEnum.UNUSED.getCode());
            device.setValveStatus(ValveStatusEnum.ON.getCode());
            device.setStatus(StatusEnum.OK.getCode());
            deviceService.insertSelective(device);

            //保存安装信息
            InstallList installList = new InstallList();
            installList.setId(dto.getId());
            installList.setIsInstalled(1);
            installList.setDeviceId(device.getId());
            this.updateByPrimaryKeySelective(installList);
        }
        log.info("end installSave");
    }

    @Override
    @Transactional
    public void installEdit(InstallInputDto dto) {
        log.info("begin installEdit dto : {}", JSON.toJSONString(dto));
        LoginUser loginUser = UserUtil.getCurrentUser();
        if (deviceMapper.findByDeviceNoUnique(dto.getDeviceId(), dto.getDeviceNo()) > 0) {
            throw BusinessException.builder(RmcpErrorEnum.RMCP_DEVICE_NO_UNIQUE_ERROR);
        }
        if (deviceMapper.findByMeterNoUnique(dto.getDeviceId(), dto.getMeterNo()) > 0) {
            throw BusinessException.builder(RmcpErrorEnum.RMCP_METER_NO_UNIQUE_ERROR);
        }
        InstallList install = installListMapper.findById(dto.getId());



        if(!install.getDeviceId().equals(dto.getDeviceId())){
            //更新旧设备关系
            Device oldDevice = new Device();
            oldDevice.setId(install.getDeviceId());
            oldDevice.setIsInstall(0);
            oldDevice.setIsAccept(0);
            deviceService.updateByPrimaryKeySelective(oldDevice);

            //更新设备
            Device update = new Device();
            update.setId(dto.getDeviceId());
            update.setDeviceNo(dto.getDeviceNo());
            update.setMeterNo(dto.getMeterNo());
            update.setFileNo(dto.getFileNo());
            update.setSealNo(dto.getSealNo());
            update.setUserName(dto.getUserName());
            update.setUserPhone(dto.getUserPhone());
            update.setIdCard(dto.getIdCard());
            update.setOldEndDegree(dto.getOldEndDegree());
            update.setOldImageUrl(dto.getOldImageUrl());
            update.setInstallDate(LocalDateTime.now());
            update.setIsInstall(1);
            deviceService.updateByPrimaryKeySelective(update);

            //保存安装信息
            InstallList installList = new InstallList();
            installList.setId(dto.getId());
            installList.setIsInstalled(1);
            installList.setDeviceId(dto.getDeviceId());
            this.updateByPrimaryKeySelective(installList);

        }else {
            //更新设备
            Device update = new Device();
            update.setId(dto.getDeviceId());
            update.setDeviceNo(dto.getDeviceNo());
            update.setMeterNo(dto.getMeterNo());
            update.setFileNo(dto.getFileNo());
            update.setSealNo(dto.getSealNo());
            update.setUserName(dto.getUserName());
            update.setUserPhone(dto.getUserPhone());
            update.setIdCard(dto.getIdCard());
            update.setOldEndDegree(dto.getOldEndDegree());
            update.setOldImageUrl(dto.getOldImageUrl());
            deviceService.updateByPrimaryKeySelective(update);
        }

        log.info("end installEdit");
    }

    @Override
    public Pagination<InstallDeviceDto> getInstallPage(InstallQueryDto dto, BasePageDto page) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        List<InstallDeviceDto> list = installListMapper.getInstallList(dto, loginUser.getUserCondition());
        return new Pagination<>(list);
    }

    @Override
    public List<InstallDeviceDto> getUnInstallList(Integer planId, Integer id) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        InstallPlan plan = installPlanMapper.findById(planId);
        List<InstallDeviceDto> list = deviceMapper.getUnInstallDeviceList(loginUser.getTenantId(),plan.getCompanyOrgId(),plan.getDeptOrgId(),plan.getProductId(),id);
        return list;
    }

    @Override
    @Transactional
    public ResultMessage saveExcelData(InstallMeterData data, ExcelData excelData) {
        log.info("install saveExcelData data = {}",JSON.toJSONString(data));
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setStatus(false);
        // 1、校验检查
        if (deviceMapper.findByDeviceNoUnique(null, data.getDeviceNo()) > 0) {
            resultMessage.setMessage(RmcpErrorEnum.RMCP_DEVICE_NO_UNIQUE_ERROR.getMessage());
            return resultMessage;
        }
        if (deviceMapper.findByMeterNoUnique(null, data.getMeterNo()) > 0) {
            resultMessage.setMessage(RmcpErrorEnum.RMCP_METER_NO_UNIQUE_ERROR.getMessage());
            return resultMessage;
        }

        InstallList install = installListMapper.findById(data.getId());
        InstallPlan installPlan = installPlanMapper.findById(install.getInstallPlanId());
        Product product = productMapper.findById(installPlan.getProductId());
        Device device = new Device();
        device.setId(idWorker.nextId());
        device.setTenantId(excelData.getImportFile().getTenantId());
        device.setProductId(installPlan.getProductId());
        device.setCategoryId(product.getProductCategoryId());
        device.setCompanyOrgId(installPlan.getCompanyOrgId());
        device.setDeptOrgId(installPlan.getDeptOrgId());
        device.setCommunityId(installPlan.getCommunityId());
        device.setDeviceNo(data.getDeviceNo());
        device.setMeterNo(data.getMeterNo());
        device.setFileNo(data.getFileNo());
        device.setSealNo(data.getSealNo());
        device.setUserName(data.getUsername());
        device.setUserPhone(data.getPhone());
        device.setIdCard(data.getIdCard());
        device.setInstallDate(LocalDateTime.now());
        device.setIsInstall(1);
        device.setDeviceStatus(DeviceStatusEnum.UNUSED.getCode());
        device.setValveStatus(ValveStatusEnum.ON.getCode());
        device.setStatus(StatusEnum.OK.getCode());
        deviceService.insertSelective(device);

        //保存安装信息
        InstallList installList = new InstallList();
        installList.setId(data.getId());
        installList.setIsInstalled(1);
        installList.setDeviceId(device.getId());
        this.updateByPrimaryKeySelective(installList);
        return null;
    }

    @Override
    @Transactional
    public void batchAccept(List<Integer> ids) {
        log.info("begin InstallListServiceImpl batchAccept ids = {}",JSON.toJSONString(ids));
        installListMapper.accept(ids);
        log.info("end InstallListServiceImpl batchAccept ");
    }

    @Override
    public void allAccept(InstallQueryDto dto) {
        log.info("begin InstallListServiceImpl allAccept dto = {}",JSON.toJSONString(dto));
        List<InstallDeviceDto> list = installListMapper.getInstallList(dto,UserUtil.getCurrentUser().getUserCondition());
        List<Integer> ids = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (InstallDeviceDto installDeviceDto : list) {
                ids.add(installDeviceDto.getId());
            }
            this.batchAccept(ids);
        }
        log.info("end InstallListServiceImpl allAccept ");
    }

    @Override
    @Transactional
    public void batchDelete(List<Integer> ids) {
        log.info("begin InstallListServiceImpl batchDelete ids = {}",JSON.toJSONString(ids));
        installListMapper.delete(ids);
        log.info("end InstallListServiceImpl batchDelete ");
    }

    @Override
    public void allDelete(InstallQueryDto dto) {
        log.info("begin InstallListServiceImpl allDelete dto = {}",JSON.toJSONString(dto));
        LoginUser loginUser = UserUtil.getCurrentUser();
        List<InstallDeviceDto> list = installListMapper.getInstallList(dto, loginUser.getUserCondition());
        List<Integer> ids = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (InstallDeviceDto installDeviceDto : list) {
                ids.add(installDeviceDto.getId());
            }
            this.batchDelete(ids);
        }
        log.info("end InstallListServiceImpl allDelete ");
    }
}
