package com.fastbee.rechargecard.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import cn.hutool.core.lang.Console;
import cn.hutool.json.JSONUtil;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.utils.DateUtils;
import com.fastbee.mqttclient.PubMqttClient;
import com.fastbee.rechargecard.domain.NgUserRechargeRecords;
import com.fastbee.rechargecard.domain.UserConsumptionDetails;
import com.fastbee.rechargecard.domain.dto.RechargecardUser;
import com.fastbee.rechargecard.mapper.NgUserRechargeRecordsMapper;
import com.fastbee.rechargecard.mapper.UserConsumptionDetailsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fastbee.rechargecard.mapper.UserRechargeCardsMapper;
import com.fastbee.rechargecard.domain.UserRechargeCards;
import com.fastbee.rechargecard.service.IUserRechargeCardsService;

/**
 * 用户充值卡Service业务层处理
 *
 * @author kerwincui
 * @date 2024-12-17
 */
@Service
public class UserRechargeCardsServiceImpl implements IUserRechargeCardsService
{
    @Autowired
    private PubMqttClient pubMqttClient;

    @Autowired
    private UserRechargeCardsMapper userRechargeCardsMapper;
    @Autowired
    private UserConsumptionDetailsMapper userConsumptionDetailsMapper;
    @Autowired
    private NgUserRechargeRecordsMapper userRechargeRecordsMapper;
    @Override
    public Long test(Long id) {
        return userRechargeCardsMapper.test(id);
    }

    /**
     * 查询用户充值卡
     *
     * @param id 用户充值卡主键
     * @return 用户充值卡
     */
    @Override
    public UserRechargeCards selectUserRechargeCardsById(Long id)
    {
        //return userRechargeCardsMapper.selectUserRechargeCardsById(id);
        //return id;
        System.out.println("selectUserRechargeCardsById");
        UserRechargeCards info=userRechargeCardsMapper.selectUserRechargeCardsById(id);
        return info;
    }

    /**
     * 查询用户充值卡列表
     *
     * @param userRechargeCards 用户充值卡
     * @return 用户充值卡
     */
    @Override
    public List<UserRechargeCards> selectUserRechargeCardsList(UserRechargeCards userRechargeCards)
    {
        return userRechargeCardsMapper.selectUserRechargeCardsList(userRechargeCards);
    }

    /**
     * 新增用户充值卡
     *
     * @param userRechargeCards 用户充值卡
     * @return 结果
     */
    @Override
    public int insertUserRechargeCards(UserRechargeCards userRechargeCards)
    {
        userRechargeCards.setCreateTime(DateUtils.getNowDate());
        return userRechargeCardsMapper.insertUserRechargeCards(userRechargeCards);
    }

    /**
     * 修改用户充值卡
     *
     * @param userRechargeCards 用户充值卡
     * @return 结果
     */
    @Override
    public int updateUserRechargeCards(UserRechargeCards userRechargeCards)
    {
        userRechargeCards.setUpdateTime(DateUtils.getNowDate());
        return userRechargeCardsMapper.updateUserRechargeCards(userRechargeCards);
    }

