package net.vtstar.zhongtong.avi.equipment.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import net.vtstar.user.mybatis.provider.Operation;
import net.vtstar.user.mybatis.provider.OrderBy;
import net.vtstar.user.mybatis.provider.WhereFilter;
import net.vtstar.user.search.service.SearchService;
import net.vtstar.utils.CollecUtils;
import net.vtstar.zhongtong.avi.equipment.domain.EquipStatusRealTime;
import net.vtstar.zhongtong.avi.equipment.domain.enums.WorkshopNames;
import net.vtstar.zhongtong.avi.equipment.mapper.EquipStatusRealTimeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author: xiadongwei
 * @Date: 2020/3/11 19:31
 */
@Slf4j
@Service
public class EquipStatusRealTimeService {

    @Autowired
    private EquipStatusRealTimeMapper mapper;
    @Autowired
    private SearchService searchService;

    /**
     * 分页查询设备
     */
    public List<EquipStatusRealTime> findPageEquipRealStatus(JSONObject pageFilter) {
        PageHelper.startPage(pageFilter.getIntValue("pageNum"), pageFilter.getIntValue("pageSize"));
        return mapper.findList(searchService.pageFilter2Filter(pageFilter, new WhereFilter(){{
            addOrderBy("equip_workshop", OrderBy.ASC);
        }}), EquipStatusRealTime.class);
    }

    /**
     * 新增/更新设备状态
     */
    public void saveEquip(String equipWorkshop, String equipCode, String equipName, String equipState) {

        List<EquipStatusRealTime> list = mapper.findList(new WhereFilter() {{
            addFilter("equip_workshop", Operation.EQUAL, equipWorkshop);
            addFilter("equip_code", Operation.EQUAL, equipCode);
            addFilter("equip_name", Operation.EQUAL, equipName);
        }}, EquipStatusRealTime.class);
        if (CollecUtils.isEmpty(list)){
            EquipStatusRealTime realTimeState = new EquipStatusRealTime();
            realTimeState.setEquipWorkshop(WorkshopNames.valueOf(equipWorkshop));
            realTimeState.setEquipCode(equipCode);
            realTimeState.setEquipName(equipName);
            realTimeState.setEquipState(equipState);
            realTimeState.setCreateTime(new Date());
            mapper.insert(realTimeState);
        }else{
            EquipStatusRealTime equipStatusRealTime = list.get(0);
            equipStatusRealTime.setEquipState(equipState);
            equipStatusRealTime.setCreateTime(new Date());
            mapper.update(equipStatusRealTime);
        }
    }

}
