package cn.iocoder.yudao.module.shop.service.impl;

import cn.iocoder.yudao.module.partner.entity.PartnerBalance;
import cn.iocoder.yudao.module.partner.entity.PartnerBankInfo;
import cn.iocoder.yudao.module.partner.entity.PartnerWorker;
import cn.iocoder.yudao.module.partner.service.IPartnerBalanceService;
import cn.iocoder.yudao.module.partner.service.IPartnerWorkerService;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.WechatPayConfig;
import cn.iocoder.yudao.util.DateUtils;
import cn.iocoder.yudao.module.shop.entity.PartnerDetail;
import cn.iocoder.yudao.module.shop.mapper.PartnerDetailMapper;
import cn.iocoder.yudao.module.shop.service.IPartnerDetailService;
import cn.iocoder.yudao.module.shop.service.IShopMallPartnersService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.profitsharing.model.AddReceiverRequest;
import com.wechat.pay.java.service.profitsharing.model.AddReceiverResponse;
import com.wechat.pay.java.service.profitsharing.model.ReceiverRelationType;
import com.wechat.pay.java.service.profitsharing.model.ReceiverType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ruoyi.partner.service.IPartnerBankInfoService;
import org.springframework.transaction.annotation.Transactional;

import static cn.iocoder.yudao.util.AddressSplitter.splitAddress;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-13
 */
@Service
public class PartnerDetailServiceImpl implements IPartnerDetailService
{
    @Autowired
    private PartnerDetailMapper partnerDetailMapper;
    @Autowired
    private IShopMallPartnersService partnersService;
    @Autowired
    private IPartnerBalanceService partnerBalanceService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    private IPartnerWorkerService workerService;
    @Autowired
    private IPartnerBankInfoService partnerBankInfoService;
    @Resource
    private WechatPayConfig wechatPayConfig;
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public PartnerDetail selectPartnerDetailById(Long id)
    {
        return partnerDetailMapper.selectPartnerDetailById(id);
    }

    @Override
    public PartnerDetail selectPartnerDetailByUserId(Long id,String type)
    {
        return partnerDetailMapper.selectPartnerDetailByUserId(id,type);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param partnerDetail 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public IPage<PartnerDetail> selectPartnerDetailList(Page<PartnerDetail> page, PartnerDetail partnerDetail)
    {
        return partnerDetailMapper.selectPartnerDetailList(page,partnerDetail);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param partnerDetail 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertPartnerDetail(PartnerDetail partnerDetail)
    {
        return partnerDetailMapper.insertPartnerDetail(partnerDetail);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param partnerDetail 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updatePartnerDetail(PartnerDetail partnerDetail)
    {
        partnerDetail.setUpdateTime(DateUtils.getNowDate());
        return partnerDetailMapper.updatePartnerDetail(partnerDetail);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deletePartnerDetailByIds(Long[] ids)
    {
        return partnerDetailMapper.deletePartnerDetailByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deletePartnerDetailById(Long id)
    {
        return partnerDetailMapper.deletePartnerDetailById(id);
    }

    void  receiversAdd(String appId, String merchantId,String privateKey,
                       String merchantSerialNumber,String apiV3Key){
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKey(privateKey)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
        // 构建service
        ProfitsharingService service = new ProfitsharingService.Builder().config(config).build();
        AddReceiverRequest request =new  AddReceiverRequest();
        request.setAppid(appId);
        request.setType(ReceiverType.MERCHANT_ID);
        request.setAccount(wechatPayConfig.getMchId());
        request.setName("成都车友帮网络科技有限公司");
        request.setRelationType(ReceiverRelationType.HEADQUARTER);
        AddReceiverResponse receiverResponse = service.addReceiver(request);
        System.out.println(receiverResponse);


    }

    //审核接口
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int examine(PartnerDetail partnerDetail) throws Exception {
        if (partnerDetail.getStatus().equals("2")){
            //开设店铺
            ShopMallPartners shopMallPartners =new ShopMallPartners();
            shopMallPartners.setUserId(partnerDetail.getUserId());
            shopMallPartners.setType(partnerDetail.getType());
            shopMallPartners.setAverageScore(4.5);
            List<String> strings = splitAddress(partnerDetail.getPosition());
            shopMallPartners.setProvince(strings.get(0));
            shopMallPartners.setCity(strings.get(1));
            shopMallPartners.setArea(strings.get(2));
            shopMallPartners.setIsWorking("0");
            shopMallPartners.setIsBanned("0");
            shopMallPartners.setContactNumber(partnerDetail.getPhone());
            shopMallPartners.setOpenComment("0");
            shopMallPartners.setPartnerName(partnerDetail.getPartnerName());
            partnersService.save(shopMallPartners);
            partnerDetail.setPartnerId(shopMallPartners.getPartnerId());
            //审核通过
            partnerDetailMapper.updatePartnerDetail(partnerDetail);
            AdminUserDO user = userService.getUser(partnerDetail.getUserId());
            Set<Long> role = new HashSet<>();
            role.add(113L);
            permissionService.assignUserRole(user.getId(),role);

            //创建账户
            PartnerBalance partnerBalance =new PartnerBalance();
            partnerBalance.setPartnerId(shopMallPartners.getPartnerId());
            partnerBalance.setTotalRevenue(0L);
            partnerBalance.setAmount(0L);
            partnerBalance.setFrozenAmount(0L);
            partnerBalance.setWithdrawAmount(0L);
            partnerBalanceService.save(partnerBalance);
            //将店主加入员工
            PartnerWorker partnerWorker =new PartnerWorker();
            partnerWorker.setUserId(user.getId());
            partnerWorker.setPartnerId(shopMallPartners.getPartnerId());
            partnerWorker.setAvatar(user.getAvatar());
            partnerWorker.setWorkName(user.getNickname());
            partnerWorker.setWorkPhone(user.getMobile());
            workerService.save(partnerWorker);
            //添加平台为收帐放
            LambdaQueryWrapper<PartnerBankInfo> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(PartnerBankInfo::getPartnerId,shopMallPartners.getPartnerId());
            PartnerBankInfo bankInfo = partnerBankInfoService.getOne(queryWrapper);
            try {
                receiversAdd(wechatPayConfig.getAppId(), bankInfo.getMchId(),bankInfo.getApiclientKey(),
                        bankInfo.getSerialNo(),bankInfo.getApiV3Key());
            }catch (Exception e){
                throw new Exception("商户信息不正确，请联系管理员");
            }

        }else if (partnerDetail.getStatus().equals("3")){
            //拒绝通过
            partnerDetailMapper.updatePartnerDetail(partnerDetail);
        }
        return 0;
    }
}
