package com.sptg.iot.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
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.util.JsonUtils;
import com.sptg.iot.api.beans.ApiResultBean;
import com.sptg.iot.api.beans.IotReturnCode;
import com.sptg.iot.api.beans.PageData;
import com.sptg.iot.api.dto.IotAlarmWorkOrderDto;
import com.sptg.iot.api.entity.IotAlarm;
import com.sptg.iot.api.entity.IotAuthentication;
import com.sptg.iot.api.entity.IotAlarmWorkOrder;
import com.sptg.iot.api.entity.IotSysConf;
import com.sptg.iot.api.util.IotHttpUtil;
import com.sptg.iot.biz.mapper.IotAlarmWorkOrderMapper;
import com.sptg.iot.biz.service.IotApiLogServiceInterface;
import com.sptg.iot.biz.service.IotAuthServiceInterface;
import com.sptg.iot.biz.service.IotAlarmWorkOrderServiceInterface;
import com.sptg.iot.biz.service.IotSysConfServiceInterface;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author zwx
 * @create 2020/10/19 23:24
 * 告警工单 服务层实现层
 */
@Service
@RequiredArgsConstructor
public class IotAlarmWorkOrderServiceImpl extends ServiceImpl<IotAlarmWorkOrderMapper, IotAlarmWorkOrder> implements IotAlarmWorkOrderServiceInterface {

    private final IotSysConfServiceInterface iotSysConfServiceInterface;
    private final IotApiLogServiceInterface apiLogServiceInterface;
    private final IotAuthServiceInterface iotAuthServiceInterface;

    @Override
    public ResultBean<Page<IotAlarmWorkOrder>> showIotDeviceWorkOrderList(IotAlarmWorkOrderDto iotAlarmWorkOrderDto) {
        Page<IotAlarmWorkOrder> page = iotAlarmWorkOrderDto.getPage();
        Wrapper<IotAlarmWorkOrder> wrapper = new EntityWrapper<>();
        page.setRecords(this.baseMapper.getList(wrapper));
        return new ResultBean<>(ResultEnum.SUCCESS, page);
    }

    @Override
    public ResultBean<String> syncIotDeviceWorkOrderList(IotAlarmWorkOrderDto iotAlarmWorkOrderDto) {
        List<IotSysConf> iotSysConfList = this.iotSysConfServiceInterface.selectList(null);
        List<IotAlarmWorkOrder> allIotDeviceWorkOrderList = new ArrayList<>();
        for(int i = 0; i < iotSysConfList.size(); i++){
            IotSysConf iotSysConf = iotSysConfList.get(i);
            String appId = iotSysConf.getAppId();
            IotAuthentication iotAuthentication = this.iotAuthServiceInterface.findByAppId(appId);
            if(iotAuthentication != null){
                IotHttpUtil httpUtil = new IotHttpUtil(iotSysConf);
                List<IotAlarmWorkOrder> iotDeviceWorkOrderList = new ArrayList<>();
                Map<String, Object> bizParamsMap = BeanUtil.beanToMap(iotAlarmWorkOrderDto);
                String[] prefixList = iotSysConf.getPrefix().split(",");
                for(int j = 0; j < prefixList.length; j++){
                    String prefix = prefixList[j];
                    String accessToken = iotAuthentication.getAccessToken();
                    ApiResultBean<PageData<IotAlarmWorkOrder>> apiResultBean = httpUtil.syncAlarmWorkOrderList(bizParamsMap, prefix, accessToken);
                    if(apiResultBean.getCode().equals(IotReturnCode.UNAUTHORIZED.getCode())){ //未认证，提示先去认证
                        return new ResultBean<>(ResultEnum.FAILURE, IotReturnCode.UNAUTHORIZED.toString());
                    }
                    if(apiResultBean.getCode().equals(OperationConstant.ZERO)){
                        PageData<IotAlarmWorkOrder> pageData = apiResultBean.getData();
                        List<IotAlarmWorkOrder> items = pageData.getItems();
                        items.forEach(iotAlarmWorkOrder -> {
                            iotAlarmWorkOrder.setLastSyncDate(new Date());
                            iotAlarmWorkOrder.setAppId(appId);
                            iotAlarmWorkOrder.setPrefix(prefix);
                        });
                        iotDeviceWorkOrderList.addAll(pageData.getItems());
                        String reqData = JsonUtils.objectToJson(bizParamsMap);
                        this.apiLogServiceInterface.recordIotApiLog("/order/list", prefix, appId, reqData, apiResultBean);
                    }
                }
                allIotDeviceWorkOrderList.addAll(iotDeviceWorkOrderList); //将改应用ID下的所有设备记录下来
            }
        }
        List<IotAlarmWorkOrder> updateIotDeviceWorkOrderList = new ArrayList<>();
        if(allIotDeviceWorkOrderList.size() > 0){
            allIotDeviceWorkOrderList.forEach(source ->{
                IotAlarmWorkOrder target = this.getIotDeviceWorkOrderByOrderId(source.getOrder_id());
                if(target == null){
                    target = new IotAlarmWorkOrder();
                }else{
                    source.setId(target.getId());
                }
                BeanUtil.copyProperties(source, target);
                updateIotDeviceWorkOrderList.add(target);
            });
        }
        if(updateIotDeviceWorkOrderList.size() > 0){
            boolean result = this.insertOrUpdateBatch(updateIotDeviceWorkOrderList);
            if(result){
                return new ResultBean<>(ResultEnum.SUCCESS, "同步告警工单成功");
            }else{
                return new ResultBean<>(ResultEnum.FAILURE, "同步告警工单成功，但保存失败");
            }
        }else{
            return new ResultBean<>(ResultEnum.SUCCESS, "同步告警工单成功，但无数据需要更新");
        }
    }

