package com.jwipc.finance.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.jwipc.constant.DictCode;
import com.jwipc.finance.dto.*;
import com.jwipc.finance.entity.CompanyInvoicedApplyPostResult;
import com.jwipc.finance.entity.InvoicedApplyPostResult;
import com.jwipc.finance.logic.*;
import com.jwipc.finance.model.query.CompanyIaApproveQuery;
import com.jwipc.finance.model.query.IaApproveQuery;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.clent.dto.SupplierContactsDTO;
import com.jwipc.supplier.clent.dto.SupplierDTO;
import com.jwipc.supplier.clent.dto.SupplierPurchaseCategoryDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.SequenceClient;
import com.jwipc.sys.client.dto.DictDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

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

/**
 * <p>
 *     对账模块-开票申请 前端控制器
 * </p>
 *
 * @author JT
 * @since 2020-08-12
 */
@Controller
@RequestMapping(MODULE_ROOT + "/company/invoiced/apply")
@RequiredArgsConstructor
public class CompanyInvoicedApplyPageController {
    private final CompanyInvoicedApplyLogic companyInvoicedApplyLogic;
    private final CompanyAccountStatementLogic companyAccountStatementLogic;
//    private final InvoicedApplyDetailLogic invoicedApplyDetailLogic;
    private final CompanyInvoicedApplyApproveLogic invoicedApplyApproveLogic;
    private final CompanyInvoicedApplyPostResultLogic invoicedApplyPostResultLogic;
    private final SupplierClient supplierClient;
    private final DictClient dictClient;
    private final SequenceClient sequenceClient;
    @Value("${sys.kingdee.financial-share.host}")
    private String kingdeeHostUrl;
    @Value("${sys.kingdee.financial-share.socket}")
    private String kingdeeSocketUrl;

    /**
     * 材料开票申请单首页
     *
     * @param model model
     * @return 页面
     */
    @GetMapping("/index")
    public String materialIndex(Model model){
        model.addAttribute("orderType", 1);
        model.addAttribute("supplierCnyFlag",0);
        if(!LoginUtil.isSupplier()){
            model.addAttribute("isSupplier", 0);
        }else {
            model.addAttribute("isSupplier", 1);
            List<SupplierPurchaseCategoryDTO> supplierPurchaseCategoryDTOS = supplierClient.getList(String.valueOf(LoginUtil.getSupplierId()));
            if (CollectionUtil.isNotEmpty(supplierPurchaseCategoryDTOS)){
                model.addAttribute("supplierCnyFlag", "CNY".equals(supplierPurchaseCategoryDTOS.get(0).getCurrencyCode())?1:0);
            }
        }

        return MODULE_ROOT + "/companyInvoicedApply/index";
    }

    /**
     * 采购确认开票申请单首页
     *
     * @param model model
     * @return 页面
     */
    @GetMapping("/purchase/index")
    public String purchaseIndex(Model model){
        model.addAttribute("deptCode", LoginUtil.getDeptCode());
        // 角色类型 1:采购角色 2:财务角色
        model.addAttribute("roleType", 1);
        return MODULE_ROOT + "/companyInvoicedApply/index_purchase";
    }


    /**
     * 财务确认开票申请单首页
     *
     * @param model model
     * @return 页面
     */
    @GetMapping("/finance/index")
    public String index(Model model,String status){
        model.addAttribute("deptCode", LoginUtil.getDeptCode());
        // 角色类型 1:采购角色 2:财务角色
        model.addAttribute("roleType", 2);
        model.addAttribute("status", status);
        return MODULE_ROOT + "/companyInvoicedApply/index_finance";
    }


