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

import com.alibaba.fastjson.JSONObject;
import com.chinaitop.depot.intelligent.common.ConstantClass;
import com.chinaitop.depot.intelligent.fumigation.model.TFumigationPlan;
import com.chinaitop.depot.intelligent.utils.DataUtils;
import com.chinaitop.depot.intelligent.utils.JsonToObjectUtils;
import com.chinaitop.depot.intelligent.utils.SocketUtils;
import com.chinaitop.depot.intelligent.utils.UuidUtils;
import com.chinaitop.depot.intelligent.ventilation.mapper.TCtldevinfoMapper;
import com.chinaitop.depot.intelligent.ventilation.mapper.TJobMapper;
import com.chinaitop.depot.intelligent.ventilation.mapper.TVentilationMapper;
import com.chinaitop.depot.intelligent.ventilation.model.*;
import com.chinaitop.depot.intelligent.ventilation.service.AerationParameterService;
import com.chinaitop.depot.intelligent.ventilation.service.AerationRecordService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;


@Service
public class AerationRecordServiceImpl implements AerationRecordService {

    Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TVentilationMapper tVentilationMapper;
    @Autowired
    private TJobMapper tJobMapper;
    @Autowired
    private TCtldevinfoMapper tCtldevinfoMapper;
    @Autowired
    private AerationParameterService aerationParameterService;

    /*@Autowired
    private ServerSocket serverSocket;*/

    @Override
    public List<TVentilation> getList(String vCfCode, String vDevKindCode, String type) {
        TVentilationExample tVentilationExample = new TVentilationExample();
        tVentilationExample.setDistinct(true);
        TVentilationExample.Criteria criteria = tVentilationExample.createCriteria();
        if (StringUtils.isNotEmpty(vCfCode)) {
            criteria.andVCfCodeEqualTo(vCfCode);
        }
        if (StringUtils.isNotEmpty(vDevKindCode)) {
            criteria.andVDeviceCodeEqualTo(vDevKindCode);
        }
        if (type != null && type.equals("0")) {
            criteria.andVDevNameEqualTo("0");//手动增加的记录
        }
        tVentilationExample.setOrderByClause("v_update_time desc");
        return tVentilationMapper.selectByExample(tVentilationExample);
    }