    @Override
    public IotAlarmWorkOrder getIotDeviceWorkOrderByOrderId(String orderId) {
        Wrapper<IotAlarmWorkOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("s_order_id", orderId);
        return this.selectOne(wrapper);
    }

    @Override
    public ResultBean<String> updateIotDeviceWorkOrder(IotAlarmWorkOrderDto iotAlarmWorkOrderDto) {
        String appId = iotAlarmWorkOrderDto.getAppId();
        String orderId = iotAlarmWorkOrderDto.getOrder_id();
        Integer status = iotAlarmWorkOrderDto.getStatus();
        IotSysConf sysConf = this.iotSysConfServiceInterface.findSysConfByAppId(appId);
        IotAuthentication iotAuthentication = this.iotAuthServiceInterface.findByAppId(appId);
        String accessToken = iotAuthentication.getAccessToken();
        IotHttpUtil httpUtil = new IotHttpUtil(sysConf);
        Map<String, Object> bizParamsMap = new HashMap<>();
        bizParamsMap.put("order_id", orderId);
        bizParamsMap.put("status", status);
        List<String> prefixList = iotAlarmWorkOrderDto.getPrefixList();
        ApiResultBean apiResultBean = httpUtil.updateAlarmWorkOrder(bizParamsMap, prefixList.get(0), accessToken);
        if(apiResultBean.getCode().equals(OperationConstant.ZERO)){
            return new ResultBean<>(ResultEnum.SUCCESS, "工单更新成功");
        }else{
            return new ResultBean<>(ResultEnum.FAILURE, "工单更新失败");
        }
    }

    @Override
    public ResultBean<Page<IotAlarmWorkOrder>> pagingQuery(IotAlarmWorkOrderDto iotAlarmWorkOrderDto) {
        Page<IotAlarmWorkOrder> page = iotAlarmWorkOrderDto.getPage();
        Wrapper<IotAlarmWorkOrder> wrapper = new EntityWrapper<>();
        String order_id = iotAlarmWorkOrderDto.getOrder_id();
        String device_id = iotAlarmWorkOrderDto.getDevice_id();
        String alarm_id = iotAlarmWorkOrderDto.getAlarm_id();
        Integer status = iotAlarmWorkOrderDto.getStatus();
        String order_name = iotAlarmWorkOrderDto.getOrder_name();
        if(StringUtils.hasText(device_id)){
            wrapper.eq("s_device_id", device_id);
        }
        if(StringUtils.hasText(order_id)){
            wrapper.eq("s_order_id", order_id);
        }
        if(StringUtils.hasText(alarm_id)){
            wrapper.eq("s_alarm_id", alarm_id);
        }
        if(status != null){
            wrapper.eq("i_status", status);
        }
        if(StringUtils.hasText(order_name)){
            wrapper.like("s_order_name", order_name);
        }
        page.setRecords(this.baseMapper.pagingQuery(wrapper, iotAlarmWorkOrderDto.getPage()));
        return new ResultBean<>(ResultEnum.SUCCESS,page);
    }

    @Override
    public IotAlarmWorkOrder getIotAlarmWorkOrderById(Long id) {
        Wrapper<IotAlarmWorkOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("l_id", id);
        IotAlarmWorkOrder iotAlarmWorkOrder = this.baseMapper.getOne(wrapper);
        return iotAlarmWorkOrder;
    }
}
