package com.jwipc.finance.controller.rest;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jwipc.exception.DaoException;
import com.jwipc.finance.dto.CompanyInvoicedReceiptDTO;
import com.jwipc.finance.dto.CompanyInvoicedReceiptImportDTO;
import com.jwipc.finance.logic.CompanyInvoicedReceiptLogic;
import com.jwipc.finance.model.query.InvoicedDetailQuery;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.prop.SysProp;
import com.jwipc.query.BasePageQuery;
import com.jwipc.security.LoginUtil;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.jwipc.finance.constant.ModuleConst.MODULE_ROOT;

/**
 * <p>
 * 对账模块-关联发票明细 前端控制器
 * </p>
 *
 * @author shenyang.ou
 * @since 2024-03-05
 */
@RestController
@RequestMapping(MODULE_ROOT + "/company/invoiced/receipt/rest/")
@RequiredArgsConstructor
public class CompanyInvoicedReceiptRestController {
    private final CompanyInvoicedReceiptLogic companyInvoicedReceiptLogic;
    private final SysProp sysProp;
    /**
     * 获取开票申请单明细数据根据开票申请单ID
     *
     * @return 结果
     */
    @PostMapping("/find/by/apply/id")
    public ResponseEntity findByApplyId(Long iaId) {
        List<CompanyInvoicedReceiptDTO> list = companyInvoicedReceiptLogic.getInvoiceReceiptListByIaId(iaId);
        BasePageQuery basePageQuery = new BasePageQuery();
        basePageQuery.setPage(1);
        basePageQuery.setRows(list.size());
        final Page<CompanyInvoicedReceiptDTO> toPage = PageUtil.toPage(basePageQuery);
        toPage.setRecords(list);
        PageView pageView = PageUtil.getPV(list, toPage.getTotal());
        BigDecimal amountExcludeTax = BigDecimal.ZERO, amount = BigDecimal.ZERO,tax = BigDecimal.ZERO;
        for (CompanyInvoicedReceiptDTO invoice : list) {
            amountExcludeTax = amountExcludeTax.add(invoice.getNoTaxAmount());
            amount = amount.add(invoice.getTaxAmount());
        }
        JSONArray footer = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("noTaxAmount", amountExcludeTax);
        obj.put("taxAmount", amount);
        obj.put("diffTaxMoney", tax);
        footer.add(obj);
        pageView.setFooter(footer);

        return ResponseEntity.ok(pageView);
    }


    /**
     * 查询发票明细单列表

     * @param query 查询条件
     * @return 结果
     */
    @PostMapping("/list")
    public PageView list(InvoicedDetailQuery query) {
        if (LoginUtil.isSupplier()) {
            query.setSupplierCode(LoginUtil.getAccount());
        } else {
            query.setUserId(LoginUtil.getUserId());
        }
        return companyInvoicedReceiptLogic.getInvoiceReceiptListByQuery(query);
    }

    /**
     * Dimension
     * @param exportFiled 导出的列信息
     * @param queryStr 查询条件
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        InvoicedDetailQuery query = JSON.parseObject(queryStr,InvoicedDetailQuery.class);
        if (LoginUtil.isSupplier()) {
            query.setSupplierCode(LoginUtil.getAccount());
        } else {
            query.setUserId(LoginUtil.getUserId());
        }
        //需要单独查询总数
        query.setRows(1);
        query.setPage(1);
        final PageView pageView = companyInvoicedReceiptLogic.getInvoiceReceiptListByQuery(query);
        if (pageView.getTotal() > sysProp.getExportMaxCount()) {
            throw new DaoException(StrUtil.format("导出数据超过{}条", sysProp.getExportMaxCount()));
        }
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final List<CompanyInvoicedReceiptDTO> exportData = companyInvoicedReceiptLogic.listAll(query);
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"发票明细-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, exportFiled);
    }

    /**
     * 导入发票信息
     * @param file 导入文件
     * @return
     */
    @PostMapping("importData")
    public ResponseEntity<List<CompanyInvoicedReceiptImportDTO>> importData(@RequestParam(value = "file") MultipartFile file) {
        List<CompanyInvoicedReceiptImportDTO> companyInvoicedReceiptImportDTOS = companyInvoicedReceiptLogic.importData(file);
        return ResponseEntity.ok(companyInvoicedReceiptImportDTOS);
    }

   /**
   * 更新抵扣状态及备注
   */
    @PostMapping("/updateDeductionStatus")
    public ResponseEntity updateDeductionStatus(String ids, String deductionStatus,String note) {
        final String[] split = ids.split(StrUtil.COMMA);
        final List<String> idList = Arrays.asList(split);
        companyInvoicedReceiptLogic.updateDeductionStatus(idList,deductionStatus,note);
        return ResponseEntity.ok().build();
    }
}