    //新增
    @Override
    public void save(TCtldevinfo tCtldevinfo, String aerationTaskControl, Integer orgId) {
        // TODO Auto-generated method stub
        TVentilation tVentilation = new TVentilation(); //通风记录
        TJob tJob = new TJob(); //通风作业
        if (StringUtils.isNotBlank(aerationTaskControl) && tCtldevinfo != null) {
            TJobApplication tJobApplication = (TJobApplication) JsonToObjectUtils.jsonToObject(aerationTaskControl, "com.chinaitop.depot.intelligent.ventilation.model.TJobApplication");
            tVentilation.setvCfCode(tJobApplication.getvCfCode()); //仓房编码
            tVentilation.setvPattern(tJobApplication.getVentilationMode()); //通风模式
            tVentilation.setOperationId(tJobApplication.getAreationPlanNumber()); //计划编号
            tVentilation.setOrgId(String.valueOf(orgId)); //orgid
            tVentilation.setvDevName(tCtldevinfo.getVdevname()); //设备名称
            tVentilation.setvDeviceCode(tCtldevinfo.getVdevkindcode());//设备类型
            tVentilation.setvState(Integer.valueOf(tCtldevinfo.getVstatue())); //状态
            tVentilation.setvDistinguishState(0); //通风
            tVentilation.setvUpdateTime(new Date());

            if (tCtldevinfo.getVstatue().equals(ConstantClass.TYPE_NO)) { //vState的状态是手动的状态  vStatue是系统里的  1是打开
                String id = UuidUtils.getCode();
                Date date1 = new Date();
                tVentilation.setvStartTime(date1); //开始时间
                tVentilation.setId(id);

                //通风记录表新增
                tVentilationMapper.insertSelective(tVentilation);
  				/*//修改通风参数值设置
  				tCtldevinfo.setVstatue(tCtldevinfo.getVstatue().toString());
  				tCtldevinfo.setId(tCtldevinfo.getId());
  				tCtldevinfoMapper.updateByPrimaryKeySelective(tCtldevinfo);*/
                //通风作业表修改状态
                tJob.setTaskState(1); //正在进行通风
                tJob.setTaskStartTime(date1);//开始时间
                tJob.setAerationPlanNumber(tJobApplication.getAreationPlanNumber());
                tJobMapper.updateByKey(tJob);
            }

            if (tCtldevinfo.getVstatue().equals(ConstantClass.TYPE_OFF)) { //0是关闭
                Date date = new Date();
                //记录表
                TVentilationExample example = new TVentilationExample();
                TVentilationExample.Criteria criteria = example.createCriteria();
                criteria.andOperationIdEqualTo(tJobApplication.getAreationPlanNumber());
                List<TVentilation> list = tVentilationMapper.selectByExample(example);
                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j).getvEndTime() == null && list.get(j).getvState() == 1 && list.get(j).getvDeviceCode().equals(tCtldevinfo.getVdevkindcode())) {
                        tVentilation.setvEndTime(date); //结束时间
                        tVentilation.setId(list.get(j).getId());
                        tVentilationMapper.updateByPrimaryKeySelective(tVentilation);  //通风记录表
  						
  						/*//修改通风参数值设置
  						tCtldevinfo.setVstatue(tCtldevinfo.getVstatue().toString());
  						tCtldevinfo.setId(tCtldevinfo.getId());
  						tCtldevinfoMapper.updateByPrimaryKeySelective(tCtldevinfo);*/

                        //通风作业表修改状态
                        tJob.setTaskState(2); //结束通风
                        tJob.setTaskEndTime(date);//结束时间
                        tJob.setAerationPlanNumber(tJobApplication.getAreationPlanNumber());
                        tJobMapper.updateByKey(tJob);
                    }
                }
            }

        }
    }

    //新增熏蒸的通风控制
    @Override
    public void saveFumigation(String task, String fumigationDate, Integer orgId) {
        // TODO Auto-generated method stub
        TVentilation tVentilation = new TVentilation();
        if (StringUtils.isNotBlank(fumigationDate) && StringUtils.isNotBlank(task)) {
            TCtldevinfo tCtldevinfo = new TCtldevinfo();
            TJob tJob = new TJob();
            TFumigationPlan tFumigationPlan = (TFumigationPlan) JsonToObjectUtils.jsonToObject(fumigationDate, "com.chinaitop.depot.intelligent.fumigation.model.TFumigationPlan");
            tVentilation.setvCfCode(tFumigationPlan.getHouseId().toString()); //仓房编码
            tVentilation.setvPattern(tFumigationPlan.getId()); //通风模式
            tVentilation.setOrgId(String.valueOf(orgId)); //orgid


            List<String> lists = new ArrayList();
            String[] split = task.split("},");
            String s = "";
            for (int i = 0; i < split.length; i++) {
                if (i != split.length - 1) {
                    s = split[i] + "}";
                    lists.add(s);
                } else {
                    lists.add(split[i]);
                }
            }


            for (int i = 0; i < lists.size(); i++) {
                if (lists.get(i).contains("vdevkindcode") && lists.get(i).contains("vState")) {
                    String str = lists.get(i);
                    JSONObject jsonObject = JSONObject.parseObject(str);
                    // 根据key获取值
                    String vdevkindcode = jsonObject.getString("vdevkindcode");
                    String vState = jsonObject.getString("vState");
                    String vdevname = jsonObject.getString("vdevname");
                    tVentilation.setvDevName(vdevname); //设备名称
                    tVentilation.setvDeviceCode(vdevkindcode);//设备类型
                    tVentilation.setvState(Integer.valueOf(vState)); //状态
                    tVentilation.setvDistinguishState(1); //熏蒸
                    tVentilation.setOperationId(tFumigationPlan.getId()); //计划编号
                    tVentilation.setvUpdateTime(new Date());

                    if (Integer.valueOf(vState) == 1) {
                        String id = UuidUtils.getCode();
                        Date date1 = new Date();
                        tVentilation.setvStartTime(date1); //开始时间
                        tVentilation.setId(id);

                        //通风记录表新增
                        tVentilationMapper.insertSelective(tVentilation);
                        //修改通风参数值设置
                        tCtldevinfo.setVstatue(vState);
                        tCtldevinfo.setId(jsonObject.getString("id"));
                        tCtldevinfoMapper.updateByPrimaryKeySelective(tCtldevinfo);
                    }
                    if (Integer.valueOf(vState) == 0) {
                        Date date = new Date();

                        //记录表
                        TVentilationExample example = new TVentilationExample();
                        TVentilationExample.Criteria criteria = example.createCriteria();

                        criteria.andOperationIdEqualTo(tFumigationPlan.getId());
                        List<TVentilation> list = tVentilationMapper.selectByExample(example);
                        for (int j = 0; j < list.size(); j++) {
                            if (list.get(j).getvEndTime() == null && list.get(j).getvState() == 1) {

                                tVentilation.setvEndTime(date); //结束时间
                                tVentilation.setId(list.get(j).getId());
                                tVentilationMapper.updateByPrimaryKeySelective(tVentilation);

                                //修改熏蒸参数值设置
                                tCtldevinfo.setVstatue(vState);
                                tCtldevinfo.setId(jsonObject.getString("id"));
                                tCtldevinfoMapper.updateByPrimaryKeySelective(tCtldevinfo);
                            }
                        }
                    }
                }
            }
        }
    }

    //根据仓房和设备名称获取信息
    @Override
    public TVentilation getByCode(String vcfcode, String vdevname) {
        // TODO Auto-generated method stub
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("vcfcode", vcfcode);
        modelMap.put("vdevname", vdevname);
        return tVentilationMapper.getByCode(modelMap);
    }


    @Transactional
    @Override
    public void insertBatch(List<TVentilation> ventilations) {
        tVentilationMapper.insertBatch(ventilations);
    }


    @Override
    public List<TVentilation> getByCodeAndTimes(List<String> cDcsCodes, List<Date> cTimes) {
        // TODO Auto-generated method stub
        TVentilationExample example = new TVentilationExample();
        TVentilationExample.Criteria criteria = example.createCriteria();
        if ((cDcsCodes != null && cDcsCodes.size() > 0) && (cTimes != null && cTimes.size() > 0)) {
            criteria.andVCfCodeIn(cDcsCodes);
            criteria.andVUpdateTimeIn(cTimes);
            List<TVentilation> tVentilations = tVentilationMapper.selectByExample(example);
            return tVentilations;
        }
        return null;
    }


    @Override
    public void add(String tVentilationJson, Integer orgId) {
        // TODO Auto-generated method stub
        if (StringUtils.isNotBlank(tVentilationJson)) {
            TVentilation tVentilation = (TVentilation) JsonToObjectUtils.jsonToObject(tVentilationJson, "com.chinaitop.depot.intelligent.ventilation.model.TVentilation");

            if (StringUtils.isNotBlank(tVentilation.getId())) {
                tVentilationMapper.updateByPrimaryKey(tVentilation);
            } else {
                tVentilation.setId(UuidUtils.getCode());
                tVentilation.setvDevName("0");//只是记录 作业前后的温湿度  不是设备通风的记录
                tVentilationMapper.insert(tVentilation);
            }
        }
    }


    @Override
    public int deleteById(String id) {
        // TODO Auto-generated method stub
        int i = tVentilationMapper.deleteByPrimaryKey(id);
        return i;
    }


    @Override
    public TVentilation getById(String id) {
        // TODO Auto-generated method stub
        return tVentilationMapper.selectByPrimaryKey(id);
    }
}
