package com.lightinit.hsdataplatformresdir.impl.admin;

import com.google.gson.internal.LinkedTreeMap;
import com.lightinit.hsdataplatformresdir.common.GateWayUtils;
import com.lightinit.hsdataplatformresdir.common.HttpUtil;
import com.lightinit.hsdataplatformresdir.common.OrderNumberUtils;
import com.lightinit.hsdataplatformresdir.common.TokenUntils;
import com.lightinit.hsdataplatformresdir.dictionary.*;
import com.lightinit.hsdataplatformresdir.entity.*;
import com.lightinit.hsdataplatformresdir.mapper.*;
import com.lightinit.hsdataplatformresdir.model.ResultState;
import com.lightinit.hsdataplatformresdir.model.ResultStateCode;
import com.lightinit.hsdataplatformresdir.model.admin.AuthorizationHeableModel;
import com.lightinit.hsdataplatformresdir.model.admin.AuthorizationListModel;
import com.lightinit.hsdataplatformresdir.model.admin.AuthorizationSearchModel;
import com.lightinit.hsdataplatformresdir.model.admin.AuthorizationViewModel;
import com.lightinit.hsdataplatformresdir.service.admin.IAuthorizationService;
import com.lightinit.hsdataplatformresdir.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 java.util.*;

@Service
public class AuthorizationServiceImpl implements IAuthorizationService {

    @Autowired
    private ResourceAuthMapper resourceAuthMapper ;

    @Autowired
    private PublishSettingMapper publishSettingMapper ;

    @Autowired
    private OrderMapper orderMapper ;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper ;

    @Autowired
    private AdminRoleMapper adminRoleMapper ;

    @Autowired
    private UserAuthSettingMapper userAuthSettingMapper ;

    @Autowired
    private UserMapper userMapper ;

    @Autowired
    private AdminMapper adminMapper ;

    @Autowired
    private PublishInfoMapper publishInfoMapper ;

    @Override
    public List<AuthorizationListModel> queryList(AuthorizationSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceAuthMapper.queryList(inputModel);
    }

    @Override
    public long queryCount(AuthorizationSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceAuthMapper.queryCount(inputModel);
    }

    @Override
    public AuthorizationViewModel queryOneView(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return resourceAuthMapper.queryOneView(id);
    }

