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.jwipc.dto.ExportDataDTO;
import com.jwipc.exception.DaoException;
import com.jwipc.finance.dto.ReceiveVoucherDTO;
import com.jwipc.finance.logic.ReceiptVoucherLogic;
import com.jwipc.finance.model.query.CreateInvoicedApplyQuery;
import com.jwipc.finance.model.query.DeductionQuery;
import com.jwipc.finance.model.query.ReceiveVoucherQuery;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.page.PageView;
import com.jwipc.prop.SysProp;
import com.jwipc.security.LoginUtil;
import com.jwipc.util.EasyExcelImportUtils;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

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

/**
 * <p>
 *     入库凭证查询 前台控制器
 * </p>
 *
 * @author shenyang.ou
 * @version 1.0
 * @since 2024/03/04
 */
@RestController
@RequestMapping(MODULE_ROOT + "/receipt/voucher/rest")
@RequiredArgsConstructor
public class ReceiptVoucherRestController {

    private final ReceiptVoucherLogic receiptVoucherLogic;
    private final SysProp sysProp;

    /**
     * 列表
     *
     * @param query
     * @return
     */
    @AuditLogInter(value = "查询列表", module = "入库凭证查询")
    @RequestMapping("/list")
    public PageView list(ReceiveVoucherQuery query) {
        if (LoginUtil.isSupplier()){
            query.setSupplierCode(LoginUtil.getSupplierCode());
        }else {
            query.setUserId(LoginUtil.getUserId());
        }
        if(!Objects.isNull(query.getIsAllowAccount())){
           //允许对账
            if(query.getIsAllowAccount() == 1){
                query.setExclusionFlag("1");
            }
        }
        return receiptVoucherLogic.findByPage(query);
    }

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

    /**
     * 价格导出
     * @param queryStr 查询条件
     */
    @PostMapping("/price/export")
    public void priceExport(HttpServletResponse response, String queryStr) throws IOException {
        List<ExportDataDTO> exportDataDTOS = new ArrayList<>();
        //先加载固定字段
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("factoryCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料凭证号").field("mvCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("行号").field("mvItemNo").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("其他折扣").field("deductionRatio").color(IndexedColors.YELLOW.getIndex()).build());
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final List<ReceiveVoucherDTO> exportData = receiptVoucherLogic.listAll(JSON.parseObject(queryStr,ReceiveVoucherQuery.class));
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"物料凭证-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, JSON.toJSONString(exportDataDTOS));
    }

    @RequestMapping("/price/import")
    public ResponseEntity priceImport(@RequestPart("file") MultipartFile file){
        receiptVoucherLogic.priceImport(file);
        return ResponseEntity.ok(true);
    }

    @PostMapping("/updateRatio")
    public ResponseEntity updateRatio(String ids, BigDecimal deductionRatio) {
        final String[] split = ids.split(StrUtil.COMMA);
        final List<String> idList = Arrays.asList(split);
        receiptVoucherLogic.updateRatio(idList,deductionRatio);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/updatePayment")
    public ResponseEntity updatePayment(String ids, String paymentTermCode) {
        final String[] split = ids.split(StrUtil.COMMA);
        final List<String> idList = Arrays.asList(split);
        receiptVoucherLogic.updatePayment(idList,paymentTermCode);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/provide/create/statement")
    public ResponseEntity provideCreateStatement(ReceiveVoucherQuery query){
        query.setIsSupplier(LoginUtil.isSupplier()?1:0);
        return ResponseEntity.ok(receiptVoucherLogic.provideCreateStatement(query));
    }

    @PostMapping("/provide/create/paymentMatching")
    public ResponseEntity provideCreatePaymentMatching(ReceiveVoucherQuery query){
        query.setIsSupplier(LoginUtil.isSupplier()?1:0);
        return ResponseEntity.ok(receiptVoucherLogic.provideCreatePaymentMatching(query));
    }

    @PostMapping("/provide/create/costMatching")
    public ResponseEntity provideCreateCostMatching(ReceiveVoucherQuery query){
        query.setIsSupplier(LoginUtil.isSupplier()?1:0);
        return ResponseEntity.ok(receiptVoucherLogic.provideCreateCostMatching(query));
    }

    @PostMapping("/provide/detail/byPaymentMatchingId")
    public ResponseEntity provideDetailByPaymentMatchingId(Long paymentMatchingId){
        return ResponseEntity.ok(receiptVoucherLogic.provideDetailByPaymentMatchingId(paymentMatchingId));
    }

    @PostMapping("/provide/detail/byCostMatchingId")
    public ResponseEntity provideDetailByCostMatchingId(Long costMatchingId){
        return ResponseEntity.ok(receiptVoucherLogic.provideDetailByCostMatchingId(costMatchingId));
    }

    @PostMapping("/getReturnVoucherRefundAmount")
    public ResponseEntity getReturnVoucherRefundAmount(String supplierCode, String factoryCode){
        return ResponseEntity.ok(receiptVoucherLogic.getReturnVoucherRefundAmount(supplierCode,factoryCode,factoryCode,true));
    }

    /**
     * 提供创建开票申请时获取对账单明细数据导出
     *
     * @param queryStr 查询条件
     * @return 结果
     */
    @PostMapping("/provide/create/statement/export")
    public void provideCreateStatementExport(HttpServletResponse response, String queryStr) throws IOException {
        List<ExportDataDTO> exportDataDTOS = new ArrayList<>();
        //先加载固定字段
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("factoryCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("receiveId").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料凭证号").field("mvCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("行号").field("receiveRowNo").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("其他折扣").field("deductionRatio").color(IndexedColors.YELLOW.getIndex()).build());
        PageView pageView = receiptVoucherLogic.provideCreateStatement(JSON.parseObject(queryStr, ReceiveVoucherQuery.class));
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"对账明细-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", pageView.getRecords(), JSON.toJSONString(exportDataDTOS));
    }

    /**
     * 检查入库凭证是否能保存一张业务单据上
     *
     * @param supplierCode 供应商编码
     * @param rvIds 入库凭证ID
     * @param receiveType 入库凭证类型
     * @return 结果
     */
    @PostMapping("/check/write/off")
    public ResponseEntity checkWriteOff(String supplierCode, String rvIds, Integer receiveType){
        if(StringUtils.isEmpty(rvIds)){
            return ResponseEntity.ok("OK");
        }
        // 待检查的入库凭证ID集合
        final List<Long> rvIdList = JSONArray.parseArray(rvIds, Long.class);
        final String result = receiptVoucherLogic.checkConsultVoucher(rvIdList, supplierCode, receiveType);
        if(StringUtils.isNotEmpty(result)){
            JSONObject error = new JSONObject();
            error.put("code", HttpStatus.INTERNAL_SERVER_ERROR);
            error.put("message", result);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
        return ResponseEntity.ok("OK");
    }
}
