package com.kxs.product.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.constant.CommonConstants;
import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.constant.enums.MachineTypeEnum;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.core.util.AssertUtil;
import com.kxs.common.core.util.R;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.product.api.dto.kxsapp.merchant.MachineRatioDTO;
import com.kxs.product.api.dto.kxsapp.merchant.MerchantListDTO;
import com.kxs.product.api.dto.kxsapp.merchant.ToMerchantMakerDTO;
import com.kxs.product.api.model.KxsBrand;
import com.kxs.product.api.model.KxsMachine;
import com.kxs.product.api.model.KxsMachineRatio;
import com.kxs.product.api.model.KxsMerchant;
import com.kxs.product.api.req.kxs.FeeSetReq;
import com.kxs.product.api.vo.kxsapp.merchant.MerchantDetailVO;
import com.kxs.product.biz.mapper.KxsBrandMapper;
import com.kxs.product.biz.mapper.KxsMachineMapper;
import com.kxs.product.biz.mapper.KxsMachineRatioMapper;
import com.kxs.product.biz.mapper.KxsMerchantMapper;
import com.kxs.product.biz.service.KxsMerchantService;
import com.kxs.system.api.feign.RemoteOldService;
import com.kxs.user.api.feign.RemoteKxsUserService;
import com.kxs.user.api.model.KxsUser;
import com.kxs.user.api.model.KxsUserReal;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 客小爽商户表(KxsMerchant)表服务实现类
 *
 * @author 系统
 * @since 2023-12-20 10:09:35
 */
@Service("kxsMerchantService")
@RequiredArgsConstructor
public class KxsMerchantServiceImpl extends ServiceImpl<KxsMerchantMapper, KxsMerchant> implements KxsMerchantService {
    private final KxsMachineMapper kxsMachineMapper;
    private final KxsBrandMapper kxsBrandMapper;
    private final RemoteKxsUserService remoteKxsUserService;
    private final KxsMerchantMapper kxsMerchantMapper;
    private final KxsMachineRatioMapper kxsMachineRatioMapper;
    private final RemoteOldService remoteOldService;



    @Override
    public Object merchantList(Page<KxsMerchant> page, MerchantListDTO param) {
        Long userId = SecurityUtils.getUser().getId();
        param.setUserId(userId);

        if (param.getAmountSection() != null){
            AssertUtil.isIntervalVariableAmount(param.getAmountSection());
        }
        //查询本月交易额
        String month = LocalDateTimeUtil.format(LocalDate.now(), DatePattern.SIMPLE_MONTH_PATTERN);
        param.setTradeMonth(month);
        return kxsMerchantMapper.merchantList(page, param, CommonConstants.MCH_TABLE_PREFIX + month);
    }