    @GetMapping("/detail")
    public String detail(Model model, Integer optType, Long id){
        CompanyInvoicedApplyDTO data = new CompanyInvoicedApplyDTO();
        if (id!=null){
            data = companyInvoicedApplyLogic.getById(id);
            CompanyAccountStatementDTO account = companyAccountStatementLogic.getById(data.getAccountStatementId());
            model.addAttribute("account", account);
        }else {
            data.setForeignCurrencyAddFlag(optType==5?1:0);
        }
        model.addAttribute("data", data);
        Pair<String, SupplierPurchaseCategoryDTO> purchaseCategoryDTOPair =  supplierClient.getSupplierPurchaseCategory(data.getSupplierCode(),data.getCompanyCode());
        if (ObjectUtil.isNotEmpty(purchaseCategoryDTOPair.getValue())){
            model.addAttribute("taxCode", purchaseCategoryDTOPair.getValue().getTaxCode());
            model.addAttribute("paymentTermCode", purchaseCategoryDTOPair.getValue().getPaymentTerms());
            model.addAttribute("currencyCode", purchaseCategoryDTOPair.getValue().getCurrencyCode());
            model.addAttribute("businessRegisterNo", purchaseCategoryDTOPair.getKey());
        }
        model.addAttribute("isSupplier", LoginUtil.isSupplier() ? 1 : 0);
        model.addAttribute("optType", optType);
        model.addAttribute("lookFlag", optType==2||optType==3||optType==4||optType==7);
        model.addAttribute("invoiceLookFlag", (optType==2||optType==4)?1:optType==3?2:0);
        model.addAttribute("manualCheckShowFlag", optType==2||optType==3||optType==4);
        String billId;
        String billNo;
        SupplierDTO supplier = new SupplierDTO();
        SupplierDTO company = new SupplierDTO();
        if (optType == 0 || optType == 5) {
            // 新建的情况，获取新的发票云单据
//            billId = sequenceClient.createSequenceNo("invoice_cloud_assistant_bill_no");
//            billNo = billId;
        } else {
//            billId = data.getBillId();
//            billNo = data.getBillNo();
            supplier = supplierClient.getSupplierByCode(data.getSupplierCode());
            company = supplierClient.getSupplierByCode("80" + data.getCompanyCode());
        }
//        model.addAttribute("billId", billId);
//        model.addAttribute("billNo", billNo);
        model.addAttribute("billTaxNo", ObjectUtil.isNotNull(supplier)?StringUtils.defaultString(supplier.getBusinessRegisterNo(), ""):"");
        model.addAttribute("companyTaxNo", StringUtils.defaultString(company.getBusinessRegisterNo(), ""));
        model.addAttribute("companyName", StringUtils.defaultString(company.getSupplierName(), ""));
        model.addAttribute("kingdeeHostUrl", kingdeeHostUrl);
        model.addAttribute("kingdeeSocketUrl", kingdeeSocketUrl);
        return MODULE_ROOT + "/companyInvoicedApply/detail";
    }



    /**
     * 开票申请编辑时选择对账单明细数据
     *
     * @param model model
     * @param companyCode 公司编码
     * @param factoryCode 工厂编码
     * @param supplierCode 供应商编码
     * @param currencyCode 货币代码
     * @param orderType 单据类型 1:材料开票申请 2:运费开票申请
     * @param excludeAsdIds 已经存在的对账单明细ID
     * @param tempDelAsdIds 临时删除的对账单明细ID
     * @return 页面
     */
    @GetMapping("/chose/statement/detail/dialog")
    public String choseStatementDetail(
            Model model, String companyCode, String factoryCode, String supplierCode, String currencyCode,
            Integer orderType, String excludeAsdIds, String tempDelAsdIds, String paymentTermCode
    ){
        model.addAttribute("companyCode", companyCode);
        model.addAttribute("factoryCode", factoryCode);
        model.addAttribute("supplierCode", supplierCode);
        model.addAttribute("currencyCode", currencyCode);
        model.addAttribute("orderType", orderType);
        model.addAttribute("excludeAsdIds", excludeAsdIds);
        model.addAttribute("tempDelAsdIds", tempDelAsdIds);
        model.addAttribute("paymentTermCode", paymentTermCode);
        return MODULE_ROOT + "/invoiced/_chose_statement_detail";
    }

    @GetMapping("/chose/advance/detail/dialog")
    public String choseAdvanceDetail(
            Model model, String companyCode, String supplierCode, String invoiceApplyId,String poCodeItemNoList){
        model.addAttribute("companyCode", companyCode);
        model.addAttribute("supplierCode", supplierCode);
        model.addAttribute("invoiceApplyId", invoiceApplyId);
        model.addAttribute("poCodeItemNoList", poCodeItemNoList);
        return MODULE_ROOT + "/invoiced/_chose_advance_detail";
    }

    /**
     * 开票申请编辑时选择对账单明细数据
     *
     * @param model model
     * @param companyCode 公司编码
     * @param companyName 公司名字
     * @param supplierName 供应商名字
     * @param supplierCode 供应商编码
     * @return 页面
     */
    @GetMapping("/chose/invoice/detail/dialog")
    public String choseInvoiceDetail(
            Model model, String companyCode, String companyName, String supplierCode, String supplierName
    ){
        model.addAttribute("companyCode", companyCode);
        model.addAttribute("companyName", companyName);
        model.addAttribute("supplierCode", supplierCode);
        model.addAttribute("supplierName", supplierName);

        return MODULE_ROOT + "/invoiced/_chose_invoice_detail";
    }



