package com.jwipc.finance.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jwipc.finance.dto.CostAccountStatementDTO;
import com.jwipc.finance.dto.PaymentNoticeDTO;
import com.jwipc.finance.logic.CostAccountStatementLogic;
import com.jwipc.finance.logic.PaymentNoticeLogic;
import com.jwipc.security.LoginUtil;
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.UserPurchaseGroupClient;
import lombok.RequiredArgsConstructor;
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.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

/**
 * <p>
 * 对账模块-报关单主表 前端控制器
 * </p>
 *
 * @author shenyang.ou
 * @since 2025-10-22
 */
@Controller
@RequestMapping(MODULE_ROOT + "/cost/account/statement")
@RequiredArgsConstructor
public class CostAccountStatementPageController {
    private final CostAccountStatementLogic costAccountStatementLogic;
    private final UserPurchaseGroupClient userPurchaseGroupClient;
    private final SupplierClient supplierClient;

    @GetMapping("/index")
    public String index(Model model){
        model.addAttribute("menuType", 0);
        model.addAttribute("isSupplier", LoginUtil.isSupplier()?1:0);
        model.addAttribute("userId", LoginUtil.getUserId());
        return MODULE_ROOT + "/costAccountStatement/list";
    }

    @GetMapping("/purchase/index")
    public String purchaseIndex(Model model){
        model.addAttribute("menuType", 1);
        model.addAttribute("isSupplier", LoginUtil.isSupplier()?1:0);
        model.addAttribute("userId", LoginUtil.getUserId());
        return MODULE_ROOT + "/costAccountStatement/purchase_list";
    }

    @GetMapping("/finance/index")
    public String financeIndex(Model model){
        model.addAttribute("menuType", 2);
        model.addAttribute("isSupplier", LoginUtil.isSupplier()?1:0);
        model.addAttribute("userId", LoginUtil.getUserId());
        return MODULE_ROOT + "/costAccountStatement/finance_list";
    }

    @GetMapping("/dialog")
    public String dialog(Model model,Integer single){
        model.addAttribute("single", single);
        return MODULE_ROOT + "/costAccountStatement/dialog";
    }

