package com.yunfeiyun.agmp.fms.service.impl;

import java.util.*;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.enums.DictTypeEnums;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.DictUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.fms.AgmpFmsApplication;
import com.yunfeiyun.agmp.fms.domain.TmnBase;
import com.yunfeiyun.agmp.fms.domain.TmnBlock;
import com.yunfeiyun.agmp.fms.mapper.FmsLandMapper;
import com.yunfeiyun.agmp.fms.mapper.TmnBaseMapper;
import com.yunfeiyun.agmp.fms.mapper.TmnBlockMapper;
import com.yunfeiyun.agmp.fms.domain.resvo.TmnBaseTypeResVo;
import com.yunfeiyun.agmp.fms.service.ITmnBaseService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;


/**
 * 设备Service业务层处理
 *
 * @author 杨晓辉
 * @date 2023-07-06
 */
@Service
public class TmnBaseServiceImpl implements ITmnBaseService
{
    @Autowired
    private TmnBaseMapper tmnBaseMapper;
    @Autowired
    private FmsLandMapper fmsLandMapper;

    @Autowired
    private TmnBlockMapper tmnBlockMapper;

    private final RestTemplate restTemplate = new RestTemplate();

    private static final Logger log = LoggerFactory.getLogger(AgmpFmsApplication.class);

    /** 是否开启swagger */
    @Value("${openBigdata.origin}")
    private String origin;

    /**
     * 查询设备
     *
     * @param tmnId 设备主键
     * @return 设备
     */
    @Override
    public TmnBase selectTmnBaseByTmnId(String tmnId)
    {
        return tmnBaseMapper.selectTmnBaseByTmnId(tmnId);
    }

    /**
     * 查询最新一台设备
     *
     * @return 设备
     */
    @Override
    public TmnBase selectTmnBaseByOne()
    {
        return tmnBaseMapper.selectTmnBaseByOne();
    }

    /**
     * 查询设备列表
     *
     * @param tmnBase 设备
     * @return 设备
     */
    @Override
    public List<TmnBase> selectTmnBaseList(TmnBase tmnBase)
    {
        String tmnType = tmnBase.getTmnType();
        if (!StringUtils.isEmpty(tmnType)){
            String[] tmnTypeIds = StringUtils.split(tmnType, ",");
            tmnBase.setTmnTypeIds(tmnTypeIds);
        }

        List<TmnBase> tmnBaseList = tmnBaseMapper.selectTmnBaseList(tmnBase);
        String[] tmnIds = new String[tmnBaseList.size()];
        int index = 0;
        for(TmnBase tb: tmnBaseList){
            if (!ObjectUtils.isEmpty(tb.getLandId())){
                tmnIds[index] = tb.getTmnId();
                index += 1;
            }
        }

        Map<String, ArrayList<String>> tmnBlockMap = new HashMap<>();
        Map<String, ArrayList<TmnBlock>> tmnBlockInfoMap = new HashMap<>();

        if(!ObjectUtils.isEmpty(tmnIds)){
            List<TmnBlock> tmnBlockList = this.tmnBlockMapper.selectTmnBlockListByTmnIds(tmnIds);
            for(TmnBlock tmnBlock: tmnBlockList){
                String tmnId = tmnBlock.getTmnId();
                String blockName = tmnBlock.getBlockName();

                ArrayList<String> bv = tmnBlockMap.getOrDefault(tmnId, new ArrayList<>());
                bv.add(blockName);
                tmnBlockMap.put(tmnId, bv);

                ArrayList<TmnBlock> bvInfo = tmnBlockInfoMap.getOrDefault(tmnId, new ArrayList<>());
                bvInfo.add(tmnBlock);
                tmnBlockInfoMap.put(tmnId, bvInfo);
            }
            for(TmnBase tb: tmnBaseList){
                String tmnId = tb.getTmnId();
                if (tmnBlockMap.containsKey(tmnId)){
                    tb.setBlockNames(StringUtils.join(tmnBlockMap.get(tmnId), ","));
                    tb.setBlockInfoList(tmnBlockInfoMap.get(tmnId));
                }
            }

        }
        return tmnBaseList;
    }

    /**
     * 查询设备列表
     * @return 设备列表集合
     */
    @Override
    public List<TmnBaseTypeResVo> selectTmnBaseTypeList()
    {
        int total = 0;
        List<TmnBaseTypeResVo> tempList = tmnBaseMapper.selectTmnBaseTypeList();
        List<TmnBaseTypeResVo> tmnBaseTypeResVoList = new ArrayList<>();

        if (ObjectUtils.isEmpty(tempList)){
            return tmnBaseTypeResVoList;
        }

        for (TmnBaseTypeResVo tmnBaseTypeResVo: tempList){
            String tmnTypeName = DictUtils.getDictLabel(DictTypeEnums.TMN_BASE_TYPE.getCode(), tmnBaseTypeResVo.getTmnType());
            if (StringUtils.isEmpty(tmnTypeName)){
                continue;
            }
            tmnBaseTypeResVo.setTmnTypeName(tmnTypeName);
            total += tmnBaseTypeResVo.getTmnTypeNum();
            tmnBaseTypeResVoList.add(tmnBaseTypeResVo);
        }

        if (!ObjectUtils.isEmpty(tmnBaseTypeResVoList)) {
            TmnBaseTypeResVo totalTmnBaseType = new TmnBaseTypeResVo();
            totalTmnBaseType.setTmnTypeName("全部设备");
            totalTmnBaseType.setTmnTypeNum(total);
            tmnBaseTypeResVoList.add(0, totalTmnBaseType);
        }

        return tmnBaseTypeResVoList;
    }