    /**
     * 开票申请编辑时选择对账单返利数据
     *
     * @param model model
     * @param asIds 对账单ID
     * @param alreadyExistSrIds 已经存在的对账单返利记录ID
     * @param tempDelSrId 临时删除的对账单返利记录ID
     * @return 页面
     */
    @GetMapping("/chose/statement/rebate/dialog")
    public String choseStatementRebate(Model model, String asIds, String alreadyExistSrIds, String tempDelSrId){
        model.addAttribute("asIds", asIds);
        model.addAttribute("alreadyExistSrIds", alreadyExistSrIds);
        model.addAttribute("tempDelSrId", tempDelSrId);
        return MODULE_ROOT + "/invoiced/_chose_statement_rebate";
    }


    /**
     * 开票申请编辑时选择对账单返利数据
     *
     * @param model model
     * @param asIds 对账单ID
     * @param alreadyExistSdIds 已经存在的对账单扣款记录ID
     * @param tempDelSdId 临时删除的对账单扣款记录ID
     * @return 页面
     */
    @GetMapping("/chose/statement/deduction/dialog")
    public String choseStatementDeduction(Model model, String asIds, String alreadyExistSdIds, String tempDelSdId){
        model.addAttribute("asIds", asIds);
        model.addAttribute("alreadyExistSdIds", alreadyExistSdIds);
        model.addAttribute("tempDelSdId", tempDelSdId);
        return MODULE_ROOT + "/invoiced/_chose_statement_deduction";
    }

    /**
     * 打印开票单据-财务到票确认
     * @param id 开票id
     * @return
     */
    @GetMapping("/print2")
    public String printInvoice2(Long id, String companyCode, Model model){
        // 开票申请
        CompanyInvoicedApplyPrintDTO data = companyInvoicedApplyLogic.selectPrintDataById(id);
        CompanyAccountStatementDTO accountStatementDTO= new CompanyAccountStatementDTO();
       if (Objects.nonNull(data.getAccountStatementId())){
           accountStatementDTO = companyAccountStatementLogic.getById(data.getAccountStatementId());
           //字典赋值
           DictDTO dictDTO = dictClient.getDictByTypeAndCode(DictCode.PAYMENT_TERMS.getCode(), accountStatementDTO.getPaymentTermCode());
           if (ObjectUtil.isNotNull(dictDTO)){
               accountStatementDTO.setPaymentTermName(dictDTO.getName());
           }

           if (Objects.nonNull(accountStatementDTO.getFinanceConfirmTime())){
               DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
               accountStatementDTO.setFinanceConfirmTimeStr(accountStatementDTO.getFinanceConfirmTime().format(formatter));
               accountStatementDTO.setCreateTimeStr(accountStatementDTO.getCreateTime().format(formatter));
           }
       }
        if (Objects.nonNull(accountStatementDTO) &&
                Objects.nonNull(accountStatementDTO.getAccountStatementYear())
        && Objects.nonNull(accountStatementDTO.getAccountStatementMonth())){
            YearMonth yearMonth = YearMonth.of(Integer.parseInt(accountStatementDTO.getAccountStatementYear()),
                    Integer.parseInt(accountStatementDTO.getAccountStatementMonth()));
            LocalDate firstDayOfMonth = yearMonth.atDay(1);
            LocalDate lastDayOfMonth = yearMonth.atEndOfMonth();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
            accountStatementDTO.setAccountStatementPeriod(formatter.format(firstDayOfMonth)+"到"+formatter.format(lastDayOfMonth));
        }
        model.addAttribute("accountStatement", accountStatementDTO);
        //计算发票税额
//        data.setBeginPeriodTotal(data.getInvoiceTaxTotalAmount().subtract(data.getInvoiceTotalAmount()).setScale(2, RoundingMode.HALF_UP));
        //人民币含税，非人民币不含税
        if ("CNY".equalsIgnoreCase(accountStatementDTO.getCurrencyCode())) {
            accountStatementDTO.setIncludeTax("含税");
        } else {
            accountStatementDTO.setIncludeTax("不含税");
            accountStatementDTO.setToBeInvoiced("(待开票)");
        }
        SupplierContactsDTO defaultContact = supplierClient.getDefaultContact(accountStatementDTO.getSupplierCode(), "4");
        model.addAttribute("supplierInvoiced", defaultContact);

        model.addAttribute("data", accountStatementDTO);

        // 业务过账结果表
        CompanyInvoicedApplyPostResult result = invoicedApplyPostResultLogic.findLastPostResult(id);
        model.addAttribute("result", result);

//        SupplierBank supplierBank = supplierBankService.selectOne(Condition.create().eq("supplier_code",data.getSupplierCode()).last(" limit 1"));
//        model.addAttribute("supplierBank", supplierBank);
        //预制发票号
        String invoiceVoucher = companyInvoicedApplyLogic.findInvoiceVoucher(id);
        model.addAttribute("invoiceVoucher",invoiceVoucher);
        // 公司数据
//        Company company = companyService.selectOne(new EntityWrapper<Company>()
//                .eq("company_code", companyCode));
//        model.addAttribute("company",company);
//        //明细数据
//        List<InvoicedApplyItemDTO> invoicedApplyDetailList = invoicedApplyDetailLogic.providePurchaseConfirm(id,0,null);
//        invoicedApplyDetailList.forEach(invoicedApplyItemDto -> {
//            invoicedApplyItemDto.setItemNo(invoicedApplyItemDto.getItemNo().replaceFirst("^0+(?!$)", ""));
//        });
//        model.addAttribute("detailList",invoicedApplyDetailList);
//        if (CollUtil.isNotEmpty(invoicedApplyDetailList) && invoicedApplyDetailList.size() > 4) {
//            model.addAttribute("detailList4", invoicedApplyDetailList.stream().limit(4).collect(Collectors.toList()));
//            model.addAttribute("remainingNum", invoicedApplyDetailList.size()-4);
//        }
//        model.addAttribute("pgName",invoicedApplyDetailList.get(0).getPgName());
//        // 金额合计
//        JSONObject jeHj = new JSONObject();
//        jeHj.put("sqje", invoicedApplyDetailList.stream().map(InvoicedApplyItemDTO::getNotTaxAmount).filter(Objects::nonNull)
//                .reduce(BigDecimal.ZERO, BigDecimal::add));
//        jeHj.put("hsje", invoicedApplyDetailList.stream().map(InvoicedApplyItemDTO::getTaxAmount).filter(Objects::nonNull)
//                .reduce(BigDecimal.ZERO, BigDecimal::add));
//        jeHj.put("hsce", invoicedApplyDetailList.stream().map(InvoicedApplyItemDTO::getDiffTaxAmount).filter(Objects::nonNull)
//                .reduce(BigDecimal.ZERO, BigDecimal::add));
////        jeHj.put("slje", invoicedApplyDetailList.stream().map(InvoicedApplyItemDTO::getStatementNum).filter(Objects::nonNull)
////                .reduce(BigDecimal.ZERO, BigDecimal::add));
//        model.addAttribute("jeHj",jeHj);
        // 预付款条目
//        List<InvoicedApplyPa> invoicedApplyPaList = invoicedApplyPaService.selectList(new EntityWrapper<InvoicedApplyPa>().eq("invoice_apply_id", id).orderBy("apply_item_no",true));
//        model.addAttribute("invoicedApplyPaList", invoicedApplyPaList);
//        if (CollUtil.isNotEmpty(invoicedApplyPaList) && invoicedApplyPaList.size() > 3) {
//            model.addAttribute("invoicedApplyPaList4", invoicedApplyPaList.stream().limit(3).collect(Collectors.toList()));
//            model.addAttribute("remainingApplyNum", invoicedApplyPaList.size()-3);
//        }
        //审核记录
        CompanyIaApproveQuery query = new CompanyIaApproveQuery();
        query.setIaId(id);
        List<CompanyInvoicedApplyApproveDTO> list = invoicedApplyApproveLogic.selectDataListByQuery(query);
        model.addAttribute("approve", list);

        return MODULE_ROOT +  "/companyInvoicedApply/invoiced_print3";
    }

