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.TimeStrategyPushTaskDto;
import com.sptg.device.api.entity.Device;
import com.sptg.device.api.entity.TimeStrategyPushTask;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.device.api.feigns.TimeStrategyPushTaskFeign;
import com.sptg.estate.api.entity.Unit;
import com.sptg.estate.api.feigns.UnitFeign;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Area;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.AreaFeign;
import com.sptg.permissions.api.feigns.OrgFeign;
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 org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * title: TimeStrategyPushTaskController
 * package: com.sptg.gateway.controller.device
 * description:时间策略发布任务
 *
 *
 *
 */
@RestController
@RequiredArgsConstructor
public class TimeStrategyPushTaskController {
    private final TimeStrategyPushTaskFeign timeStrategyPushTaskFeign;
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final AreaFeign areaFeign;
    private final DeviceFeign deviceFeign;
    private final UnitFeign unitFeign;
    private final OrgFeign orgFeign;
    private final SysOperationLogFeign sysOperationLogFeign;


    /**
     * 功能描述: 分页查询时间策略发布列表
     * @param dto 时间策略传输对象
     * @param page  分页信息
     * @return ResultBean<Page<TimeStrategyPushTask>>
     *
     *
     */
    @GetMapping(value = "/device/time/strategy/push/pagingQuery")
    @Security(token = DeviceSecurityToken.TIME_STRATEGY_PUSH_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Page<TimeStrategyPushTask>> pagingQuery(TimeStrategyPushTaskDto dto, Page<TimeStrategyPushTask> page){
        dto.setPage(page);
        ResultBean<Page<TimeStrategyPushTask>> resultBean=timeStrategyPushTaskFeign.pagingQuery(dto);
        page=resultBean.getData();
        //获取发布范围
        if(null!=page&&null!=page.getRecords()){
            page.getRecords().forEach(task->{
                List<Long> fkIdList = this.timeStrategyPushTaskFeign.getFkIdListByTaskId(task.getId());
                List<String> list = null;
                if (fkIdList.size() > OperationConstant.ZERO) {
                    switch (task.getPushType()) {
                        case OperationConstant.ONE:
                            //  按小区发布
                            List<Organization> orgList = this.orgFeign.getListByIds(fkIdList);
                            list = orgList.stream().map(Organization::getName).collect(Collectors.toList());
                            break;
                        case OperationConstant.TWO:
                            //  按单元发布
                            List<Unit> unitList = this.unitFeign.getListByIdList(fkIdList);
                            list = unitList.stream().map(Unit::getName).collect(Collectors.toList());
                            break;
                        case OperationConstant.THREE:
                            //  按设备发布
                            List<Device> deviceList = this.deviceFeign.getListByIds(fkIdList);
                            list = deviceList.stream().map(Device::getName).collect(Collectors.toList());
                            break;
                        default:
                            //  按区域发布
                            List<Area> areaList = this.areaFeign.getListByIds(fkIdList);
                            list = areaList.stream().map(Area::getName).collect(Collectors.toList());
                            break;
                    }
                }
                task.setFkNameList(list);
            });
        }

        return resultBean;
    }

    /**
     * 功能描述:时间策略添加发布
     * @param dto
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/device/time/strategy/push/task/add")
    @Security(token = DeviceSecurityToken.TIME_STRATEGY_PUSH_ADD,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> addEntity(@RequestBody TimeStrategyPushTaskDto dto){
        //  字段校验
        if (null == dto.getTimeStrategyId() ||  null == dto.getFkIdList() ||
                dto.getFkIdList().size() == OperationConstant.ZERO ||
                null == dto.getPushType()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        dto.setCreateAccountId(onLineUser.getId());
        dto.setCreateAccountName(onLineUser.getLoginName());
        dto.setCreateDate(new Date());
        dto.setPushStatus(OperationConstant.ONE);
        ResultBean<Boolean> resultBean=timeStrategyPushTaskFeign.addEntity(dto);
        if(null!=resultBean.getData()&&resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.DEVICE_TIME_STRATEGY_PUSH, SysLogConstant.ADD_EVENT,
                    WebUtils.getIp(),dto,onLineUser,dto);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:发布范围
     * @param taskId 任务id
     * @param pushType 发布类型
     * @return List<String>
     *
     *
     */
    @GetMapping(value = "/device/time/strategy/task/getPushRange/{taskId}/{pushType}")
    @Security(token = DeviceSecurityToken.TIME_STRATEGY_PUSH_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<List<String>>  getPushRange(@PathVariable(value = "taskId") Long taskId,@PathVariable(value = "pushType") Integer pushType){
        List<Long> fkIdList = this.timeStrategyPushTaskFeign.getFkIdListByTaskId(taskId);
        List<String> list = null;
        if (fkIdList.size() > OperationConstant.ZERO) {
            switch (pushType) {
                case OperationConstant.ONE:
                    //  按小区发布
                    List<Organization> orgList = this.orgFeign.getListByIds(fkIdList);
                    list = orgList.stream().map(Organization::getName).collect(Collectors.toList());
                    break;
                case OperationConstant.TWO:
                    //  按单元发布
                    List<Unit> unitList = this.unitFeign.getListByIdList(fkIdList);
                    list = unitList.stream().map(Unit::getName).collect(Collectors.toList());
                    break;
                case OperationConstant.THREE:
                    //  按设备发布
                    List<Device> deviceList = this.deviceFeign.getListByIds(fkIdList);
                    list = deviceList.stream().map(Device::getName).collect(Collectors.toList());
                    break;
                default:
                    //  按区域发布
                    List<Area> areaList = this.areaFeign.getListByIds(fkIdList);
                    list = areaList.stream().map(Area::getName).collect(Collectors.toList());
                    break;
            }
        }
        return new ResultBean(ResultEnum.SUCCESS,list);
    }

    /**
     * 功能描述:撤回发布
     * @param taskId
     * @return ResultBean<Boolean>
     *
     *
     */
    @GetMapping(value = "/device/time/strategy/push/task/rollback/{taskId}")
    @Security(token = DeviceSecurityToken.TIME_STRATEGY_PUSH_ROLLBACK,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> rollback(@PathVariable(value = "taskId") Long taskId){
        //登录用户
        TimeStrategyPushTaskDto dto=new TimeStrategyPushTaskDto();
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        dto.setId(taskId);
        TimeStrategyPushTask oldObj = this.timeStrategyPushTaskFeign.getEntityById(dto);
        ResultBean<Boolean> resultBean=timeStrategyPushTaskFeign.rollback(dto);
        if(null!=resultBean.getData()&&resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.DEVICE_TIME_STRATEGY_PUSH, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),"撤回发布",dto,onLineUser,oldObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }
}