    @Override
    public Object merchantDetail(Long merchantId) {
        MerchantDetailVO merchantDetailVO = new MerchantDetailVO();
        //商户信息
        KxsMerchant mchInfo = getById(merchantId);
        BeanUtil.copyProperties(mchInfo,merchantDetailVO);
        //机具信息
        KxsMachine kxsMachine = kxsMachineMapper.selectById(mchInfo.getMachineId());
        merchantDetailVO.setPosSn(kxsMachine.getPosSn());
        merchantDetailVO.setBrand(kxsMachine.getBrandId().toString());
        merchantDetailVO.setActTime(kxsMachine.getActTime().toString());
        merchantDetailVO.setIsAct(kxsMachine.getIsAct());
        KxsBrand brand = kxsBrandMapper.selectById(kxsMachine.getBrandId());
        merchantDetailVO.setBrandName(brand.getName());
        //查询调费调升记录
        KxsMachineRatio upFee = kxsMachineRatioMapper.selectOne(Wrappers.<KxsMachineRatio>lambdaQuery()
                .eq(KxsMachineRatio::getMachineId, kxsMachine.getId())
                .eq(KxsMachineRatio::getMerchantId, merchantId)
                .eq(KxsMachineRatio::getVersion, 1)
                .orderByDesc(KxsMachineRatio::getCreateTime).last("limit 1"));
        //查询调费调降记录
        KxsMachineRatio downFee = kxsMachineRatioMapper.selectOne(Wrappers.<KxsMachineRatio>lambdaQuery()
                .eq(KxsMachineRatio::getMachineId, kxsMachine.getId())
                .eq(KxsMachineRatio::getMerchantId, merchantId)
                .eq(KxsMachineRatio::getVersion, 0)
                .orderByDesc(KxsMachineRatio::getCreateTime).last("limit 1"));

        merchantDetailVO.setUpFeeDate(upFee != null ? upFee.getCreateTime() : null);
        merchantDetailVO.setDownFeeDate(downFee != null ? downFee.getCreateTime() : null);
        merchantDetailVO.setUpFeeFlag(kxsMachine.getUpFeeFlag());
        merchantDetailVO.setDownFeeFlag(kxsMachine.getDownFeeFlag());
        merchantDetailVO.setMachineFee(kxsMachine.getMachineRatio());

        if(kxsMachine.getMachineRatio().compareTo(CommonConstants.FEE_63) == 0){
            merchantDetailVO.setIsChangeFee(1);
        }
        //如果在审核中则不可调
        if (downFee != null &&downFee.getStatus() == 0) {
            merchantDetailVO.setIsChangeFee(0);
        }

        if (kxsMachine.getBrandId() == 12 || kxsMachine.getBrandId() == 13 || kxsMachine.getBrandId() == 15)
        {
            if (kxsMachine.getUpFeeFlag() == 1 && kxsMachine.getDownFeeFlag() == 0)
            {
                merchantDetailVO.setMchStatus("稳定期A");
            }
            else if (kxsMachine.getDownFeeFlag() == 1)
            {
                if(kxsMachine.getMachineRatio().compareTo(new BigDecimal("0.6")) == 0)
                {
                    merchantDetailVO.setMchStatus("稳定期B");
                }
                        else
                {
                    merchantDetailVO.setMchStatus( "稳定期A");
                }
            }
            else
            {
                merchantDetailVO.setMchStatus("扶持期");
            }
        }
        else if (kxsMachine.getBrandId() == 14) //广电卡
        {
            if (kxsMachine.getBindTime().plusDays(CommonConstants.BIND_DAY_NUM).isAfter(LocalDateTime.now()))
            {
                merchantDetailVO.setMchStatus("扶持期");
            }
            else
            {
                merchantDetailVO.setMchStatus("稳定期");
            }
        }
        else
        {
            if (kxsMachine.getBindTime().plusDays(CommonConstants.BIND_DAY_NUM).isAfter(LocalDateTime.now()) && kxsMachine.getIsFirst() == 1 && kxsMachine.getCashPledge().compareTo(BigDecimal.ZERO) > 0)
            {
                merchantDetailVO.setMchStatus("扶持期");
            }
            else if (kxsMachine.getDownFeeFlag() == 1)
            {
                if (kxsMachine.getMachineRatio().compareTo(new BigDecimal("0.6")) == 0 )
                {
                    merchantDetailVO.setMchStatus("稳定期B");
                }
                        else if (kxsMachine.getMachineRatio().compareTo(new BigDecimal("0.63")) == 0 )
                {
                    merchantDetailVO.setMchStatus("稳定期A");
                }
                        else
                {
                    merchantDetailVO.setMchStatus("稳定期");
                }
            }
            else
            {
                merchantDetailVO.setMchStatus("稳定期");
            }
        }

        return merchantDetailVO;

    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public R toMerchantMaker(ToMerchantMakerDTO param) {
        Long parenUserId = SecurityUtils.getUser().getId();
        //查询创客
        R<KxsUser> kxsUserR = remoteKxsUserService.loadUserByCode(param.getUserCode(), SecurityConstants.FROM_IN);
        if (kxsUserR.getData() == null){
            return R.failed("用户不存在");
        }
        KxsUser kxsUser = kxsUserR.getData();
        //查询实名信息
        if (kxsUser.getRealStatus() == null || kxsUser.getRealStatus() == 0) {
            return R.failed("用户未实名");
        }
        //查询是否是下级
        String pidPath = kxsUser.getPidPath();
        boolean isParent = pidPath.contains("," + parenUserId + ",");
        if (!isParent) {
            return R.failed("用户不在当前用户系统下");
        }

        //查询机具所属商户
        KxsMachine kxsMachine = kxsMachineMapper.selectOne(Wrappers.<KxsMachine>query().lambda().eq(KxsMachine::getPosSn,param.getPosSn()));
        //机具所属不一致
        if (!Long.valueOf(kxsMachine.getUserId()).equals(parenUserId)) {
            return R.failed("非法参数:机具非当前用户所有");
        }
        //未激活
        if (!kxsMachine.getIsAct().equals(MachineTypeEnum.ACT.getType())) {
            return R.failed("机具未激活");
        }
        KxsMerchant kxsMerchant = getById(kxsMachine.getMerchantId());
        if (kxsMerchant == null) {
            return R.failed("机具商户不存在");
        }
        //判断机具所属商户和转换的用户数据能否一致 2要素
        //商户实名信息
        String idCard = kxsMerchant.getMerchantCard();
        if (CharSequenceUtil.isEmpty(idCard)) {
            return R.failed("商户未绑定身份信息");
        }
        //判断身份证是否脱敏
        boolean validCard = IdcardUtil.isValidCard(idCard);
        //用户实名信息
        KxsUserReal userReal = remoteKxsUserService.loadUserRealById(kxsUser.getId(), SecurityConstants.FROM_IN).getData();
        if (!validCard) {
            //如果脱敏需要验证前6后4
            String prefix = idCard.substring(0, 4);
            String after = idCard.substring(idCard.length() - 4);
            //
            String realPrefix = userReal.getIdCard().substring(0, 4);
            String realAfter = userReal.getIdCard().substring(userReal.getIdCard().length() - 4);
            if (!prefix.equals(realPrefix) || !after.equalsIgnoreCase(realAfter)) {
                return R.failed("当前商户身份信息与转换用户身份信息不一致,请重新核对后重试");
            }
        } else {
            //未脱敏直接比对
            if (!userReal.getIdCard().equalsIgnoreCase(idCard)) {
                return R.failed("当前商户身份信息与转换用户身份信息不一致,请重新核对后重试");
            }
        }

        if (!userReal.getRealName().equals(kxsMerchant.getMerchantName())) {
            return R.failed("当前商户身份信息与转换用户身份信息不一致,请重新核对后重试");

        }

        //可以转换为商户型创客
        kxsUser.setIsMerchantMaker(CommonConstants.SUCCESS);
        kxsUser.setUpdateTime(LocalDateTime.now());
        remoteKxsUserService.updateById(kxsUser,SecurityConstants.FROM_IN);

        //修改商户类型
        kxsMerchant.setIsMaker(CommonConstants.SUCCESS);
        kxsMerchant.setMakerUserId(kxsUser.getId());
        updateById(kxsMerchant);
        return R.ok();
    }

    @Override
    public Object merchantTotal(Integer brandId) {
        Long id = SecurityUtils.getUser().getId();
        return kxsMerchantMapper.merchantTotal(brandId,id);
    }

    @Override
    public R changeToMchUser(KxsMerchant param) {

        KxsMerchant mchInfo = getById(param.getId());
        if (mchInfo == null) {
            throw new GlobalCustomerException("商户不存在");
        }
        if(mchInfo.getMakerUserId() != null){
            throw new GlobalCustomerException("该商户已是商户型创客");
        }

        //修改商户类型
        mchInfo.setIsMaker(CommonConstants.SUCCESS);
        mchInfo.setMakerUserId(param.getMakerUserId());
        updateById(mchInfo);

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R changeMachineRatio(MachineRatioDTO param) {

        KxsMerchant mchInfo = getById(param.getMerchantId());
        if (mchInfo == null) {
            throw new GlobalCustomerException("商户不存在");
        }
        KxsMachine kxsMachine = kxsMachineMapper.selectById(mchInfo.getMachineId());
        if (kxsMachine == null) {
            throw new GlobalCustomerException("商户机具不存在");
        }

        FeeSetReq req = FeeSetReq.builder()
                .posSn(kxsMachine.getPosSn())
                .brandId(kxsMachine.getBrandId())
                .feeRate(param.getMachineRatio())
                .callBackUrl("")
                .build();
        R res = remoteOldService.feeSet(req);

        if(res.getStatus() != CommonConstants.SUCCESS){
            throw new GlobalCustomerException("修改费率失败");
        }
        kxsMachine.setMachineRatio(param.getMachineRatio());
        kxsMachine.setDownFeeFlag(CommonConstants.SUCCESS);
        //增加费率调整记录
        KxsMachineRatio kxsMachineRatio = new KxsMachineRatio();
        kxsMachineRatio.setMerchantId(mchInfo.getId());
        kxsMachineRatio.setRatio(param.getMachineRatio());
        kxsMachineRatio.setMachineId(kxsMachine.getId());
        kxsMachineRatio.setStatus(CommonConstants.SUCCESS);
        kxsMachineRatio.setBrandId(kxsMachine.getBrandId());
        kxsMachineRatio.setPosUserId(kxsMachine.getUserId());
        kxsMachineRatio.setPosSn(kxsMachine.getPosSn());
        kxsMachineRatio.setUserId(SecurityUtils.getUser().getId().intValue());
        kxsMachineRatio.setResult(JSON.toJSONString(res));
        kxsMachineRatio.setRemark("设置成功");
        kxsMachineRatioMapper.insert(kxsMachineRatio);

        return R.ok();
    }


}

