package com.lightinit.hsdataplatform.impl.admin;

import com.google.gson.internal.LinkedTreeMap;
import com.lightinit.hsdataplatform.common.HttpUtil;
import com.lightinit.hsdataplatform.common.TokenUntils;
import com.lightinit.hsdataplatform.dictionary.*;
import com.lightinit.hsdataplatform.entity.*;
import com.lightinit.hsdataplatform.mapper.PublishInfoMapper;
import com.lightinit.hsdataplatform.mapper.PublishSettingMapper;
import com.lightinit.hsdataplatform.mapper.ResourceMapper;
import com.lightinit.hsdataplatform.mapper.ResourceMicroappMapper;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IResourceMicroappPublishService;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ResourceMicroappPublishServiceImpl implements IResourceMicroappPublishService {
    @Autowired
    private ResourceMicroappMapper resourceMicroappMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private PublishInfoMapper publishInfoMapper;
    @Autowired
    private PublishSettingMapper publishSttingMapper;
    public List<ResourceMicroappRegisterListModel> queryList(ResourceMicroappRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.selectModelList(inputModel);
    }




    public long queryCount(ResourceMicroappRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.selectModelCount(inputModel);

    }

    @Override
    public List<ResourceMicroappRegisterListModel> querypublishList(ResourceMicroappRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.querypublishList(inputModel);
    }

    @Override
    public long querypublishCount(ResourceMicroappRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.querypublishCount(inputModel);
    }

    @Transactional
    public ResultState<Long> delete(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        //删除microapp注册表
//        ResourceMicroappExample example2 = new ResourceMicroappExample();
//        ResourceMicroappExample.Criteria criteria2 = example2.createCriteria();
//        criteria2.andIdEqualTo(id);
//        int sqlResult2 = resourceMicroappMapper.deleteByExample(example2);

        //删除PublishSetting表
        PublishInfo obj = publishInfoMapper.selectByResourceId(id);
        List<APIPublishSettingModel> list = publishSttingMapper.selectBypublishId(obj.getId());
        int sqlResult4 = 0;
        for(APIPublishSettingModel obj1 :list) {
            PublishSettingExample example4 = new PublishSettingExample();
            PublishSettingExample.Criteria criteria4 = example4.createCriteria();
            criteria4.andIdEqualTo(id);
             sqlResult4 = publishSttingMapper.deleteByPublishInfoId(obj.getId());
        }

        //删除PublishInfo表
        PublishInfoExample example3 = new PublishInfoExample();
        PublishInfoExample.Criteria criteria3 = example3.createCriteria();
        criteria3.andIdEqualTo(id);
        int sqlResult3 = publishInfoMapper.deleteByPrimaryKey(obj.getId());

        //删除resource表
//        ResourceExample example1 = new ResourceExample();
//        ResourceExample.Criteria criteria1 = example1.createCriteria();
//        criteria1.andIdEqualTo(id);
//        int sqlResult1 = resourceMapper.deleteByExample(example1);

        if (!(sqlResult3 >0 && sqlResult4> 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据不存在");
        }
        resultState.setData(id);
        return resultState;
    }


    public Object queryOne(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResourceDataMicroappDataModel outputModel = new ResourceDataMicroappDataModel();
        Resource entity1 = resourceMapper.selectByPrimaryKey(id);
        ResourceMicroappWithBLOBs entity2 = resourceMicroappMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(entity2, outputModel);
        BeanUtils.copyProperties(entity1, outputModel);
        return outputModel;
    }

//    public Object aduit(long id) {
//        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
//        ResourceMicroappPublishDataModel outputModel = new ResourceMicroappPublishDataModel();
//        Resource entity1 = resourceMapper.selectByPrimaryKey(id);
//        ResourceMicroappWithBLOBs entity2 = resourceMicroappMapper.selectByPrimaryKey(id);
//        PublishInfo entity3 = publishInfoMapper.selectByResourceId(id);
//        List<PublishSetting> list = publishSttingMapper.selectBypublishId(entity3.getId());
//
//        BeanUtils.copyProperties(entity2, outputModel);
//        BeanUtils.copyProperties(entity1, outputModel);
//        BeanUtils.copyProperties(entity3, outputModel);
//
//        outputModel =  resourceMicroappMapper.selectMicroappAduitModel(id);
//        return outputModel;
//    }

    @Override
    public ResourceMicroappWithBLOBs selectMicroappId(long id) {

        return resourceMicroappMapper.selectByPrimaryKey(id);
    }

    @Override
    public Object selectResourceId(long id) {
        return  (Resource) resourceMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<APIPublishSettingModel> selectByPublishInfoId(long id) {
        return publishSttingMapper.selectBypublishId(id);
    }

    @Override
    public PublishInfoWithBLOBs selectByResourceId(long id) {
        return   publishInfoMapper.selectByResourceId(id);
    }


    public ResultState edit(ResourceMicroappPublishDataModel inputModel) {
        ResultState<Long> resultState = new ResultState<>();
        try {
            Long publishInfoId = inputModel.getPublishInfoId();
            PublishSettingExample publishSettingExample = new PublishSettingExample();
            publishSettingExample.createCriteria().andPublishInfoIdEqualTo(publishInfoId);
            List<Long> publishSettingsInDataBaseList = publishSttingMapper.selectPublishSettingByPublishInfoId(publishInfoId);
            List<PublishSetting> list = inputModel.getSettingList();
            PublishSetting publishSettingEntry=null;
            ArrayList<Long> idList = new ArrayList<>();
            if(list !=null && list.size()>0) {
                for (PublishSetting publishSetting : list) {
                    if(org.apache.commons.lang3.StringUtils.isEmpty(publishSetting.getPackageName())){    //套餐名称必填项，这里通过名称判断角标为空的剔除
                        continue;
                    }
                    if(publishSetting.getId() ==null|| publishSetting.getId()==0){  //前端默认添加数据id为0
                        publishSettingEntry=new PublishSetting();
                        BeanUtils.copyProperties(publishSetting,publishSettingEntry);
                        publishSetting.setPublishInfoId(publishInfoId);
                        publishSttingMapper.insert(publishSetting);
                    }else{
                        publishSettingEntry=new PublishSetting();
                        BeanUtils.copyProperties(publishSetting,publishSettingEntry);
                        publishSetting.setPublishInfoId(publishInfoId);
                        publishSttingMapper.updateByPrimaryKeySelective(publishSettingEntry);
                        idList.add(publishSetting.getId());
                    }
                }
            }
            //用前端传入的集合id与数据库中的集合id比较，前端不包含的id即为删除的id--->更新删除时间和删除人
            if(publishSettingsInDataBaseList!=null && publishSettingsInDataBaseList.size()>0){
                for (Long aLong : publishSettingsInDataBaseList) {
                    if(! idList.contains(aLong)){
                        publishSettingEntry=new PublishSetting();
                        publishSettingEntry.setId(aLong);
                        publishSettingEntry.setDeletedAt(new Date());
                        publishSettingEntry.setDeletedBy(inputModel.getDeleteById());
                        publishSttingMapper.updateByPrimaryKeySelective(publishSettingEntry);
                    }
                }
            }
            PublishInfoWithBLOBs publishInfoWithBLOBs = new PublishInfoWithBLOBs();
            publishInfoWithBLOBs.setOpenCondition(inputModel.getOpenCondition());
            publishInfoWithBLOBs.setShareCondition(inputModel.getShareCondition());
            publishInfoWithBLOBs.setResourceImg(inputModel.getResourceImg());
            publishInfoWithBLOBs.setPublishState(inputModel.getPublishState());
            publishInfoWithBLOBs.setId(inputModel.getPublishInfoId());
//            if(dataPublishDetailModel.getParam()==1){
//                publishInfoWithBLOBs.setPublishState(DicDataPublishState.PENDING);
//            }else{
//                publishInfoWithBLOBs.setPublishState(DicDataPublishState.DRAFT);
//            }
            publishInfoMapper.updateByPrimaryKeySelective(publishInfoWithBLOBs);
            resultState.setData(publishInfoId);
            return  resultState;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("编辑失败");
        return resultState;
    }

    @Override
    public List<ResourceMicroappRegisterListModel> querypublishAduitList(ResourceMicroappRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.querypublishAduitList(inputModel);
    }

    @Override
    public long querypublishAduitCount(ResourceMicroappRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.querypublishAduitCount(inputModel);
    }

    @Override
    public ResultState<Long> doPublish(ResourceMicroappPublishDataModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Date createdAt = new Date();

        PublishInfoWithBLOBs entity1 = new PublishInfoWithBLOBs();
        entity1.setResourceId(inputModel.getId());
        entity1.setPublishState(inputModel.getPublishState());
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setPublishState(StringUtils.isNotEmpty(inputModel.getPublishState()) && inputModel.getPublishState().equals(DicResourceMicroappPublishState.AUDITING) ? DicResourceMicroappPublishState.AUDITING : DicResourceMicroappPublishState.DRAFT);
        entity1.setCreatedAt(createdAt);
        int sqlResult1 = publishInfoMapper.insert(entity1);
        List<PublishSetting> list = inputModel.getSettingList();
        int sqlResult2 =0;
        if(list!=null && list.size()>0) {
            for (PublishSetting entity2 :list){
                PublishSetting obj = new PublishSetting();
                entity2.setPublishInfoId(entity1.getId());
                BeanUtils.copyProperties(entity2, obj);
                obj.setCreatedAt(createdAt);
                sqlResult2 = publishSttingMapper.insert(obj);
            }
        }

        if (!(sqlResult1 > 0 )){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据插入失败");
        }
        resultState.setData(entity1.getId());        return resultState;
    }

    @Override
    public ResultState downframe(PublishInfo publishInfo) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        PublishInfoWithBLOBs entity = new PublishInfoWithBLOBs();
        BeanUtils.copyProperties(publishInfo, entity);
        PublishInfoExample example = new PublishInfoExample();
        PublishInfoExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(publishInfo.getId());
         int sqlResult = publishInfoMapper.updateByExampleSelective(entity, example);
        if (!(sqlResult > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据下架失败");
        }
        resultState.setData(entity.getId());
        return resultState;
    }

    @Override
    public ResultState doAduit(ResourceMicroappPublishDataModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        PublishInfoWithBLOBs entity1 = new PublishInfoWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setPublishState(inputModel.getPublishState());
        entity1.setId(inputModel.getPublishInfoId());
        entity1.setAuditResult(inputModel.getAuditResult());
        entity1.setAuditedAt(new Date());
        int sqlResult1 = publishInfoMapper.updateByPrimaryKeySelective(entity1);
        if (!(sqlResult1 > 0 )){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("审核失败");
        }
//        else {
//            //获取token
//
////                Map<String,String> map = new HashMap<>();
////                map.put("Authorization","Basic bm9raWE6bm9raWE=");
////                map.put("Content-Type","application/x-www-form-urlencoded");
////                String aa = "grant_type=password&username=admin&password=hB6f4hZyWNj0h4boFy7E5l3pt8CL%2BTCI7ifwKF5UKo52GFe19ObDGoVFrv3aszrYX3k5tZ5j3gwl%2BnY0Q2Eyb3tQACa8pHCOGsx1s4z1msJ88LtJpQ9gycfSYT3uVP4WCNa6VK3OmKvUMITJRz3VqEYoVspk3DMjBRXxJ5JxCmM%3D";
////                Map<String,Object> token = HttpUtil.strToMap(HttpUtil.getToken(DicPaasApi.TOKEN,map,aa));
////                String ss = (String)token.get("access_token");
//                String ss=  TokenUntils.getToken();
//                //新建路由规则
//                HashMap<String, String> headers = new HashMap<>();
//                headers.put("Content-Type", "application/json");
//                headers.put("Authorization", ss);
//                HashMap<String, Object> json = new HashMap<>();
//                json.put("id",inputModel.getRouteId());
//                json.put("path",inputModel.getPath());
////                json.put("lesseeId",Integer.parseInt(inputModel.getServiceId().substring(0,inputModel.getServiceId().indexOf(".")))) ;
//                json.put("serviceId",inputModel.getServiceId());
//                json.put("url"," ");
//                json.put("appName",inputModel.getAppName());
//                json.put("refreshInterval",inputModel.getRefreshInterval());
//                json.put("policyLimit",inputModel.getPolicyLimit());
//                json.put("lesseeId",inputModel.getLesseeId());
//                json.put("authType",inputModel.getAuthType());
//                json.put("authValue",inputModel.getAuthValue());
//                json.put("retryable",inputModel.getRetryable());
//                json.put("enabled",inputModel.getEnabled());
//                json.put("stripPrefix",inputModel.getStripPrefix());
//            try {
//                String message = HttpUtil.httpPost(DicPaasApi.ROUTE_ADD, headers, json); //同步
//                Map<String,Object> map1= HttpUtil.strToMap(message) ;
//                if ((boolean)map1.get("success")){
//                    Map<String,Object> map2= (Map<String, Object>) map1.get("data");
//                    String outId = (String) map2.get("id");
//                    publishInfoMapper.insertOutId(outId,inputModel.getId()) ;
//                }
//                System.out.println("-------------------"+message+"------------------------");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//
//        }
        resultState.setData(inputModel.getId());
        return resultState;
    }

    @Override
    public ResultState shoreAduit(ResourceMicroappPublishDataModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        PublishInfoWithBLOBs entity1 = new PublishInfoWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setPublishState(inputModel.getPublishState());
        entity1.setId(inputModel.getPublishInfoId());
        entity1.setAuditResult(inputModel.getAuditResult());
        entity1.setAuditedAt(new Date());
        int sqlResult1 = publishInfoMapper.updateByPrimaryKeySelective(entity1);
        if (!(sqlResult1 > 0 )){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("审核失败");
        }
        else {
            //获取token

//                Map<String,String> map = new HashMap<>();
//                map.put("Authorization","Basic bm9raWE6bm9raWE=");
//                map.put("Content-Type","application/x-www-form-urlencoded");
//                String aa = "grant_type=password&username=admin&password=hB6f4hZyWNj0h4boFy7E5l3pt8CL%2BTCI7ifwKF5UKo52GFe19ObDGoVFrv3aszrYX3k5tZ5j3gwl%2BnY0Q2Eyb3tQACa8pHCOGsx1s4z1msJ88LtJpQ9gycfSYT3uVP4WCNa6VK3OmKvUMITJRz3VqEYoVspk3DMjBRXxJ5JxCmM%3D";
//                Map<String,Object> token = HttpUtil.strToMap(HttpUtil.getToken(DicPaasApi.TOKEN,map,aa));
//                String ss = (String)token.get("access_token");
            //插入权限
            Map<String,Object> sysAuthority = new HashMap<>() ;
            sysAuthority.put("name",inputModel.getGatewayRouteId()) ;
            sysAuthority.put("value",inputModel.getAppName()) ;
                String ss=  TokenUntils.getToken();
                //新建路由规则
                HashMap<String, String> headers = new HashMap<>();
                String lesseeId = inputModel.getLesseeId() ;
                headers.put("Content-Type", "application/json");
                headers.put("Authorization", ss);
                HashMap<String, Object> json = new HashMap<>();
                json.put("id",inputModel.getGatewayRouteId());
                json.put("path",inputModel.getPath());
                json.put("lesseeId",Integer.parseInt(lesseeId.substring(0,lesseeId.indexOf(".")))) ;
                json.put("serviceId",inputModel.getServiceId());
                json.put("url"," ");
                json.put("appName",inputModel.getAppName());
                json.put("refreshInterval",inputModel.getRefreshInterval());
                json.put("policyLimit",inputModel.getPolicyLimit());
                json.put("authType",inputModel.getAuthType());
                json.put("authValue",inputModel.getAuthValue());
                json.put("retryable",inputModel.getRetryable());
                json.put("enabled",inputModel.getEnabled());
                json.put("stripPrefix",inputModel.getStripPrefix());
            try {
                String str1 = HttpUtil.httpPost(DicPaasApi.ADDAUTHORITIES, TokenUntils.getHead() ,sysAuthority) ;
                Map<String,Object> map3= HttpUtil.strToMap(str1) ;
                if ((boolean)map3.get("success")){
                    LinkedTreeMap linkedTreeMap3 = (LinkedTreeMap) map3.get("data");
                    String name = (String) linkedTreeMap3.get("name");
                    json.put("authWrite",name) ;
                    json.put("authRead",name) ;
                    String str = HttpUtil.httpPost(DicPaasApi.ROUTE_ADD,headers,json) ;
                    Map<String,Object> map1= HttpUtil.strToMap(str) ;
                    if ((boolean)map1.get("success")){
                        Map<String,Object> map2= (Map<String, Object>) map1.get("data");
                        String outId = (String) map2.get("id");
                        String authId = (String) map3.get("id");
                        publishInfoMapper.insertOutIdTwo(outId,inputModel.getId(),authId) ;
                    }
                    System.out.println("-------------------"+str+"------------------------");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        resultState.setData(inputModel.getId());
        return resultState;
    }

}
