package com.lightinit.hsdataplatform.impl.admin;

import com.lightinit.hsdataplatform.common.HttpUtil;
import com.lightinit.hsdataplatform.common.TokenUntils;
import com.lightinit.hsdataplatform.dictionary.DicPaasApi;
import com.lightinit.hsdataplatform.dictionary.DicPublishApiState;
import com.lightinit.hsdataplatform.dictionary.DicResourceState;
import com.lightinit.hsdataplatform.entity.*;
import com.lightinit.hsdataplatform.mapper.*;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IApiPublishService;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApiPublishServiceImpl implements IApiPublishService {

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourceApiInterfaceMapper resourceApiInterfaceMapper;

    @Autowired
    private PublishInfoMapper publishInfoMapper;

    @Autowired
    private PublishSettingMapper publishSettingMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper ;


    @Override
    public List<APIPublishListModel> queryList(APIPublishSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.queryAllPublishApiList(inputModel);
    }

    @Override
    public long queryCount(APIPublishSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.queryAllPublishApiCount(inputModel);
    }

    @Override
    public List<ResourceAPIRegisterListModel> queryPublishList(ResourceAPIRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        inputModel.setResourceState(DicResourceState.APPROVED);
        return publishInfoMapper.queryPublishList(inputModel);
    }

    @Override
    public long queryPublishCount(ResourceAPIRegisterSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        inputModel.setResourceState(DicResourceState.APPROVED);
        return publishInfoMapper.queryPublishCount(inputModel);
    }

    @Override
    public ResourceAPIRegisterViewResourceModel queryOneViewResource(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceMapper.queryOneViewResource(id);
    }

    @Override
    public List<ResourceApiInterfaceWithBLOBs> queryOneResourceAPIInterface(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        List<ResourceApiInterfaceWithBLOBs> resourceApiInterfaceList = resourceApiInterfaceMapper.selectByAPIid(id);
        return resourceApiInterfaceList;
    }

    @Override
    @Transactional
    public ResultState<Long> publishAPI_add(APIPublishInfoAndSettingModel apiPublishInfoAndSettingModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Date createdAt = new Date();

        //插入publish_info
        PublishInfoWithBLOBs entity1 = new PublishInfoWithBLOBs();
        BeanUtils.copyProperties(apiPublishInfoAndSettingModel, entity1);
        entity1.setCreatedAt(createdAt);
        int sqlResult1 = publishInfoMapper.insert(entity1);


        //插入publish_setting
        if (apiPublishInfoAndSettingModel.getApiPublishSettingList() != null) {
            List<APIPublishSettingModel> apiPublishSettingList = apiPublishInfoAndSettingModel.getApiPublishSettingList();
            //判断是否为空
            if (!apiPublishSettingList.isEmpty() && apiPublishSettingList.size() > 0) {
                for (APIPublishSettingModel apiPublishSettingModel : apiPublishSettingList) {
                    if (!org.springframework.util.StringUtils.isEmpty(apiPublishSettingModel)) {
                        //循环插入
                        PublishSetting entity2 = new PublishSetting();
                        BeanUtils.copyProperties(apiPublishSettingModel, entity2);
                        entity2.setPublishInfoId(entity1.getId());
                        entity2.setCreatedAt(createdAt);
                        int sqlResult2 = publishSettingMapper.insert(entity2);
                    }
                }
            }
        }
        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据插入失败");
        }
        resultState.setData(entity1.getId());
        return resultState;
    }

    @Override
    @Transactional
    public ResultState<Long> delete(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        //删除publish_setting
        PublishSettingExample example1 = new PublishSettingExample();
        PublishSettingExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andPublishInfoIdEqualTo(id);
        int sqlResult1 = publishSettingMapper.deleteByExample(example1);

        //删除publish_info
        PublishInfoExample example2 = new PublishInfoExample();
        PublishInfoExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andIdEqualTo(id);
        int sqlResult2 = publishInfoMapper.deleteByExample(example2);

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

    @Override
    public ResultState<Long> downframe(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        //更改为下架状态
        PublishInfoWithBLOBs entity1 = new PublishInfoWithBLOBs();
        PublishInfoExample example1 = new PublishInfoExample();
        entity1.setPublishState(DicPublishApiState.UN_PUBLISH);
        PublishInfoExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(id);
        int sqlResult1 = publishInfoMapper.updateByExampleSelective(entity1, example1);
        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据更新失败");
        }
        resultState.setData(id);
        return resultState;
    }

    @Override
    public PublishInfoWithBLOBs queryOnePublishInfoById(long publishInfoId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        PublishInfoWithBLOBs entity1 = publishInfoMapper.selectByPrimaryKey(publishInfoId);
        return entity1;
    }

    @Override
    public List<PublishSetting> queryListPublishSettingByInfoId(long publishInfoId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        PublishSettingExample example1 = new PublishSettingExample();
        PublishSettingExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andPublishInfoIdEqualTo(publishInfoId);
        return publishSettingMapper.selectByExample(example1);
    }

    @Override
    public PublishSetting queryOnePublishSettingById(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishSettingMapper.selectByPrimaryKey(id) ;
    }

    @Override
    public ResultState<Long> toExamine(APIToExamineModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        //审核publish_info表
        PublishInfoWithBLOBs entity1 = new PublishInfoWithBLOBs();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setAuditedAt(new Date());
        PublishInfoExample example1 = new PublishInfoExample();
        PublishInfoExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(inputModel.getId());
        int sqlResult1 = publishInfoMapper.updateByExampleSelective(entity1, example1);
        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据失败");
//            String lesseeId = inputModel.getLesseeId() ;
//            Map<String,Object> map = new HashMap<>() ;
//            map.put("id",inputModel.getGatewayRouteId()) ;
//            map.put("path",inputModel.getPath()) ;
//            map.put("serviceId",inputModel.getServiceId()) ;
//            map.put("appName",inputModel.getAppName()) ;
//            map.put("refreshInterval",inputModel.getRefreshInterval()) ;
//            map.put("policyLimit",inputModel.getPolicyLimit()) ;
//            map.put("policyQuota",inputModel.getPolicyQuota()) ;
//            map.put("lesseeId",Integer.parseInt(lesseeId.substring(0,lesseeId.indexOf(".")))) ;
//            map.put("authType",inputModel.getAuthType()) ;
//            map.put("authValue",inputModel.getAuthValue()) ;
//            map.put("stripPrefix",inputModel.isStripPrefix()) ;
//            map.put("retryable",inputModel.isRetryable()) ;
//            map.put("enabled",inputModel.isEnabled()) ;
//            Map<String,String> heads = new HashMap<>() ;
//            heads.put("Authorization",TokenUntils.getToken()) ;
//            heads.put("Content-Type","application/json") ;
//            try {
//                String str = HttpUtil.httpPost(DicPaasApi.ROUTE_ADD,heads,map) ;
//                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");
//                    publishInfoMapper.insertOutId(outId,inputModel.getId()) ;
//                }
//                System.out.println("-------------------"+str+"------------------------");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }
        resultState.setData(inputModel.getId());
        return resultState;
    }

    @Override
    @Transactional
    public ResultState<Long> publishAPI_edit(APIPublishInfoAndSettingEditModel infoAndSettingEditModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Date createdAt = new Date();

        //修改publish_info表
        PublishInfoWithBLOBs entity1 = new PublishInfoWithBLOBs();
        BeanUtils.copyProperties(infoAndSettingEditModel, entity1);
        entity1.setId(infoAndSettingEditModel.getPublishInfoId());
        PublishInfoExample  example1 = new PublishInfoExample();
        PublishInfoExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(infoAndSettingEditModel.getPublishInfoId());
        int sqlResult1 = publishInfoMapper.updateByExampleSelective(entity1, example1);

        //删除publish_setting中删除的行
        if(infoAndSettingEditModel.getDeletePublishSettingIds()!=null){
            if (infoAndSettingEditModel.getDeletePublishSettingIds().size()>0){
                for (Long aLong : infoAndSettingEditModel.getDeletePublishSettingIds()) {
                    PublishSettingExample example2 = new PublishSettingExample();
                    PublishSettingExample.Criteria criteria2 = example2.createCriteria();
                    criteria2.andIdEqualTo(aLong);
                    int sqlResult2 = publishSettingMapper.deleteByExample(example2);
                }
            }
        }

        //插入修改publish_setting表
        if (infoAndSettingEditModel.getApiPublishSettingList() != null) {
            List<APIPublishSettingModel> apiPublishSettingList = infoAndSettingEditModel.getApiPublishSettingList();
            //判断是否为空
            if (!apiPublishSettingList.isEmpty() && apiPublishSettingList.size() > 0) {
                for (APIPublishSettingModel apiPublishSettingModel : apiPublishSettingList) {
                    if (!org.springframework.util.StringUtils.isEmpty(apiPublishSettingModel)) {
                        if (StringUtils.isEmpty(apiPublishSettingModel.getId())&&(!StringUtils.isEmpty(apiPublishSettingModel.getPackageName()))){
                            //循环插入
                            PublishSetting entity4 = new PublishSetting();
                            BeanUtils.copyProperties(apiPublishSettingModel, entity4);
                            entity4.setPublishInfoId(entity1.getId());
                            entity4.setCreatedAt(createdAt);
                            int sqlResult4 = publishSettingMapper.insert(entity4);
                        }else {
                            //循环更新
                            PublishSetting entity5 = new PublishSetting();
                            PublishSettingExample example5 = new PublishSettingExample() ;
                            BeanUtils.copyProperties(apiPublishSettingModel, entity5);
                            PublishSettingExample.Criteria criteria4 = example5.createCriteria() ;
                            criteria4.andIdEqualTo(apiPublishSettingModel.getId()) ;
                            int sqlResult5 = publishSettingMapper.updateByExampleSelective(entity5,example5);
                        }
                    }
                }
            }
        }
        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据更新失败");
        }
        resultState.setData(infoAndSettingEditModel.getPublishInfoId());
        return resultState;
    }

    @Override
    public int isAdminFalg(Long id) {
        return adminRoleMapper.isAdminFalg(id);
    }
}
