package com.artfess.device.monitor.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.artfess.base.constants.UrlConstant;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.device.base.manager.DeviceInfoManager;
import com.artfess.device.base.model.DeviceInfo;
import com.artfess.device.base.utils.BizUtils;
import com.artfess.device.base.vo.ActGroupVo;
import com.artfess.device.base.vo.BollardResultVo;
import com.artfess.device.monitor.dao.DeviceDataBarricadeDao;
import com.artfess.device.monitor.manager.DeviceDataBarricadeManager;
import com.artfess.device.monitor.model.DeviceDataBarricade;
import com.artfess.uc.model.User;
import com.artfess.uc.util.ContextUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 实时监控-路障操作数据（DEVICE_DATA_BARRICADE） 服务实现类
 *
 * @author min.wu
 * @company 阿特菲斯信息技术有限公司
 * @since 2022-08-01
 */
@Service
public class DeviceDataBarricadeManagerImpl extends BaseManagerImpl<DeviceDataBarricadeDao, DeviceDataBarricade> implements DeviceDataBarricadeManager {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DeviceInfoManager deviceInfoManager;

    @Override
    public String batchAct(List<ActGroupVo> list) {

        Assert.notEmpty(list, "参数不能为空");

        // 权限检查
        List<DeviceInfo> deviceInfos = deviceInfoManager.list();
        List<String> authorityMessage = Lists.newArrayList();
        Iterator<ActGroupVo> it = list.iterator();
        while (it.hasNext()){
            ActGroupVo vo = it.next();
            deviceInfos.forEach(di -> {
                if(di.getCode().equals(vo.getDeviceCode())){
                    try{
                        BizUtils.checkLevel(di);
                    }catch (RuntimeException e){
                        it.remove();
                        authorityMessage.add(",");
                        authorityMessage.add(e.getMessage());
                        return;
                    }
                }
            });
        }

        String url = UrlConstant.ACT_GROUP;

        ResponseEntity<JSONObject> result = restTemplate.postForEntity(url, list, JSONObject.class);
        JSONObject body = result.getBody();
        if (!body.containsKey("response_code") || !"0".equals(body.getString("response_code"))) {
            return null;
        }

        //将字符串转成list集合
        List<BollardResultVo> data = JSONObject.parseArray(JSONObject.toJSONString(body.getJSONArray("data")), BollardResultVo.class);

        Map<String, ActGroupVo> actGroupVoMap = list.stream().collect(Collectors.toMap(item -> item.getController_id(), item -> item));
        StringBuffer sb = new StringBuffer();
        List<DeviceDataBarricade> deviceDataBarricades = Lists.newArrayList();
        data.forEach(bollardResultVo -> {
            String controllerId = bollardResultVo.getController_id();
            if (!actGroupVoMap.containsKey(controllerId)) {
                return;
            }

            ActGroupVo actGroupVo = actGroupVoMap.get(controllerId);
            DeviceDataBarricade deviceDataBarricade = new DeviceDataBarricade();
            deviceDataBarricade.setCollTime(LocalDateTime.now());
            deviceDataBarricade.setDeviceCode(actGroupVo.getDeviceCode());
            deviceDataBarricade.setAction(actGroupVo.getAction());
            if ("0".equals(bollardResultVo.getResponse_code())) {
                deviceDataBarricade.setStatus("1");
            } else {
                deviceDataBarricade.setStatus("0");
            }
            deviceDataBarricades.add(deviceDataBarricade);
            sb.append(",");
            sb.append("操作" + actGroupVo.getDeviceName() + bollardResultVo.getResponse_msg());
        });
        authorityMessage.forEach(sb::append);
        this.saveBatch(deviceDataBarricades);
        if (sb.length() > 1) {
            return sb.substring(1);
        }
        return null;
    }

    @Override
    public String lockAct(List<ActGroupVo> vo) {
        User currentUser = ContextUtil.getCurrentUser();
        Assert.notNull(currentUser, "获取当前登录用户异常！");
        List<DeviceInfo> deviceInfos = deviceInfoManager.list();
        StringBuffer sb = new StringBuffer();
        List<String> authorityMessage = Lists.newArrayList();
        List<DeviceDataBarricade> actData = Lists.newArrayList();
        vo.forEach(v->{
            String action  = "20".equals(v.getAction()) ? "锁定" : "解锁";
            deviceInfos.forEach(di->{
                if(v.getDeviceCode().equals(di.getCode())){
                    if (di.getLevel() > currentUser.getUserLevel()){
                        throw new RuntimeException(action+"【"+di.getName()+"】权限不足：所需级别为【"+di.getLevel()+"】，当前用户【"+currentUser.getFullname()+"】拥有的设备操作权限为【"+currentUser.getUserLevel()+"】！");
                    }
                    if ("21".equals(v.getAction()) && di.getLevel().equals(currentUser.getUserLevel()) && !di.getLockUser().equals(currentUser.getAccount()) ){
                        throw new RuntimeException(action+"【"+di.getName()+"】失败：同级设备只能由锁定人【"+di.getLockUser()+"】解锁");
                    }

                    boolean actResult = deviceInfoManager.update(new UpdateWrapper<DeviceInfo>()
                            .eq("code_", v.getDeviceCode()).set("IS_LOCK_", "20".equals(v.getAction())?"1":"0").set("LOCK_USER_", currentUser.getAccount()));

                    DeviceDataBarricade deviceDataBarricade = new DeviceDataBarricade();
                    deviceDataBarricade.setCollTime(LocalDateTime.now());
                    deviceDataBarricade.setDeviceCode(v.getDeviceCode());
                    deviceDataBarricade.setAction(v.getAction());
                    deviceDataBarricade.setCreateBy(currentUser.getAccount());
                    deviceDataBarricade.setStatus(actResult?"1":"0");
                    actData.add(deviceDataBarricade);
                    sb.append(",");
                    sb.append(action + di.getName() + "，状态："+actResult);
                }
            });
        });
        saveBatch(actData);
        authorityMessage.forEach(sb::append);
        if (sb.length() > 1) {
            return sb.substring(1);
        }
        return null;
    }

    @Override
    public CommonResult findByDeviceId(String productType, QueryFilter<DeviceDataBarricade> queryFilter) {
        Map<String, Object> data = Maps.newHashMap();
        data.put("productType", productType);

        PageBean pageBean = queryFilter.getPageBean();
        IPage<DeviceDataBarricade> result = baseMapper.findByDeviceId(convert2IPage(pageBean), convert2Wrapper(queryFilter, currentModelClass()));

        data.put("data", new PageList<DeviceDataBarricade>(result));
        return CommonResult.success(data, "查询成功");
    }

    @Override
    @Transactional(readOnly = true)
    public PageList<DeviceDataBarricade> query(QueryFilter<DeviceDataBarricade> queryFilter) {
        PageBean pageBean = queryFilter.getPageBean();
        Class<DeviceDataBarricade> currentModelClass = currentModelClass();
        IPage<DeviceDataBarricade> result = baseMapper.findByDeviceId(convert2IPage(pageBean), convert2Wrapper(queryFilter, currentModelClass));
        return new PageList<DeviceDataBarricade>(result);
    }
}