    /**
     * 微信支付后修改用户充值卡余额以及订单状态
     * @param rechargeCode
     * @return
     */
    @Override
    public int updateUserRechargeWechat(String rechargeCode,BigDecimal payer_total) throws Exception {


        //用户充值记录中订单信息状态更改为已支付
        NgUserRechargeRecords ngUserRechargeRecords=new NgUserRechargeRecords();
        if(rechargeCode==null)
        {
            throw new Exception("订单编号为空");
        }

        if(userRechargeRecordsMapper.selectNgUserRechargeRecordsByRechargeCode(rechargeCode)==null)
        {
            throw new Exception("订单信息不存在");
        }
        ngUserRechargeRecords=userRechargeRecordsMapper.selectNgUserRechargeRecordsByRechargeCode(rechargeCode);//查询订单信息
        if(ngUserRechargeRecords.getStatus().equals(1))
        {
            return 1;
        }
        ngUserRechargeRecords.setStatus(1);//状态更改为已支付
        userRechargeRecordsMapper.updateNgUserRechargeRecords(ngUserRechargeRecords);


        //用户充值卡中的余额更改
        String cardNumber=ngUserRechargeRecords.getCardNumber();//卡号
        BigDecimal balance=ngUserRechargeRecords.getAmount();//充值金额
        if(!cardNumber.isEmpty())
        {
            if(userRechargeCardsMapper.selectUserRechargeCardsByCardNumber(cardNumber)==null)
            {
                throw new Exception("用户信息不存在");
            }
            UserRechargeCards rechargeCards=userRechargeCardsMapper.selectUserRechargeCardsByCardNumber(ngUserRechargeRecords.getCardNumber());
            BigDecimal newBalance = rechargeCards.getBalance().add(balance);
            System.out.println(cardNumber+"的余额从"+rechargeCards.getBalance()+"变成了"+newBalance);
            rechargeCards.setBalance(newBalance);
            userRechargeCardsMapper.updateUserRechargeCards(rechargeCards);
        }else{
            throw new Exception("卡号为空");
        }



        //用户消费明细记录中状态更改为已支付
        /*UserConsumptionDetails userConsumptionDetails=userConsumptionDetailsMapper.selectUserConsumptionDetailsBy();
        userConsumptionDetails.setStatus(0);//更改为已支付
        userConsumptionDetails.setPaymentStatus(2);//账单状态更改为已支付*/

        String areaCode=ngUserRechargeRecords.getAreaCode();
        if(ngUserRechargeRecords.getSerialNumber()==null){
            throw new ServiceException("充值机编码为空！！！");
        }
        //构建主题
        String topic ="hzlink/147/"+ngUserRechargeRecords.getSerialNumber()+"/cmd/down";
        //构建消息
        Map<String,Object> param = new HashMap<>();
        //远程阀控
        param.put("cmd",1000);
        Map<String,Object> data = new HashMap<>();
        data.put("orderNum", ngUserRechargeRecords.getId());//订单号
        data.put("cardNum",Integer.parseInt(cardNumber));//卡号
        data.put("areaCode",Integer.parseInt(areaCode));//区域号
        data.put("investBalance",balance.doubleValue()*100);//充值的金额
        data.put("investWater",100*100);//充值的水量

        param.put("data",data);
        try{
            pubMqttClient.publish(1,true,topic, JSONUtil.toJsonStr(param));
        }catch (Exception e)
        {
            throw new ServiceException("消息发布失败");
        }

//        int i = userRechargeCardsMapper.updateUserRechargeCards(info);
        return 1;
    }

    /**
     * 批量删除用户充值卡
     *
     * @param ids 需要删除的用户充值卡主键
     * @return 结果
     */
    @Override
    public int deleteUserRechargeCardsByIds(Long[] ids)
    {
        return userRechargeCardsMapper.deleteUserRechargeCardsByIds(ids);
    }

