package com.sptg.gateway.controller.device;

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.SysLogConstant;
import com.sptg.common.core.util.WebUtils;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.device.api.constant.DeviceSecurityToken;
import com.sptg.device.api.dto.TimeStrategyDto;
import com.sptg.device.api.entity.TimeStrategy;
import com.sptg.device.api.entity.TimeStrategyConf;
import com.sptg.device.api.feigns.TimeStrategyFeign;
import com.sptg.permissions.api.entity.Account;
import com.sptg.statistics.api.constant.SysLogMenuConstant;
import com.sptg.statistics.api.entity.SysOperationLog;
import com.sptg.statistics.api.feigns.SysOperationLogFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * title: TimeStrategyController
 * package: com.sptg.gateway.controller.device
 * description: 时间策略管理-网关控制器
 *
 *
 *
 */
@RestController
@Slf4j
@RequiredArgsConstructor
public class TimeStrategyController {
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final TimeStrategyFeign timeStrategyFeign;
    private final SysOperationLogFeign sysOperationLogFeign;

    @PostMapping(value = "/device/time/strategy/addEntity")
    @Security(token = DeviceSecurityToken.TIME_STRATEGY_ADD,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> addEntity(TimeStrategyDto dto){
        //获取时间段信息
        try {
            String [] strategyTimeParams=dto.getStrategyTimeParams();
            dto.setTimeStrategyConfList(this.getTimeStrategyConfList(strategyTimeParams));
        } catch (ParseException e) {
            log.error(e.getMessage(),e);
        }
        //登陆用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        //状态
        dto.setStatus(OperationConstant.ZERO);
        dto.setCreateAccountId(onLineUser.getId());
        dto.setCreateDate(new Date());
        ResultBean<Boolean> resultBean=timeStrategyFeign.addEntity(dto);
        if(null!=resultBean.getData()&&resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.DEVICE_TIME_STRATEGY_MANAGE, SysLogConstant.ADD_EVENT,
                    WebUtils.getIp(),dto,onLineUser,dto);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }
    /**
     * 功能描述: 分页查询时间策略列表
     * @param dto
     * @param page
     * @return ResultBean<Page<TimeStrategy>>
     *
     *
     */
    @GetMapping(value = "/device/time/strategy/pagingQuery")
    @Security(token = DeviceSecurityToken.TIME_STRATEGY_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Page<TimeStrategy>> pagingQuery(TimeStrategyDto dto,Page<TimeStrategy> page){
        dto.setPage(page);
        return timeStrategyFeign.pagingQuery(dto);
    }
    /**
     * 功能描述:根据id获取时间策略信息
     * @param id
     * @return ResultBean<TimeStrategy>
     *
     *
     */
    @GetMapping(value = "/device/time/strategy/get/{id}")
    @Security(token = DeviceSecurityToken.TIME_STRATEGY_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<TimeStrategy> getEntityById(@PathVariable(value = "id") Long id){
        TimeStrategyDto dto=new TimeStrategyDto();
        dto.setId(id);
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        return timeStrategyFeign.getEntityById(dto);
    }
    /**
     * 功能描述:修改时间策略信息
     * @param dto
     * @return com.sptg.common.core.beans.ResultBean<java.lang.Boolean>
     *
     *
     */
    @PostMapping(value = "/device/time/strategy/edit")
    @Security(token = DeviceSecurityToken.TIME_STRATEGY_UPDATE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> editEntity(TimeStrategyDto dto){
        //获取时间段信息
        try {
            String [] strategyTimeParams=dto.getStrategyTimeParams();
            dto.setTimeStrategyConfList(this.getTimeStrategyConfList(strategyTimeParams));
        } catch (ParseException e) {
            log.error(e.getMessage(),e);
        }
        //登陆用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        TimeStrategy oldObj = this.timeStrategyFeign.getEntityById(dto).getData();
        ResultBean<Boolean> resultBean=timeStrategyFeign.editEntity(dto);
        if(null!=resultBean.getData()&&resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            TimeStrategy newObj = this.timeStrategyFeign.getEntityById(dto).getData();
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.DEVICE_TIME_STRATEGY_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),dto,onLineUser,oldObj,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }
    /**
     * 功能描述:根据id删除时间策略
     * @param id
     * @return ResultBean<Boolean>
     *
     *
     */
    @GetMapping(value = "/device/time/strategy/delete/{id}")
    @Security(token = DeviceSecurityToken.TIME_STRATEGY_DELETE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> deleteEntity(@PathVariable(value = "id") Long id){
        TimeStrategyDto dto=new TimeStrategyDto();
        dto.setId(id);
        TimeStrategy oldObj = this.timeStrategyFeign.selectById(id);
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        ResultBean<Boolean> resultBean=timeStrategyFeign.deleteEntity(dto);
        if(null!=resultBean.getData()&&resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.DEVICE_TIME_STRATEGY_MANAGE, SysLogConstant.DELETE_EVENT,
                    WebUtils.getIp(),dto,onLineUser,oldObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }
    /**
     * 功能描述:根据名称查询时间策略列表
     * @param name 策略名称
     * @return ResultBean<TimeStrategy>
     *
     *
     */
    @GetMapping(value = "/device/time/strategy/getByName")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<TimeStrategy> getEntityByName(String name){
        if (StringUtils.isEmpty(name)){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        TimeStrategyDto dto = new TimeStrategyDto();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        dto.setName(name);
        List<TimeStrategy> entityList = this.timeStrategyFeign.getEntityList(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,entityList);
    }

    /*-------------------------------------------------------内部方法-------------------------------------------------------------*/
    /*----------------------------------------------------------------------------------------------------------------------------*/

    /**
     * 功能描述:获取时间段的参数信息
     * @param strategyTimeParams 时间段的参数信息字符串数组
     * @return List<TimeStrategyConf>
     *
     *
     */
    private List<TimeStrategyConf> getTimeStrategyConfList(String [] strategyTimeParams) throws ParseException{
        List<TimeStrategyConf> timeStrategyConfList=null;
        if(strategyTimeParams!=null){
            timeStrategyConfList=new ArrayList<TimeStrategyConf>();
            for(String strategyTimeParam:strategyTimeParams){
                TimeStrategyConf timeStrategyConf=new TimeStrategyConf();
                String [] strategyTimeParamArray=strategyTimeParam.split(";");
                //获取时间范围
                String strategyTime=strategyTimeParamArray[0];
                if(StringUtils.isNotBlank(strategyTime)){
                    String [] strategyTimeArray=strategyTime.split(" - ");
                    SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
                    String beginTimeStr=strategyTimeArray[0];
                    String endTimeStr=strategyTimeArray[1];
                    Date beginTime=sdf.parse(beginTimeStr);
                    timeStrategyConf.setBeginTime(beginTime);
                    Date endTime=sdf.parse(endTimeStr);
                    timeStrategyConf.setEndTime(endTime);
                }
                //音量大小
                String soundVolume=strategyTimeParamArray[1];
                if(StringUtils.isNotBlank(soundVolume)){
                    timeStrategyConf.setSoundVolume(Integer.valueOf(soundVolume));
                }
                //屏幕亮度
                String screenLuminance=strategyTimeParamArray[2];
                if(StringUtils.isNotBlank(screenLuminance)){
                    timeStrategyConf.setScreenLuminance(Integer.valueOf(screenLuminance));
                }
                //补光灯亮度
                String fillLightLuminance=strategyTimeParamArray[3];
                if(StringUtils.isNotBlank(fillLightLuminance)){
                    timeStrategyConf.setFillLightLuminance(Integer.valueOf(fillLightLuminance));
                }
                timeStrategyConfList.add(timeStrategyConf);
            }
        }
        return timeStrategyConfList;
    }
}
