package com.kym.service.miniapp.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kym.entity.miniapp.ChargeOrder;
import com.kym.entity.miniapp.Invoice;
import com.kym.entity.miniapp.params.ApplyInvoiceParams;
import com.kym.mapper.miniapp.InvoiceMapper;
import com.kym.service.miniapp.ChargeOrderService;
import com.kym.service.miniapp.InvoiceService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 发票记录表 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2023-09-15
 */
@Service
@DS("db-miniapp")
public class InvoiceServiceImpl extends ServiceImpl<InvoiceMapper, Invoice> implements InvoiceService {

    private final ChargeOrderService chargeOrderService;

    public InvoiceServiceImpl(ChargeOrderService chargeOrderService) {
        this.chargeOrderService = chargeOrderService;
    }

    @Override
    public void applyInvoice(ApplyInvoiceParams params) {
        // orderDetails 获取申请开票的订单
        // TODO: 2023-09-21 校验订单是未开票且为该用户的订单
        var userId = StpUtil.getLoginIdAsLong();
        var orders = chargeOrderService.getChargeOrdersBySeqs(params.getStartChargeSeqs());
        var orderDetails = orders.stream().collect(Collectors.toMap(ChargeOrder::getStartChargeSeq, chargeOrder -> Map.of(
                "totalPower", chargeOrder.getTotalPower(),
                "totalMoney", chargeOrder.getTotalMoney(),
                "elecMoney", chargeOrder.getElecMoney(),
                "serviceMoney", chargeOrder.getServiceMoney()
        )));

        // 组装invoice
        var invoice = new Invoice()
                .setUserId(userId)
                .setOrderDetails(List.of(orderDetails)) // 订单信息
                .setInvoiceAmount(orders.stream().mapToInt(ChargeOrder::getTotalMoney).sum())   // 总金额
                .setElecMoney(orders.stream().mapToInt(ChargeOrder::getElecMoney).sum())    // 电费
                .setElecMoney(orders.stream().mapToInt(ChargeOrder::getServiceMoney).sum())    // 服务费
                .setTotalPower(orders.stream().mapToDouble(ChargeOrder::getTotalPower).sum())   // 总电量
                .setInvoiceType(params.getInvoiceType())    // 类型
                .setInvoiceTitle(params.getInvoiceTitle())  //抬头
                .setTaxId(params.getTaxId())    // 税号
                .setAddress(params.getAddress())    // 公司地址
                .setBankName(params.getBankName())  // 开户银行
                .setBankAccount(params.getBankAccount())  // 银行账户
                .setPhone(params.getPhone())    // 公司电话
                .setRemark(params.getRemark())  // 备注
                .setEmail(params.getEmail());    // 邮箱
        baseMapper.insert(invoice);

    }


}
