package com.chinaitop.depot.intelligent.basicdata.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.chinaitop.depot.intelligent.basicdata.mapper.TNNtinfoHistoryMapper;
import com.chinaitop.depot.intelligent.basicdata.mapper.TNtinfoMapper;
import com.chinaitop.depot.intelligent.basicdata.model.*;
import com.chinaitop.depot.intelligent.basicdata.service.GasService;
import com.chinaitop.depot.intelligent.basicdata.service.WareHouseBasicInfoService;
import com.chinaitop.depot.intelligent.utils.DateUtils;
import com.chinaitop.depot.intelligent.utils.JsonToObjectUtils;
import com.chinaitop.depot.intelligent.utils.UuidUtils;
import com.unissoft.model.BasicEntity;
import com.unissoft.model.SendEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class GasServiceImpl implements GasService {
    @Resource
    private TNtinfoMapper tNtinfoMapper;

    @Resource
    private TNNtinfoHistoryMapper tNNtinfoHistoryMapper;
    @Resource
    private GasService gasService;
    @Resource
    private WareHouseBasicInfoService wareHouseBasicInfoService;
    @Resource
    private UuidUtils uUidUtils;

    @Override
    public List<TNtinfo> getList(String cfCode) {
        TNtinfoExample example = new TNtinfoExample();
        TNtinfoExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(cfCode)) {
            criteria.andVcfcodeEqualTo(cfCode);
        }
        criteria.andDelFlagEqualTo(1);//未删除
        return tNtinfoMapper.selectByExample(example);
    }

    @Override
    public TNtinfo getById(String id) {
        return tNtinfoMapper.selectByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(String grainJson) {
    	if (StringUtils.isNotBlank(grainJson)) {
            TNtinfo tNtinfo = (TNtinfo) JsonToObjectUtils.jsonToObject(grainJson,TNtinfo.class);
            tNtinfo.setUpdatetime(DateUtils.getDate());
            // 推送基础数据
            JSONObject jsonObject = SendEntity.synchronizationConvert(grainJson);
            jsonObject.put("updatetime",DateUtils.dateToString(tNtinfo.getUpdatetime()));
            if (StringUtils.isNotBlank(tNtinfo.getId())) {
            	tNtinfoMapper.updateByPrimaryKey(tNtinfo);
                // 推送数据并返回结果
                SendEntity.cxfFactor().saveMapData(SendEntity.sendAndConvert(jsonObject, "U"));
            } else {
                // 获取Max+1值
                Map<String, Object> valueMax = wareHouseBasicInfoService.getCode("t_ntinfo", "sitecode", "vdevcode", null);
                // 替换值
                jsonObject.put("vdevcode",valueMax.get("column2"));
                tNtinfo.setId(uUidUtils.getCodeId(tNtinfo.getOrgId(), "t_ntinfo"));
                tNtinfo.setVdevcode(valueMax.get("column2").toString());
                tNtinfo.setDelFlag(1); //未删除
                tNtinfoMapper.insert(tNtinfo);
                // 推送数据并返回结果
                SendEntity.cxfFactor().saveMapData(SendEntity.sendAndConvert(jsonObject, "I"));
            }
        }
    	
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteById(String id,String basicGasSetJson) {
    	TNtinfo tNtinfo = (TNtinfo) JsonToObjectUtils.jsonToObject(basicGasSetJson,TNtinfo.class);
    	tNtinfo.setDelFlag(0); //删除
    	int i = tNtinfoMapper.updateByPrimaryKeySelective(tNtinfo);
        if (i > 0) {
            // 推送同步数据
            JSONObject jsonObject = SendEntity.synchronizationConvert(basicGasSetJson);
            SendEntity.cxfFactor().saveMapData(SendEntity.sendAndConvert(jsonObject, "D"));
        }
        return i;
    	
    }

    @Override
    public boolean getBycfCode(String vdevcode, String vdevname) {
        TNtinfoExample example = new TNtinfoExample();
        TNtinfoExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(vdevcode)) {
            criteria.andVdevcodeEqualTo(vdevcode);
        }
        if (StringUtils.isNotEmpty(vdevname)) {
            criteria.andVdevnameEqualTo(vdevname);
        }
        List<TNtinfo> tNtinfos = tNtinfoMapper.selectByExample(example);
        if (tNtinfos.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 保存作业记录
     * @param type
     * @param ktinfoJson
     * @param uperson
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveHistoryData(String type, String ktinfoJson, String uperson, Integer energy) {
        TKtinfo tKtinfo = (TKtinfo) JsonToObjectUtils.jsonToObject(ktinfoJson, TKtinfo.class);
        TNNtinfoHistory tnNtinfoHistory = new TNNtinfoHistory();

        BigDecimal b = new BigDecimal(energy);
        if ("open".equals(type)) {
            tnNtinfoHistory.setId(UuidUtils.getCode()); // id
            tnNtinfoHistory.setVcfcode(tKtinfo.getVcfcode()); // 仓房code
            tnNtinfoHistory.setVdevcode(tKtinfo.getVdevcode()); // 设备code
            tnNtinfoHistory.setVdevname(tKtinfo.getVdevname()); // 设备名称
            tnNtinfoHistory.setUperson(uperson); // 操作人
            tnNtinfoHistory.setRemark(tKtinfo.getRemark()); // 具体详细信息
            tnNtinfoHistory.setOrgId(tKtinfo.getOrgId()); // 组织机构代码
            tnNtinfoHistory.setStarttime(new Date()); // 开始时间
            tnNtinfoHistory.setEnergy(b); //区分是氮气气调还是氮气房
            tNNtinfoHistoryMapper.insertSelective(tnNtinfoHistory); // 新增作业记录
            gasService.save(ktinfoJson); // 更新操作状态
        } else if ("close".equals(type)){
            TNNtinfoHistoryExample example = new TNNtinfoHistoryExample();
            TNNtinfoHistoryExample.Criteria criteria = example.createCriteria();
            criteria.andOrgIdEqualTo(tKtinfo.getOrgId());
            criteria.andVcfcodeEqualTo(tKtinfo.getVcfcode());
            criteria.andVdevcodeEqualTo(tKtinfo.getVdevcode());
            criteria.andVdevnameEqualTo(tKtinfo.getVdevname());
            criteria.andEndtimeIsNull();
            tnNtinfoHistory.setEnergy(b); //区分氮气气调还是氮气房
            tnNtinfoHistory.setEndtime(new Date()); // 结束时间
            tNNtinfoHistoryMapper.updateByExampleSelective(tnNtinfoHistory,example); // 更新作业记录
            gasService.save(ktinfoJson); // 更新操作状态
        }
    }

    @Override
    public List<TNNtinfoHistory> getHistoryList(String cfCode, String energy) {
        TNNtinfoHistoryExample example = new TNNtinfoHistoryExample();
        TNNtinfoHistoryExample.Criteria criteria = example.createCriteria();
        BigDecimal b = new BigDecimal(energy);
        if (StringUtils.isNotEmpty(cfCode)) {
            criteria.andVcfcodeEqualTo(cfCode);
        }
        criteria.andEnergyEqualTo(b);
        return tNNtinfoHistoryMapper.selectByExample(example);
    }

    @Transactional
    @Override
    public String synchronizationAll(String orgId) {
        //获取所有基础数据getMapData
        String device = SendEntity.cxfFactor().getMapData();
        //转换对象
        BasicEntity basicEntity = (BasicEntity) JsonToObjectUtils.jsonToObject(device, BasicEntity.class);
        if (basicEntity.getState().equals("0")) {
            List<Object> data = basicEntity.getData();
            if (data.size() > 0) {
                String tt = JSONObject.toJSONString(data);
                ArrayList<Object> objects = JsonToObjectUtils.jsonToObjectsDiverse(tt, TNtinfo.class,"yyyy-MM-dd'T'HH:mm:ss");
                objects.forEach(t -> {
                    TNtinfo tc = (TNtinfo) t;
                    tc.setId(uUidUtils.getCodeId(orgId, "t_ntinfo"));
                    tc.setOrgId(orgId);
                    tc.setDelFlag(1); //未删除sitecode
                    String vdevcode = tc.getSitecode();
                    TNtinfo info1 = getVinfo(vdevcode);
                    if (info1 != null) {
                        tc.setId(info1.getId());
                        tNtinfoMapper.updateByPrimaryKey(tc);
                    } else {
                        tNtinfoMapper.insert(tc);
                    }
                });
            }
        } else {
            return basicEntity.getMsg();
        }
        return basicEntity.getMsg();
    }

    public TNtinfo getVinfo(String vdevcode) {
        TNtinfoExample example = new TNtinfoExample();
        TNtinfoExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(vdevcode)) {
            criteria.andSitecodeEqualTo(vdevcode);
        }
        List<TNtinfo> infos = tNtinfoMapper.selectByExample(example);
        if (infos.size() > 0) {
            return infos.get(0);
        }
        return null;
    }
}