    /**
     * 删除用户充值卡信息
     *
     * @param id 用户充值卡主键
     * @return 结果
     */
    @Override
    public int deleteUserRechargeCardsById(Long id)
    {
        return userRechargeCardsMapper.deleteUserRechargeCardsById(id);
    }
    /**
     * 用户充值卡信息
     *
     * @return 结果
     */
    @Override
    public int updateUserRecharge(RechargecardUser rechargecardUser){

        // 根据id查询用户充值卡信息
        UserRechargeCards info = userRechargeCardsMapper.selectUserRechargeCardsByCardnumber(String.valueOf(rechargecardUser.getCardnumber()));
        if (info == null) {
            // 如果没有找到对应的记录，返回0或者一个错误码
            throw  new ServiceException("卡号不存在！");
        }

        UserConsumptionDetails userConsumptionDetails=new UserConsumptionDetails();
        userConsumptionDetails.setUserId(info.getUserId());
        userConsumptionDetails.setCardNumber(info.getCardNumber());
        userConsumptionDetails.setCardNumber(String.valueOf(rechargecardUser.getCardnumber()));
        userConsumptionDetails.setBillingType(0);
        userConsumptionDetails.setAmountDue(rechargecardUser.getAmount());
        userConsumptionDetails.setBillingDate(DateUtils.getNowDate());
        userConsumptionDetails.setPaymentStatus(2);
        userConsumptionDetails.setPaymentMethod(rechargecardUser.getType());
        userConsumptionDetails.setPaymentTime(DateUtils.getNowDate());
        userConsumptionDetails.setStatus(0);
        userConsumptionDetails.setAreaCode(String.valueOf(rechargecardUser.getAreacode()));
        userConsumptionDetails.setCreateTime(DateUtils.getNowDate());
        /*UserConsumptionDetails userConsumptionDetails = UserConsumptionDetails.builder()
                .userId(info.getUserId())
                .cardNumber(info.getCardNumber())
                .billingType(0)
                .amountDue(rechargecardUser.getNumber())
                .billingDate(DateUtils.getNowDate()) // 获取当前日期
                .paymentStatus(2)
                .paymentMethod(rechargecardUser.getStatus())
                .paymentTime(DateUtils.getNowDate()) // 获取当前日期
                .status(0)
                .areaCode(rechargecardUser.getAreacode()) // 假设 getAreacode() 方法返回区域代码
                .build();*/
        NgUserRechargeRecords ngUserRechargeRecords=new NgUserRechargeRecords();
        ngUserRechargeRecords.setUserId(info.getUserId());
        ngUserRechargeRecords.setUserName(info.getUserName());
        ngUserRechargeRecords.setCardNumber(info.getCardNumber());
        ngUserRechargeRecords.setCardNumber(String.valueOf(rechargecardUser.getCardnumber()));
        ngUserRechargeRecords.setAreaCode(String.valueOf(rechargecardUser.getAreacode()));
        ngUserRechargeRecords.setType(rechargecardUser.getType());
        ngUserRechargeRecords.setAmount(rechargecardUser.getAmount());
        ngUserRechargeRecords.setBalance(info.getBalance());
        ngUserRechargeRecords.setBalance(rechargecardUser.getAmount());
        ngUserRechargeRecords.setRechargeTime(DateUtils.getNowDate());
        ngUserRechargeRecords.setStatus(0);
        ngUserRechargeRecords.setAreaCode(String.valueOf(rechargecardUser.getAreacode()));
        ngUserRechargeRecords.setSerialNumber(rechargecardUser.getDeviceNumber());
        // 计算新的余额
        BigDecimal newBalance = rechargecardUser.getAmount().add(info.getBalance());

       /* userConsumptionDetails.setCreateTime(DateUtils.getNowDate());
        NgUserRechargeRecords ngUserRechargeRecords = NgUserRechargeRecords.builder()
                .userId(info.getUserId()).userName(info.getUserName())
                .cardNumber(info.getCardNumber()).areaCode(rechargecardUser.getAreacode())
                .type(rechargecardUser.getStatus()).amount(rechargecardUser.getNumber())
                .balance(info.getBalance()).rechargeTime(DateUtils.getNowDate())
                .rechargeCode(null).status(0).serialNumber(null).deviceNumber(null).projectId(null)
                .deptId(null)
                .areaCode(rechargecardUser.getAreacode())
                .build();*/
        userRechargeRecordsMapper.insertNgUserRechargeRecords(ngUserRechargeRecords);
        userConsumptionDetailsMapper.insertUserConsumptionDetails(userConsumptionDetails);
        // 更新用户充值卡信息，包括新的余额
        info.setBalance(newBalance);
        info.setUpdateTime(DateUtils.getNowDate());
        info.setAreaCode(String.valueOf(rechargecardUser.getAreacode()));

        //构建主题
        String topic ="hzlink/147/"+rechargecardUser.getDeviceNumber()+"/cmd/down";
        //构建消息
        Map<String,Object> param = new HashMap<>();
        //远程阀控
        param.put("cmd",1000);
        Map<String,Object> data = new HashMap<>();
        data.put("orderNum", ngUserRechargeRecords.getId());
        data.put("cardNum",rechargecardUser.getCardnumber());
        data.put("areaCode",rechargecardUser.getAreacode());
        data.put("investBalance",rechargecardUser.getAmount().doubleValue()*100);
        data.put("investWater",rechargecardUser.getWater()*100);

        param.put("data",data);
        pubMqttClient.publish(1,true,topic, JSONUtil.toJsonStr(param));
        int i = userRechargeCardsMapper.updateUserRechargeCards(info);
        return 1;
    }
}
