package com.mvc.service.app;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.BaseConstant;
import com.mvc.dao.TAppComlogMapper;
import com.mvc.entity.TAppComlog;
import com.mvc.entity.TAppComlogExample;
import com.mvc.model.AppUserModel;
import com.mvc.model.StationAccModel;
import com.mvc.model.TAppComlogModel;
import com.mvc.service.PackLogMana;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service
@Transactional
public class TAppComlogService {

    @Autowired(required = false)
    private TAppComlogMapper tAppComlogMapper;

    @Autowired
    private StationAccService stationAccService;

    @Autowired
    private AppUserService appUserService;

    public Map<String, Object> findAllTAppComlog(TAppComlogModel queryModel) {
        Map<String, Object> resMap = new HashMap<>();
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPage(), queryModel.getRows());

        TAppComlogExample example = new TAppComlogExample();
        TAppComlogExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getDeviceSn())) {
            if (queryModel.getDeviceSn().length() == BaseConstant.LENGTH_DEVICE_SN) {
                criteria.andDeviceSnEqualTo(queryModel.getDeviceSn());
            } else {
                criteria.andDeviceSnLike(StringUtil.getLikeFormat(queryModel.getDeviceSn()));
            }
        }

        if (StringUtils.isNotEmpty(queryModel.getStationCode())) {
            if (queryModel.getStationCode().length() == BaseConstant.LENGTH_STATION_CODE) {
                criteria.andStationCodeEqualTo(queryModel.getStationCode());
            } else {
                criteria.andStationCodeLike(StringUtil.getLikeFormat(queryModel.getStationCode()));
            }
        }

        if (StringUtils.isNotEmpty(queryModel.getAppLoginId())) {
            criteria.andAppLoginIdLike("%" + queryModel.getAppLoginId() + "%");
        }

        if (StringUtils.isNotEmpty(queryModel.getLogFrom())) {
            criteria.andLogFromEqualTo(queryModel.getLogFrom());
        }

        if (StringUtils.isNotEmpty(queryModel.getStartTime())) {
            Date date = DateUtil.parseTimeStr(queryModel.getStartTime(), "yyyy-MM-dd HH:mm:ss");
            criteria.andCreateTimeGreaterThanOrEqualTo(date);
        }

        if (StringUtils.isNotEmpty(queryModel.getEndTime())) {
            Date date = DateUtil.parseTimeStr(queryModel.getEndTime(), "yyyy-MM-dd HH:mm:ss");
            criteria.andCreateTimeLessThanOrEqualTo(date);
        }

        example.setOrderByClause("CREATE_TIME desc");

        List<TAppComlog> TAppComlogs = tAppComlogMapper.selectByExample(example);
        List<TAppComlogModel> resList = new ArrayList<>();
        for (TAppComlog tAppComlog : TAppComlogs) {
            TAppComlogModel model = new TAppComlogModel();
            BeanUtils.copyProperties(tAppComlog, model);

            //查遥测站点名称
            if (StringUtils.isNotEmpty(model.getStationCode())) {
                StationAccModel accModel = stationAccService.findStationAccByStationCode(model.getStationCode());
                if (accModel != null) {
                    model.setStationName(accModel.getStationName());
                }
            }
            //查APP用户姓名
            if (StringUtils.isNotEmpty(model.getAppLoginId())) {
                AppUserModel userModel = appUserService.getModelByLoginid(model.getAppLoginId());
                if (userModel != null) {
                    model.setAppUserName(userModel.getUserName());
                }
            }
            resList.add(model);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    public TAppComlogModel saveTAppComlog(TAppComlogModel model) throws IOException {
        model.setCreateTime(new Date());
        TAppComlog tAppComlog = new TAppComlog();
        BeanUtils.copyProperties(model, tAppComlog);

        //存成文件 2022.10.08 guozhao
        if (StringUtils.isNotEmpty(model.getRawComLog()) && StringUtils.isEmpty(model.getFileName())) {
            String fileName = PackLogMana.saveRunLogByRawMsg(model.getRawComLog(), model.getStationCode());
            tAppComlog.setFileName(fileName);
            tAppComlog.setLogType("0");
            tAppComlog.setRawComLog("");
            tAppComlog.setLogFrom("0");
            if (StringUtils.isNotEmpty(model.getDeviceSn()) && model.getDeviceSn().length() > 11) {
                tAppComlog.setDeviceSn(model.getDeviceSn().substring(0, 11));
            }
        }

        int insert = tAppComlogMapper.insert(tAppComlog);
        model.setId(tAppComlog.getId());
        model.setRawComLog("");
        return model;
    }

    public TAppComlogModel updateTAppComlog(TAppComlogModel model) {
        TAppComlog TAppComlog = tAppComlogMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, TAppComlog);
        int i = tAppComlogMapper.updateByPrimaryKey(TAppComlog);
        return model;
    }

    public int deleteTAppComlog(int id) {
        int i = tAppComlogMapper.deleteByPrimaryKey(id);
        return i;
    }

    /**
     * 根据ID获取记录(包含日志原文)
     *
     * @param id
     * @return
     * @throws IOException
     */
    public TAppComlogModel findTAppComlogById(Integer id) throws IOException {
        TAppComlog tAppComlog = tAppComlogMapper.selectByPrimaryKey(id);
        TAppComlogModel model = null;
        if (tAppComlog != null) {
            model = new TAppComlogModel();
            BeanUtils.copyProperties(tAppComlog, model);
            String content = PackLogMana.getFileContent(model.getFileName(), model.getStationCode(), 0);
            model.setRawComLog(content);
        }
        return model;
    }

    /**
     * 根据设备SN和采样时间获取记录
     * @param deviceSn
     * @param sampleTime
     * @return
     */
    public TAppComlogModel findTAppComlogBySnAndTime(String deviceSn, String sampleTime) {
        TAppComlogModel model = null;
        TAppComlogExample example = new TAppComlogExample();
        TAppComlogExample.Criteria criteria = example.createCriteria();
        criteria.andDeviceSnEqualTo(deviceSn);
        criteria.andSampleTimeEqualTo(DateUtil.parseTimeStr(sampleTime, DateUtil.PATTERN_DATA_UNSIGNED));
        try {
            List<TAppComlog> list = tAppComlogMapper.selectByExample(example);

            if (list != null && list.size() > 0) {
                model = new TAppComlogModel();
                BeanUtils.copyProperties(list.get(0), model);

                String content = PackLogMana.getFileContent(model.getFileName(), model.getStationCode(), 0);
                model.setRawComLog(content);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return model;
    }
}