    @GetMapping("/detail")
    public String detail(Model model, Long id,Integer optType) {
        CostAccountStatementDTO data = new CostAccountStatementDTO();
        if (ObjectUtil.isNotNull(id)){
            data = costAccountStatementLogic.getById(id);
            if (optType==3){
                data.setAccountStatementNo(null);
            }
        }else {
            //默认采购组
            data.setPurchaseGroup(userPurchaseGroupClient.getMarkPurchaseGroupCodeByUserId(LoginUtil.getUserId()));
            data.setAccountStatementYear(DateUtil.format(new Date(),"yyyy"));
            data.setAccountStatementMonth(DateUtil.format(DateUtil.offsetMonth(new Date(),-1),"MM"));
            //默认上个月一号
            ;
            data.setInStockStartDate(LocalDateTimeUtil.parse(DateUtil.format(DateUtil.offsetMonth(new Date(),-1),"yyyy-MM-01"),"yyyy-MM-01"));
            //获取上个月最后一天
            data.setInStockEndDate(LocalDateTime.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()));

            if(LoginUtil.isSupplier()){
                List<SupplierPurchaseCategoryDTO> supplierPurchaseCategoryDTOS = supplierClient.getList(String.valueOf(LoginUtil.getSupplierId()));
                if (CollectionUtil.isNotEmpty(supplierPurchaseCategoryDTOS)){
                    //过滤优先标记
                    List<SupplierPurchaseCategoryDTO> filterSupplierPurchaseCategoryDTOS = supplierPurchaseCategoryDTOS.stream().filter(supplierPurchaseCategoryDTO -> supplierPurchaseCategoryDTO.getFirstFlag()==1).toList();
                    if (CollectionUtil.isEmpty(filterSupplierPurchaseCategoryDTOS)){
                        //过滤公司
                        List<SupplierPurchaseCategoryDTO> filterCompanyDTOS = supplierPurchaseCategoryDTOS.stream().filter(supplierPurchaseCategoryDTO -> "1000".equals(supplierPurchaseCategoryDTO.getCompanyCode())).toList();
                        if (CollectionUtil.isNotEmpty(filterCompanyDTOS)){
                            data.setCompanyCode(filterCompanyDTOS.get(0).getCompanyCode());
                            data.setCurrencyCode(filterCompanyDTOS.get(0).getCurrencyCode());
                            data.setTaxCode(filterCompanyDTOS.get(0).getTaxCode());
                            data.setPaymentTermCode(filterCompanyDTOS.get(0).getPaymentTerms());
                            data.setPaymentWay(filterCompanyDTOS.get(0).getPaymentMethod());
                            data.setPurchaseGroup(filterCompanyDTOS.get(0).getPurchaseGroupCode());
                        }else {
                            data.setCompanyCode(supplierPurchaseCategoryDTOS.get(0).getCompanyCode());
                            data.setCurrencyCode(supplierPurchaseCategoryDTOS.get(0).getCurrencyCode());
                            data.setTaxCode(supplierPurchaseCategoryDTOS.get(0).getTaxCode());
                            data.setPaymentTermCode(supplierPurchaseCategoryDTOS.get(0).getPaymentTerms());
                            data.setPaymentWay(supplierPurchaseCategoryDTOS.get(0).getPaymentMethod());
                            data.setPurchaseGroup(supplierPurchaseCategoryDTOS.get(0).getPurchaseGroupCode());
                        }
                    }else {
                        data.setCompanyCode(filterSupplierPurchaseCategoryDTOS.get(0).getCompanyCode());
                        data.setCurrencyCode(filterSupplierPurchaseCategoryDTOS.get(0).getCurrencyCode());
                        data.setTaxCode(filterSupplierPurchaseCategoryDTOS.get(0).getTaxCode());
                        data.setPaymentTermCode(filterSupplierPurchaseCategoryDTOS.get(0).getPaymentTerms());
                        data.setPaymentWay(filterSupplierPurchaseCategoryDTOS.get(0).getPaymentMethod());
                        data.setPurchaseGroup(filterSupplierPurchaseCategoryDTOS.get(0).getPurchaseGroupCode());
                    }

                }
                String account = LoginUtil.getAccount();
                data.setSupplierCode(account);
                model.addAttribute("supplierCode", account);
                SupplierDTO supplierByCode = supplierClient.getSupplierByCode(account);
                if(supplierByCode!=null){
                    data.setSupplierName(supplierByCode.getSupplierName());
                }
            }
        }
        //0：新增 1：编辑 2:查看 3:复制 4:采购确认 5:财务确认
        model.addAttribute("data", data);
        model.addAttribute("optType", optType);
        model.addAttribute("lookFlag", optType==2||optType==4||optType==5);
        model.addAttribute("isSupplier", LoginUtil.isSupplier()?1:0);
        return MODULE_ROOT + "/costAccountStatement/detail";
    }

    /**
     * 打印开票单据-财务到票确认
     * @param id 开票id
     * @return
     */
    @GetMapping("/print")
    public String printStatement(Long id, Model model){

        Map<String,Object> map = costAccountStatementLogic.printStatement(id);
        for(String key:map.keySet()){
            model.addAttribute(key,map.get(key));
        }

        return MODULE_ROOT +  "/costAccountStatement/statement_print";
    }

    /**
     * 对账单采购审批确认时选择扣款信息弹框
     *
     * @param model model
     * @return 页面
     */
    @GetMapping("/chose/statement/dialog")
    public String choseStatementDialog(Model model){
        if(LoginUtil.isSupplier()){
            model.addAttribute("supplierCode", LoginUtil.getAccount());
        }
        model.addAttribute("isSupplier", LoginUtil.isSupplier()?1:0);
        model.addAttribute("userId", LoginUtil.getUserId());
        return MODULE_ROOT + "/costAccountStatement/_chose_statement";
    }

    /**
     * 对账单采购审批确认时选择扣款信息弹框
     *
     * @param model model
     * @return 页面
     */
    @GetMapping("/chose/statement/with/apply/dialog")
    public String choseStatementWithApplyDialog(Model model,String companyCode,String supplierCode,String currencyCode){
        model.addAttribute("supplierCode", supplierCode);
        model.addAttribute("companyCode", companyCode);
        model.addAttribute("currencyCode", currencyCode);
        return MODULE_ROOT + "/costAccountStatement/_chose_statement_with_apply";
    }
}