    @Override
    @Transactional
    public ResultState<Long> handle(AuthorizationHeableModel inputModel,Long followId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Date createdAt = new Date();

        //修改resource_auth表
        ResourceAuth resourceAuth = new ResourceAuth() ;
        resourceAuth.setAuditOpinion(inputModel.getAuditOpinion());
        resourceAuth.setAuthState(inputModel.getAuthorizationState());
        ResourceAuthExample example = new ResourceAuthExample() ;
        ResourceAuthExample.Criteria criteria = example.createCriteria() ;
        criteria.andIdEqualTo(inputModel.getId()) ;
        int result0 = resourceAuthMapper.updateByExampleSelective(resourceAuth,example) ;
        int result1 = 0;int result2 = 0 ;
        if (inputModel.getAuthorizationState().equals(DicAuthorizationState.AUTHORIZE_OK)){
            PublishSetting publishSetting = publishSettingMapper.selectByPrimaryKey(inputModel.getPublishSettingId()) ;

            //插入order表
            Order order = new Order() ;
            order.setPlatformType(inputModel.getPlatfromType());
            order.setUserId(followId) ;
            order.setOrderTime(createdAt) ;
            order.setOrderNumber(OrderNumberUtils.generate());
            if (inputModel.getPlatfromType().equals(DicOrderTypeState.OFFLINE)){
                order.setOrderState(DicOrderState.PAID);
            }else {
                if (publishSetting.getChargeMethod().equals(DicPublishSettingChargeMethod.FREE)){
                    order.setOrderState(DicOrderState.PAID);
                }else {
                    order.setOrderState(DicOrderState.NOTPAID);
                }
            }
            order.setOrderAmount(publishSetting.getPackagePrice());
            order.setRemark(publishSetting.getDescription());
            order.setCreatedAt(createdAt);
            result1 = orderMapper.insert(order) ;
            //插入order_goods表
            OrderGoods orderGoods = new OrderGoods() ;
            BeanUtils.copyProperties(publishSetting,orderGoods);
            orderGoods.setOrderId(order.getId());
            orderGoods.setResourceType(inputModel.getResourceType()) ;
            orderGoods.setResourceName(inputModel.getResourceName());
            orderGoods.setPublishSettingId(inputModel.getPublishSettingId());
            orderGoods.setCreatedAt(createdAt);
            orderGoods.setResourceAuthId(inputModel.getId());
            result2 = orderGoodsMapper.insert(orderGoods) ;
            if (result1>0&&result2>0){
                //=================新路由鉴权和计费==================
                if (order.getOrderState().equals(DicOrderState.PAID)&&orderGoods.getResourceType().equals(DicResourceType.API)){
                    String userName = null ;
                    if (order.getPlatformType().equals(DicPlatformType.OPEN)){
                        userName = userMapper.selectByPrimaryKey(order.getUserId()).getUsername() ;
                    }else {
                        userName = adminMapper.selectByPrimaryKey(order.getUserId()).getUsername() ;
                    }
                    PublishInfoWithBLOBs publishInfoWithBLOBs = publishInfoMapper.selectByPrimaryKey(publishSetting.getPublishInfoId());
                    // 新增网关授权
                    GateWayUtils.gatewayAuthAdd(publishInfoWithBLOBs.getOutId1(),DicNewGateway.APPLICATIONID,userName,userName+"添加授权") ;
                    //新增网关计费
                    GateWayUtils.gatewayChargeAdd(publishInfoWithBLOBs.getOutId1(),DicNewGateway.APPLICATIONID,userName,
                            DicPublishSettingChargeMethod.FREE,publishSetting.getUseTimesLimit().toString(),userName+"添加计费") ;
                }
            }
        }


        if (!(result0>0||(result1>0&&result2>0))){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("授权失败");
        }else {

            //=====================================================
            //授权权限
            UserAuthSettingExample example1 = new UserAuthSettingExample() ;
            UserAuthSettingExample.Criteria criteria1 = example1.createCriteria() ;
            criteria1.andUserIdEqualTo((long) 60) ;
            List<UserAuthSetting> userAuthSettings = userAuthSettingMapper.selectByExample(example1);
            if (userAuthSettings.size()>0){
                UserAuthSetting userAuthSetting = userAuthSettings.get(0);
                String authKey = userAuthSetting.getAuthKey() ;
                Map<String,Object> params = new HashMap<>() ;
                params.put("Authorization","Bearer "+TokenUntils.getToken()) ;
                String str1 = null;
                try {
                    str1 = HttpUtil.httpGet2(DicPaasApi.EDITUSER+authKey, "Bearer "+TokenUntils.getToken(),null );
                    Map<String,Object> map1= HttpUtil.strToMap(str1) ;
                    if ((boolean)map1.get("success")){
                        LinkedTreeMap linkedTreeMap = (LinkedTreeMap) map1.get("data");
                        //角色列表
                        Double id = (Double) linkedTreeMap.get("id");
                        int newId = id.intValue() ;
                        String userName = (String) linkedTreeMap.get("username");
                        ArrayList<Map<String,Object>> arrayList = (ArrayList<Map<String, Object>>) linkedTreeMap.get("roles");
                        if (arrayList.size()>0){
                            Map<String, Object> map3 = arrayList.get(0);
                            //权限列表
                            List<Map<String,Object>> list2 = (List<Map<String, Object>>) map3.get("authorities");
                            Map<String,Object> map4 = new HashMap<>() ;
//                            map4.put("id",inputModel.getOutId1()) ;
                            map4.put("id",43) ;
                            list2.add(map4) ;
                            Map<String,Object> map5 = new HashMap<>() ;
                            //更新角色
                            Map<String, String> head = TokenUntils.getHead();
                            head.put("Content-Type","application/json") ;
                            map3.put("authorities",list2) ;
                            Double id2 = (Double) map3.get("id");
                            String str3 = HttpUtil.httpPut(DicPaasApi.UPDATAROLES+id2.intValue(), head ,map3) ;
                            Map<String,Object> map10= HttpUtil.strToMap(str3) ;
                            if ((boolean)map10.get("success")){
                                arrayList.set(0,map3) ;
                                linkedTreeMap.put("roles",arrayList) ;
                                linkedTreeMap.remove("permissions") ;
                                linkedTreeMap.remove("authorities") ;
                                String str2 = HttpUtil.httpPut(DicPaasApi.UPDATEUSER+newId, head ,linkedTreeMap) ;
                            }
                        }else {
                            //新建一个角色
                            Map<String,Object> map8 = new HashMap<>() ;
                            map8.put("name",userName) ;
                            map8.put("value",userName) ;
                            List<Map<String,Object>> list3 = new ArrayList<>() ;
                            Map<String,Object> map9 = new HashMap<>() ;
                            map9.put("id",inputModel.getOutId1()) ;
                            list3.add(map9) ;
                            map8.put("authorities",list3) ;
                            Map<String, String> head = TokenUntils.getHead();
                            head.put("Content-Type","application/json") ;
                            String str2 = HttpUtil.httpPost(DicPaasApi.ADDROLES, head ,map8) ;
                            Map<String,Object> map7= HttpUtil.strToMap(str2) ;
                            if ((boolean)map7.get("success")){
                                LinkedTreeMap linkedTreeMap1 = (LinkedTreeMap) map7.get("data");
                                Double id3 = (Double) linkedTreeMap1.get("id");
                                int newId3 = id3.intValue() ;
                                List<Map<String,Object>> list4 = new ArrayList<>() ;
                                Map<String,Object> map11 = new HashMap<>() ;
                                map11.put("id",newId3) ;
                                list4.add(map11) ;
                                linkedTreeMap.put("roles",list4) ;
                                linkedTreeMap.remove("permissions") ;
                                linkedTreeMap.remove("authorities") ;
                                String str3 = HttpUtil.httpPut(DicPaasApi.UPDATEUSER+newId, head ,linkedTreeMap) ;
                            }
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            //=====================================================
        }
        return resultState ;
    }

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