package com.lightinit.hsdataportal.impl;

import com.lightinit.hsdataportal.common.GateWayUtils;
import com.lightinit.hsdataportal.common.HttpUtil;
import com.lightinit.hsdataportal.common.OrderNumberUtils;
import com.lightinit.hsdataportal.dictionary.*;
import com.lightinit.hsdataportal.entity.*;
import com.lightinit.hsdataportal.mapper.*;
import com.lightinit.hsdataportal.model.*;
import com.lightinit.hsdataportal.service.IAPIservice;
import com.lightinit.hsdataportal.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.*;

@Service
public class APIServiceImpl implements IAPIservice {

    @Autowired
    private ResourceApiMapper resourceApiMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourceApiInterfaceMapper resourceApiInterfaceMapper;

    @Autowired
    private ResourceApiInterfaceInputMapper interfaceInputMapper;

    @Autowired
    private ResourceApiInterfaceOutputMapper interfaceOutputMapper;

    @Autowired
    private PublishSettingMapper publishSettingMapper;

    @Autowired
    private PublishInfoMapper publishInfoMapper;

    @Autowired
    private ResourceFollowMapper followMapper;

    @Autowired
    private OfflineConferenceMapper offlineConferenceMapper;

    @Autowired
    private ResourceAuthMapper resourceAuthMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private ResourceCatelogMapper resourceCatelogMapper;

    @Autowired
    private ResourceViewTimesMapper viewTimesMapper;

    @Autowired
    private DictionaryGroupMapper dictionaryGroupMapper;

    @Autowired
    private UserMapper userMapper ;

    @Autowired
    private AdminMapper adminMapper ;

    // ---------------open-------------
    @Override
    public List<APIOpenListModel> queryOpenList(APIOpenSearchModel apiOpenSearchModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceApiMapper.queryOpenList(apiOpenSearchModel);
    }

    @Override
    public long queryOpenCount(APIOpenSearchModel apiOpenSearchModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceApiMapper.queryOpenCount(apiOpenSearchModel);
    }

    @Override
    public APIOpenViewModel queryOpenView(Long id, Long settingId, String platformType) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        APIOpenViewModel apiOpenViewModel = new APIOpenViewModel();

        //查询resource 表
        Resource resource = resourceMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(resource, apiOpenViewModel);

        //查询resource_catelog
        FourResourceCatelogModel resourceCatelogModel = resourceCatelogMapper.selectFourClassify(id);
        if (!StringUtils.isEmpty(resourceCatelogModel)) {
            apiOpenViewModel.setFourResourceCatelogModel(resourceCatelogModel);
        }

        //查找resource_view_times
        ResourceViewTimes resourceViewTimes = viewTimesMapper.selectByPrimaryKey(id);
        if (!StringUtils.isEmpty(resourceViewTimes)) {
            apiOpenViewModel.setViewTimes(resourceViewTimes.getViewTimes());
            viewTimesMapper.updateViewTimes(id);
        } else {
            viewTimesMapper.insertViews(id, 1);
        }


        //查询resource_api 表
        ResourceApi resourceApi = resourceApiMapper.selectByPrimaryKey(id);
        apiOpenViewModel.setReturnCode(resourceApi.getReturnCode());
        apiOpenViewModel.setServiceTag(resourceApi.getServiceTag());

        //查询resource_api_interfance 表
        ResourceApiInterfaceExample resourceApiInterfaceExample = new ResourceApiInterfaceExample();
        ResourceApiInterfaceExample.Criteria criteria = resourceApiInterfaceExample.createCriteria();
        criteria.andApiIdEqualTo(id);
        List<ResourceApiInterfaceWithBLOBs> list = resourceApiInterfaceMapper.selectByExampleWithBLOBs(resourceApiInterfaceExample);
        if (list.size() > 0) {
            List<APIOpenInterfaceViewModel> apiOpenInterfaceViewModelList = new ArrayList<>();
            for (ResourceApiInterfaceWithBLOBs resourceApiInterfaceWithBLOBs : list) {
                APIOpenInterfaceViewModel apiOpenInterfaceViewModel = new APIOpenInterfaceViewModel();
                BeanUtils.copyProperties(resourceApiInterfaceWithBLOBs, apiOpenInterfaceViewModel);

                //查询查询resource_api_interfance_input表
                ResourceApiInterfaceInputExample inputExample = new ResourceApiInterfaceInputExample();
                ResourceApiInterfaceInputExample.Criteria criteria1 = inputExample.createCriteria();
                criteria1.andInterfaceIdEqualTo(resourceApiInterfaceWithBLOBs.getId());
                List<ResourceApiInterfaceInput> inputs = interfaceInputMapper.selectByExample(inputExample);
                apiOpenInterfaceViewModel.setInterfaceInputs(inputs);

                //查询查询resource_api_interfance_output表
                ResourceApiInterfaceOutputExample outputExample = new ResourceApiInterfaceOutputExample();
                ResourceApiInterfaceOutputExample.Criteria criteria2 = outputExample.createCriteria();
                criteria2.andInterfaceIdEqualTo(resourceApiInterfaceWithBLOBs.getId());
                List<ResourceApiInterfaceOutput> outputs = interfaceOutputMapper.selectByExample(outputExample);
                apiOpenInterfaceViewModel.setInterfaceOutputs(outputs);

                apiOpenInterfaceViewModelList.add(apiOpenInterfaceViewModel);
            }
            apiOpenViewModel.setInterfaceViewModels(apiOpenInterfaceViewModelList);
        }