    /**
     * 新增设备
     *
     * @param tmnBase 设备
     * @return 结果
     */
    @Override
    public int insertTmnBase(TmnBase tmnBase)
    {
        return tmnBaseMapper.insertTmnBase(tmnBase);
    }


    /**
     * 修改设备
     *
     * @param tmnBase 设备
     * @return 结果
     */
    @Override
    public int updateTmnBase(TmnBase tmnBase)
    {
        return tmnBaseMapper.updateTmnBase(tmnBase);
    }

    /**
     * 同步设备
     *
     * @return 结果
     */
    @Override
    public int syncTmnBase(){
        return this.syncTmnBase(null);
    }
    /**
     * 同步设备
     *
     * @return 结果
     */
    @Override
    public int syncTmnBase(String startTimestamp)
    {
        String nsToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS2256")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 5))
                .signWith(SignatureAlgorithm.HS256,"nong_shi_xi_tong".getBytes())
                .compact();

        HashMap<String, String> params = new HashMap<>();
        params.put("ns_token", nsToken);
        params.put("device_type_ids", "2,3,5,6,7,15,30,31,32,33,34");

        if (StringUtils.isEmpty(startTimestamp)){
            TmnBase tb = this.selectTmnBaseByOne();
            if (!ObjectUtils.isEmpty(tb)){
                Date createddate = DateUtils.parseDate(tb.getTmnCreateddate());
                long startTime = createddate.getTime() / 1000L;
                params.put("start_time", String.valueOf(startTime));
            }
        }else{
            params.put("start_time", String.valueOf(startTimestamp));
        }

        String url = this.origin + "/api/device/device/ns/info/list/";
        log.info("设备同步: " + url);
        AjaxResult response = null;

        try {
            response = this.restTemplate.postForObject(url, params, AjaxResult.class );
            JSONArray dataList = JSONArray.from(response.get("data"));
            if (ObjectUtils.isEmpty(dataList)){
                return 1;
            }

            ArrayList<TmnBase> tmnBaseArrayList = new ArrayList<>();
            for (Object o : dataList) {
                JSONObject item = JSONObject.from(o);
                TmnBase tmnBase = new TmnBase();
                tmnBase.setTmnId(tmnBase.getId());
                tmnBase.setTmnBizcode(item.get("device_id").toString());
                String tmnName = item.get("device_name").toString();
                String tmnType = item.get("device_type_id").toString();
                String lat = item.getOrDefault("lat", "").toString();
                String lng = item.getOrDefault("lng", "").toString();

                if (StringUtils.isEmpty(tmnType)){
                    continue;
                }
                if (StringUtils.isEmpty(tmnName)){
                    tmnName = DictUtils.getDictLabel(DictTypeEnums.TMN_BASE_TYPE.getCode(), tmnType);
                }
                tmnBase.setTmnName(tmnName);
                tmnBase.setTmnType(tmnType);
                tmnBase.setTmnLatitude(lat);
                tmnBase.setTmnLongitude(lng);
                tmnBase.setTmnCreateddate(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));

                tmnBaseArrayList.add(tmnBase);
            }
            int startIndex = 0;
            int step = 500;
            int tmpSize = tmnBaseArrayList.size();
            while (startIndex < tmpSize){
                int endIndex = Math.min(startIndex + step, tmpSize);
                this.tmnBaseMapper.insertTmnBaseBatch(tmnBaseArrayList.subList(startIndex, endIndex));
                startIndex = endIndex;
            }

        }catch (Exception e) {
            e.printStackTrace();
            // 设备同步错误
            throw new BizException(ErrorCode.TMN_DEVICE_SYNC_ERROR);
        }

        return 1;
    }

    /**
     * 批量删除设备
     * 
     * @param tmnIds 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteTmnBaseByTmnIds(String[] tmnIds)
    {
        return tmnBaseMapper.deleteTmnBaseByTmnIds(tmnIds);
    }

    /**
     * 删除设备信息
     * 
     * @param tmnId 设备主键
     * @return 结果
     */
    @Override
    public int deleteTmnBaseByTmnId(String tmnId)
    {
        return tmnBaseMapper.deleteTmnBaseByTmnId(tmnId);
    }
}
