package com.kym.service.admin.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.kym.common.utils.CommUtil;
import com.kym.entity.admin.InvoiceDetail;
import com.kym.entity.admin.queryParams.InvoiceDetailQueryParam;
import com.kym.entity.common.PageBean;
import com.kym.entity.miniapp.Invoice;
import com.kym.entity.wechat.FapiaoApplications;
import com.kym.mapper.admin.InvoiceDetailMapper;
import com.kym.service.admin.InvoiceDetailService;
import com.kym.service.miniapp.DataDictService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 发票详情表 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2024-03-19
 */
@Service
public class InvoiceDetailServiceImpl extends MPJBaseServiceImpl<InvoiceDetailMapper, InvoiceDetail> implements InvoiceDetailService {

    private final DataDictService dataDictService;

    public InvoiceDetailServiceImpl(DataDictService dataDictService) {
        this.dataDictService = dataDictService;
    }


    @Override
    public PageBean<InvoiceDetail> listInvoiceDetail(InvoiceDetailQueryParam params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        var res = lambdaQuery()
                .eq(CommUtil.isNotEmptyAndNull(params.getApplyId()), InvoiceDetail::getApplyId, params.getApplyId())
                .orderByDesc(InvoiceDetail::getFapiaoTime)
                .list();
        return new PageBean<>(res);
    }

    @Override
    public ExcelWriter exportInvoiceDetail(InvoiceDetailQueryParam params) {
        var invoiceDetailList = lambdaQuery()
                .eq(CommUtil.isNotEmptyAndNull(params.getApplyId()), InvoiceDetail::getApplyId, params.getApplyId())
                .orderByDesc(InvoiceDetail::getFapiaoTime)
                .list();
        ExcelWriter writer = ExcelUtil.getWriter();

        // excel 行信息
        List<Map<String, Object>> rows = new ArrayList<>();

        // 单张发票若发票行有多行，则每项单独一行
        invoiceDetailList.forEach(invoiceDetail -> {
            var items = JSON.parseArray(JSON.toJSONString(invoiceDetail.getItems()), FapiaoApplications.FapiaoItem.class);
            items.forEach(item -> {
                var row = new HashMap<String, Object>();
                // 发票基本信息
                row.put("blue_fapiao.fapiao_time", invoiceDetail.getFapiaoTime());
                row.put("blue_fapiao.fapiao_code", invoiceDetail.getBlueFapiao().getFapiao_code());
                row.put("blue_fapiao.fapiao_number", invoiceDetail.getBlueFapiao().getFapiao_number());
                row.put("buyer_information.type", Invoice.TYPE_企业.equals(invoiceDetail.getBuyerInformation().getType()) ? "企业" : "个人");
                row.put("buyer_information.name", invoiceDetail.getBuyerInformation().getName());
                row.put("buyer_information.taxpayer_id", invoiceDetail.getBuyerInformation().getTaxpayer_id());
                row.put("fapiao_information.status", "否"); // invoiceDetail.getStatus()

                row.putAll(Map.of(
                        "goods_name", item.getGoods_name(),
//             "specification",item.getSpecification(),
//             "unit",item.getUnit(),
                        "quantity", item.getQuantity() / 100000000,
                        "amount", NumberUtil.decimalFormat("#.##", item.getAmount() / 100f),
                        "tax_amount", NumberUtil.decimalFormat("#.##", item.getTax_amount() / 100f),
                        "tax_rate", NumberUtil.decimalFormat("#.##", item.getTax_rate() / 10000f)
                ));

                rows.add(row);
            });
        });

        writer.addHeaderAlias("blue_fapiao.fapiao_code", "发票代码");
        writer.addHeaderAlias("blue_fapiao.fapiao_number", "发票号码");
        writer.addHeaderAlias("blue_fapiao.fapiao_time", "开票日期");
        writer.addHeaderAlias("goods_name", "货物、应税劳务及服务");
        writer.addHeaderAlias("specification", "规格型号");
        writer.addHeaderAlias("quantity", "数量");
        writer.addHeaderAlias("unit", "单位");
        writer.addHeaderAlias("amount", "金额");
        writer.addHeaderAlias("tax_rate", "税率");
        writer.addHeaderAlias("tax_amount", "税额");
        writer.addHeaderAlias("fapiao_information.status", "是否作废");
        writer.addHeaderAlias("buyer_information.type", "购买方类型");
        writer.addHeaderAlias("buyer_information.name", "购方单位名称");
        writer.addHeaderAlias("buyer_information.taxpayer_id", "购方识别号");

        writer.write(rows, true);

        return writer;

    }
}