    /**
     * 询价导入物料界面
     */
    @RequestMapping("/importUI")
    public String importUI(Model model) {
        return MODULE_ROOT + "/invoiced/import";
    }


    @GetMapping("/financePost")
    public String financePost(String id, Model model){
        model.addAttribute("id",id);
        return MODULE_ROOT + "/companyInvoicedApply/finance_post";
    }

    @GetMapping("/financeDate")
    public String financeDate(String id, Model model){
        model.addAttribute("id",id);
        return MODULE_ROOT + "/companyInvoicedApply/finance_date";
    }

//    /**
//     * 导入关联发票
//     *
//     * @param file              导入信息
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping("/importInvoiceData")
//    @Transactional(rollbackFor = Exception.class)
//    public ResponseEntity importInvoiceData(@RequestParam(value = "file") MultipartFile file) {
//        SysReturnMsg sysReturnMsg = new SysReturnMsg(true);
//        List<InvoiceExportDto> supplierCodeList = ExcelUtil.importExcel(file, 0, 1, InvoiceExportDto.class);
//        if (supplierCodeList.size() == 0) {
//            sysReturnMsg.setState(false);
//            sysReturnMsg.setMsg("导入数量为0,请检查");
//            return ResponseEntity.ok(sysReturnMsg);
//        }
//        boolean addFailure = false;
//        StringBuilder msg=new StringBuilder();
//        if (addFailure) {
//            sysReturnMsg.setState(false);
//            sysReturnMsg.setMsg(msg.toString());
//            return ResponseEntity.ok(sysReturnMsg);
//        }
//
//        sysReturnMsg.setData(supplierCodeList);
//        return ResponseEntity.ok(sysReturnMsg);
//    }
}