        //查询publish_setting表
        PublishSetting publishSetting = publishSettingMapper.selectByPrimaryKey(settingId);
        //查询publish_info 表
        PublishInfoWithBLOBs publishInfo = publishInfoMapper.selectByPrimaryKey(publishSetting.getPublishInfoId());
        //统计resource_follow关注数量
        int followCount = followMapper.selectFollowCount(platformType, settingId);
        apiOpenViewModel.setFollowTotalCount(followCount);
        apiOpenViewModel.setPublishSetting(publishSetting);
        apiOpenViewModel.setAuditedAt(publishInfo.getAuditedAt());
        apiOpenViewModel.setResourceImg(publishInfo.getResourceImg());
        return apiOpenViewModel;
    }

    @Override
    public ResultState follow(Long settingId, Long id, String platformType) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        ResourceFollowExample example = new ResourceFollowExample();
        ResourceFollowExample.Criteria criteria = example.createCriteria();
        criteria.andPublishSettingIdEqualTo(settingId);
        criteria.andFollowerIdEqualTo(id);
        criteria.andPlatformTypeEqualTo(platformType);
        List<ResourceFollow> resourceFollows = followMapper.selectByExample(example);
        int result = 0;
        int result1 = 0;
        if (resourceFollows.size() == 0) {
            ResourceFollow resourceFollow1 = new ResourceFollow();
            resourceFollow1.setPlatformType(platformType);
            resourceFollow1.setFollowerId(id);
            resourceFollow1.setPublishSettingId(settingId);
            resourceFollow1.setCreatedAt(new Date());
            result = followMapper.insert(resourceFollow1);
            resultState.setData(resourceFollow1.getId());
            resultState.setMsg("关注成功");
        } else {
            result1 = followMapper.deleteByExample(example);
            resultState.setMsg("取消关注");
        }
        if (!(result > 0 || result1 > 0)) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("关注失败");
        }
        return resultState;
    }

    @Override
    public ResultState<Long> offlineConference(APIOfflineConferenceModel offlineConferenceModel, Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        OfflineConferenceWithBLOBs offlineConferenceWithBLOBs = new OfflineConferenceWithBLOBs();
        BeanUtils.copyProperties(offlineConferenceModel, offlineConferenceWithBLOBs);
        offlineConferenceWithBLOBs.setUserId(id);
        offlineConferenceWithBLOBs.setOrderNumber(OrderNumberUtils.generate());
        offlineConferenceWithBLOBs.setSubmitTime(new Date());
        offlineConferenceWithBLOBs.setCreatedAt(new Date());
        int result = offlineConferenceMapper.insert(offlineConferenceWithBLOBs);
        if (!(result > 0)) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("点击洽谈失败");
        }
        return resultState;
    }

    public boolean isApply(Long settingId, Long userId, String dicPlatformType, String applyReason) {
        //查询publish_setting
        PublishSetting publishSetting = publishSettingMapper.selectByPrimaryKey(settingId);
        //查询publish_info
        PublishInfoWithBLOBs publishInfoWithBLOBs = publishInfoMapper.selectByPrimaryKey(publishSetting.getPublishInfoId());
        //查询resource
        Resource resource = resourceMapper.selectByPrimaryKey(publishInfoWithBLOBs.getResourceId());
        int i = orderMapper.isOrderGoodsCount(userId, publishSetting.getId(), dicPlatformType);
        if (resource.getOpenType().equals(DicResourceOpenType.UNCONDITIONAL)) {
            if (i > 0) {
                // TODO 判断过期问题，暂时不考虑
//                if (!publishSetting.getExpiriedDate().after(new Date())) {
//                    return false;
//                }
                if (publishSetting.getChargeMethod().equals(DicPublishSettingChargeMethod.BY_TIME)) {
                    Date expiriedDate = orderMapper.isOrderGoodsGuoQiTime(userId, publishSetting.getId(), DicPlatformType.OPEN);
                    if (!expiriedDate.after(new Date())) {
                        return true;
                    }
                }
                return false ;

            }
        }
        if (resource.getOpenType().equals(DicResourceOpenType.NEED_TO_APPLY)) {
            ResourceAuthExample resourceAuthExample = new ResourceAuthExample();
            ResourceAuthExample.Criteria criteria = resourceAuthExample.createCriteria();
            criteria.andPlatformTypeEqualTo(dicPlatformType);
            criteria.andPublishSettingIdEqualTo(publishSetting.getId());
            criteria.andCreatedByEqualTo(userId);
            List<ResourceAuth> resourceAuths = resourceAuthMapper.selectByExample(resourceAuthExample);
            if (resourceAuths.size() > 0) {
                if (resourceAuths.get(0).getAuthState().equals(DicResourceAuthAuditResult.AUTHORIZATION_NO)) {
                    return true;
                }
                if (resourceAuths.get(0).getAuthState().equals(DicResourceAuthAuditResult.AUTHORIZATION_SUCCESS)) {
                    OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
                    OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
                    criteria1.andResourceAuthIdEqualTo(resourceAuths.get(0).getId());
                    List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
                    Order order = orderMapper.selectByPrimaryKey(orderGoods.get(0).getOrderId());
                    if (order.getOrderState().equals(DicOrderState.PAY_WAIT)){
                        return false ;
                    }
//                    Date newDate = new Date();
//                    if ((!publishSetting.getExpiriedDate().after(newDate)) && (!orderGoods.get(0).getExpiriedDate().after(newDate))) {
//                        return false;
//                    }
                    if (publishSetting.getChargeMethod().equals(DicPublishSettingChargeMethod.BY_TIME)) {
                        Date expiriedDate = orderMapper.isOrderGoodsGuoQiTime(userId, publishSetting.getId(), DicPlatformType.OPEN);
                        if (!expiriedDate.after(new Date())) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public ResultState isPay(Long settingId, Long id1, String open) {
        ResultState resultState = new ResultState() ;
        long orderId = orderGoodsMapper.getOrderId(DicResourceType.API,
                settingId,DicPublishSettingChargeMethod.FREE) ;
        if (orderId!=0){
            Order order = orderMapper.selectByPrimaryKey(orderId);
            if (order.getOrderState().equals(DicOrderState.PAY_WAIT)){
                resultState.setData(order.getOrderNumber());
                resultState.setMsg(order.getOrderAmount().toString());
            }else {
                resultState.setStateCode(ResultStateCode.INVALID_DATA);
            }
        }else {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
        }
        return resultState;
    }


    @Override
    @Transactional
    public ResultState<Long> apply(Long settingId, Long followId, String dicPlatformType, String applyReason) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Calendar c = Calendar.getInstance();
        Date creatAt = c.getTime();
        int result = 0;
        int result1 = 0;
        int result2 = 0;
        //查询publish_setting
        PublishSetting publishSetting = publishSettingMapper.selectByPrimaryKey(settingId);
        //查询publish_info
        PublishInfoWithBLOBs publishInfoWithBLOBs = publishInfoMapper.selectByPrimaryKey(publishSetting.getPublishInfoId());
        //查询resource
        Resource resource = resourceMapper.selectByPrimaryKey(publishInfoWithBLOBs.getResourceId());

        //插入resource_auth
        ResourceAuth resourceAuth = new ResourceAuth();
        resourceAuth.setPublishSettingId(settingId);
        resourceAuth.setPublishInfoId(publishInfoWithBLOBs.getId());
        resourceAuth.setApplier(followId);
        resourceAuth.setPlatformType(dicPlatformType);
        resourceAuth.setCreatedAt(creatAt);
        resourceAuth.setCreatedBy(followId);
        resourceAuth.setApplyTime(creatAt);
        resourceAuth.setApplyReason(applyReason);
        //如果是开放平台
        if (dicPlatformType.equals(DicPlatformType.OPEN)) {
            if (resource.getOpenType().equals(DicResourceOpenType.NEED_TO_APPLY)) {
                resourceAuth.setAuthState(DicResourceAuthAuditResult.WAIT_AUTHORIZATION);
            } else {
                resourceAuth.setAuthState(DicResourceAuthAuditResult.AUTHORIZATION_SUCCESS);
            }
        } else {
            //如果是共享平台
            if (resource.getShareType().equals(DicResourceShareType.CONDITIONAL)) {
                resourceAuth.setAuthState(DicResourceAuthAuditResult.WAIT_AUTHORIZATION);
            } else {
                resourceAuth.setAuthState(DicResourceAuthAuditResult.AUTHORIZATION_SUCCESS);
            }
        }

        result = resourceAuthMapper.insert(resourceAuth);
        if (resource.getOpenType().equals(DicResourceOpenType.UNCONDITIONAL) || dicPlatformType.equals(DicPlatformType.SHARE)) {
            //插入order表
            Order order = new Order();
            order.setPlatformType(dicPlatformType);
            order.setUserId(followId);
            order.setOrderTime(creatAt);
            order.setOrderNumber(OrderNumberUtils.generate());
            order.setCreatedBy(followId);
            order.setOrderType(DicOrderType.ONLINEORDER);
            if (publishSetting.getChargeMethod().equals(DicPublishSettingChargeMethod.FREE) || dicPlatformType.equals(DicPlatformType.SHARE)) {
                order.setOrderState(DicOrderState.PAY_SUCCESS);
            } else {
                order.setOrderState(DicOrderState.PAY_WAIT);
            }
            order.setOrderAmount(publishSetting.getPackagePrice());
            order.setRemark(publishSetting.getDescription());
            order.setCreatedAt(creatAt);
            result1 = orderMapper.insert(order);
            //插入order_goods表
            OrderGoods orderGoods = new OrderGoods();
            BeanUtils.copyProperties(publishSetting, orderGoods);
            if (publishSetting.getChargeMethod().equals(DicPublishSettingChargeMethod.BY_TIME)) {
                orderGoods.setEffectiveDate(creatAt);
                c.add(Calendar.MONTH, Math.toIntExact(publishSetting.getPackageMonths()));
                orderGoods.setExpiriedDate(c.getTime());
            }
            if (publishSetting.getChargeMethod().equals(DicPublishSettingChargeMethod.BY_NUMBER_OF_TIMES)) {
                orderGoods.setRestTimes(publishSetting.getUseTimesLimit());
            }
            orderGoods.setOrderId(order.getId());
            orderGoods.setResourceType(DicResourceType.API);
            orderGoods.setResourceName(resource.getResourceName());
            orderGoods.setPublishSettingId(settingId);
            orderGoods.setCreatedAt(creatAt);
            orderGoods.setCreatedBy(followId);
            orderGoods.setResourceAuthId(resourceAuth.getId());
            result2 = orderGoodsMapper.insert(orderGoods);

            //申请成功后，对接新网关接口，鉴权和计费
            //开放平台（无条件开放）
            if (dicPlatformType.equals(DicPlatformType.OPEN)){
                if (resource.getOpenType().equals(DicResourceOpenType.UNCONDITIONAL)) {
                    //1。已授权，免费
                    if (orderGoods.getChargeMethod().equals(DicPublishSettingChargeMethod.FREE)) {
                        if (publishInfoWithBLOBs.getOutId1()!=null){
                            User user = userMapper.selectByPrimaryKey(order.getUserId());
                            // 新增网关授权
                            GateWayUtils.gatewayAuthAdd(publishInfoWithBLOBs.getOutId1(),DicNewGateway.APPLICATIONID,user.getUsername(),user.getUsername()+"添加授权") ;
                            //新增网关计费
                            GateWayUtils.gatewayChargeAdd(publishInfoWithBLOBs.getOutId1(),DicNewGateway.APPLICATIONID,user.getUsername(),
                                    DicPublishSettingChargeMethod.FREE,publishSetting.getUseTimesLimit().toString(),user.getUsername()+"添加计费") ;
                        }
                    }

                } ;
            }
            if (dicPlatformType.equals(DicPlatformType.SHARE)){
                if(resource.getShareType().equals(DicResourceShareType.UNCONDITIONAL)){
                    if (publishInfoWithBLOBs.getOutId1()!=null){
                        Admin user = adminMapper.selectByPrimaryKey(order.getUserId());
                        // 新增网关授权
                        GateWayUtils.gatewayAuthAdd(publishInfoWithBLOBs.getOutId1(),DicNewGateway.APPLICATIONID,user.getUsername(),user.getUsername()+"添加授权") ;
                        //新增网关计费
                        GateWayUtils.gatewayChargeAdd(publishInfoWithBLOBs.getOutId1(),DicNewGateway.APPLICATIONID,user.getUsername(),
                                DicPublishSettingChargeMethod.FREE,publishSetting.getUseTimesLimit().toString(),user.getUsername()+"添加计费") ;
                    }
                }
            }

        }
        if (!(result > 0)) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("申请失败");
        }
        return resultState;
    }

    @Override
    public List<APIServiceTypeModel> getApiServiceTypes(String fuwutype) {
        return dictionaryGroupMapper.getApiServiceTypes(fuwutype);
    }

    @Override
    public int isFollow(Long userId, Long settingId, String platformType) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        //查询resource_follow表
        ResourceFollowExample example = new ResourceFollowExample();
        ResourceFollowExample.Criteria criteria = example.createCriteria();
        criteria.andPublishSettingIdEqualTo(settingId);
        criteria.andFollowerIdEqualTo(userId);
        criteria.andPlatformTypeEqualTo(platformType);
        List<ResourceFollow> resourceFollows = followMapper.selectByExample(example);
        return resourceFollows.size();
    }

    // -----------------------------------


    // ---------------share-------------
    @Override
    public List<APIShareListModel> queryShareList(APIShareSearchModel apiShareSearchModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceApiMapper.queryShareList(apiShareSearchModel);
    }

    @Override
    public long queryShareCount(APIShareSearchModel apiShareSearchModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceApiMapper.queryShareCount(apiShareSearchModel);
    }

    @Override
    public APIShareViewModel queryShareView(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        APIShareViewModel apiShareViewModel = new APIShareViewModel();

        //查询resource 表
        Resource resource = resourceMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(resource, apiShareViewModel);

        //查询resource_api 表
        ResourceApi resourceApi = resourceApiMapper.selectByPrimaryKey(id);
        apiShareViewModel.setReturnCode(resourceApi.getReturnCode());

        //查询resource_api_interfance 表
        ResourceApiInterfaceExample resourceApiInterfaceExample = new ResourceApiInterfaceExample();
        ResourceApiInterfaceExample.Criteria criteria = resourceApiInterfaceExample.createCriteria();
        criteria.andApiIdEqualTo(id);
        List<ResourceApiInterfaceWithBLOBs> list = resourceApiInterfaceMapper.selectByExampleWithBLOBs(resourceApiInterfaceExample);
        if (list.size() > 0) {
            for (ResourceApiInterfaceWithBLOBs resourceApiInterfaceWithBLOBs : list) {
                APIOpenInterfaceViewModel apiOpenInterfaceViewModel = new APIOpenInterfaceViewModel();
                BeanUtils.copyProperties(resourceApiInterfaceWithBLOBs, apiOpenInterfaceViewModel);

                //查询查询resource_api_interfance_input表
                ResourceApiInterfaceInputExample inputExample = new ResourceApiInterfaceInputExample();
                ResourceApiInterfaceInputExample.Criteria criteria1 = inputExample.createCriteria();
                criteria1.andInterfaceIdEqualTo(resourceApiInterfaceWithBLOBs.getId());
                List<ResourceApiInterfaceInput> inputs = interfaceInputMapper.selectByExample(inputExample);
                apiOpenInterfaceViewModel.setInterfaceInputs(inputs);

                //查询查询resource_api_interfance_output表
                ResourceApiInterfaceOutputExample outputExample = new ResourceApiInterfaceOutputExample();
                ResourceApiInterfaceOutputExample.Criteria criteria2 = outputExample.createCriteria();
                criteria2.andInterfaceIdEqualTo(resourceApiInterfaceWithBLOBs.getId());
                List<ResourceApiInterfaceOutput> outputs = interfaceOutputMapper.selectByExample(outputExample);
                apiOpenInterfaceViewModel.setInterfaceOutputs(outputs);

                apiShareViewModel.getInterfaceViewModels().add(apiOpenInterfaceViewModel);
            }
        }
        return apiShareViewModel;
    }
}
