package com.foreverwin.mesnac.equip.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.meapi.mapper.DcParameterMapper;
import com.foreverwin.mesnac.meapi.model.DcParameter;
import com.foreverwin.mesnac.meapi.model.Resrce;
import com.foreverwin.mesnac.meapi.service.ResrceService;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.util.FrontPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.foreverwin.mesnac.equip.model.EdcDataResource;
import com.foreverwin.mesnac.equip.mapper.EdcDataResourceMapper;
import com.foreverwin.mesnac.equip.service.EdcDataResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pavel.liu
 * @since 2021-07-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EdcDataResourceServiceImpl extends ServiceImpl<EdcDataResourceMapper, EdcDataResource> implements EdcDataResourceService {

    @Autowired
    private EdcDataResourceMapper edcDataResourceMapper;
    @Autowired
    private EdcDataResourceService edcDataResourceService;
    @Autowired
    private DcParameterMapper dcParameterMapper;
    @Autowired
    private ResrceService resrceService;

    @Override
    public IPage<EdcDataResource> selectPage(FrontPage<EdcDataResource> frontPage, EdcDataResource edcDataResource) {
        QueryWrapper<EdcDataResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(edcDataResource);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<EdcDataResource> selectList(EdcDataResource edcDataResource) {
        QueryWrapper<EdcDataResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(edcDataResource);
        return super.list(queryWrapper);
    }

    @Override
    public void removeAll(EdcDataResource edcDataResource) {
        QueryWrapper<EdcDataResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(edcDataResource);
        super.remove(queryWrapper);
    }

    @Override
    public void saveResourceParamByMq(String text) {
        // json解析，获取json中数据
        JSONObject jsonObject = JSONObject.parseObject(text);
//        String handle = jsonObject.getString("TRANID");
        String site = jsonObject.getString("SITE");
//        String resource = jsonObject.getString("RESOURCE");
        String resource = jsonObject.getString("equipmentId");
        String sendTime = jsonObject.getString("SEND_TIME");
        if (StringUtil.isBlank(site)) {
            throw BusinessException.build("站点不能为空！");
        }
        if (StringUtil.isBlank(resource)) {
            throw BusinessException.build("设备编号不能为空！");
        }
        String resourceHandle = HandleEnum.RESOURCE.getHandle(site, resource);
        Resrce resourceById = resrceService.getById(resourceHandle);
        if (resourceById == null){
            throw BusinessException.build("未找到设备编号为" + resource + "的设备！");
        }

        // 参数列，将参数存入MAP，方便提取
        /*String paramList = jsonObject.getString("PARAM_LIST");
        JSONArray jsonArray = JSON.parseArray(paramList);
        Map<String,String> map = new HashMap<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObj = (JSONObject) jsonArray.get(i);
            String paramVal = jsonObj.getString("PARAM_VAL");
            String param = jsonObj.getString("PARAM");
            map.put(param,paramVal);
        }*/
        // 获取数据收集组HANDLE
        /*String resourceBo = HandleEnum.RESOURCE.getHandle(site, "Z_EDC_DATA_RESOURCE");
        String dcGroupBo = edcDataResourceMapper.getDcGroupBoByResourceBo(resourceBo);
        if (dcGroupBo == null){
            dcGroupBo = edcDataResourceMapper.getDcGroupBoByResourceBo2(resourceBo);
            if (dcGroupBo == null){
                throw BusinessException.build("设备编号["+ resource +"]未找到数据收集组！");
            }
        }*/
        // 获取数据收集组的字段配置信息
        StringBuilder columnValSql = new StringBuilder();
        StringBuilder columnSql = new StringBuilder();
        List<DcParameter> getParamList = dcParameterMapper.getDcParameterByDcGroupBo("DcGroupBO:1000,RESOURCE_EDC,A");
        if (getParamList.size() <= 0){
//            throw BusinessException.build("数据收集组" + dcGroupBo + "未维护字段信息");
            throw BusinessException.build("数据收集组" + "DcGroupBO:1000,RESOURCE_EDC,A" + "未维护字段信息");
        }
        for (DcParameter dcParam:getParamList) {
            String parameterName = dcParam.getDescription();
            // 数据收集组---值-列
            String dcValueMask = dcParam.getDcValueMask();
            // json值
//            String value = map.get(parameterName);
            String value = jsonObject.getString(parameterName);
            if (value == null){
                continue;
            }
            // 字段
            columnSql.append(dcValueMask).append(",");
            // 值
            if (dcValueMask.indexOf('N')==-1){
                columnValSql.append("'").append(value).append("'").append(",");
            }else {
                columnValSql.append(value).append(",");
            }
        }
        StringBuilder sqlStr = new StringBuilder();
        String nowString = LocalDateTime.now().toString().substring(0, 19).replace('T', ' ');
        EdcDataResource edcDataResource = new EdcDataResource();
        edcDataResource.setResrce(resource);
        edcDataResourceService.removeAll(edcDataResource);
        sqlStr.append("INSERT INTO Z_EDC_DATA_RESOURCE")
                //.append(resource.replace("-","_"))
                //.append("@ODS")
                .append(" (HANDLE,SITE,RESRCE,DC_GROUP_BO,DATE_TIME,CREATED_DATE_TIME,CREATE_USER,")
                .append(columnSql.substring(0,columnSql.length()-1))
                .append(") ")
                .append(" VALUES ('")
                .append(UUID.randomUUID()).append("','")
                .append(site).append("','")
                .append(resource).append("','")
//                .append(dcGroupBo).append("',")
                .append("DcGroupBO:1000,RESOURCE_EDC,A").append("',")
                .append("TO_DATE('").append(sendTime).append("','yyyy-MM-dd hh24:mi-ss') ,")
                .append("TO_DATE('").append(nowString).append("','yyyy-MM-dd hh24:mi-ss') ,'")
                .append("SITE_ADMIN").append("',")
                .append(columnValSql.substring(0,columnValSql.length()-1))
                .append(" )");
        edcDataResourceMapper.insertBySql(sqlStr.toString());
    }

}