package com.chaozhanggui.admin.system.service;

import cn.hutool.core.util.ObjectUtil;
import com.chaozhanggui.common.system.config.RespBody;
import com.chaozhanggui.dao.system.dao.*;
import com.chaozhanggui.dao.system.entity.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SystemApiService {

    @Autowired
    GuserSetMapper guserSetMapper;

    @Autowired
    TbPlussMerchantBaseInfoMapper baseInfoMapper;

    @Autowired
    TbPlussUserAppMapper tbPlussUserAppMapper;

    @Autowired
    TbPlussMerchantStoreMapper tbPlussMerchantStoreMapper;
    public RespBody querySystemApi(String appId,Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<GuserSet> list=guserSetMapper.selectByAppId(appId);
        PageInfo pageInfo=new PageInfo(list);
        return new RespBody("000000",pageInfo);
    }

    public RespBody modifyApi(Integer id,String ip,String publicKey,String privateKey){

        GuserSet guserSet=guserSetMapper.selectByPrimaryKey(id);
        if(ObjectUtil.isEmpty(guserSet)){
            return new RespBody("000034");
        }
        guserSet.setIp(ip);
        guserSet.setPublicKey(publicKey);
        guserSet.setPrivateKey(privateKey);
        guserSet.setUpdateTime(new Date());
        guserSetMapper.updateByPrimaryKeySelective(guserSet);
        return new RespBody("000000");
    }


    public RespBody insertApi(String appId,String ip,String publicKey,String privateKey){
        TbPlussMerchantBaseInfo baseInfo= baseInfoMapper.selectByMerchantcode(appId);
        if(ObjectUtil.isEmpty(baseInfo)){
            return new RespBody("000034");
        }
        TbPlussUserApp userApp= tbPlussUserAppMapper.selectByUserId(baseInfo.getUserid());
        if(ObjectUtil.isEmpty(userApp)){
            return new RespBody("000034");
        }

        TbPlussMerchantStore store=tbPlussMerchantStoreMapper.getStoreByMerchantCode(baseInfo.getMerchantcode());
        if(ObjectUtil.isEmpty(store)){
            return new RespBody("000034");
        }

        GuserSet set=new GuserSet();
        set.setAppId(appId);
        set.setStoreId(store.getId().toString());
        set.setStoreName(store.getStorename());
        set.setStoreCode(store.getStoreid());
        set.setMerchantName(store.getMerchantname());
        set.setToken(userApp.getToken());
        set.setIp(ip);
        set.setPublicKey(publicKey);
        set.setPrivateKey(privateKey);
        set.setCreateTime(new Date());
        guserSetMapper.insert(set);
        return new RespBody("000000");
    }
}
