package com.jwipc.finance.controller.rest;


import com.jwipc.finance.entity.InvoicedApply;
import com.jwipc.finance.logic.InvoicedApplyApproveLogic;
import com.jwipc.finance.logic.InvoicedApplyDetailLogic;
import com.jwipc.finance.model.query.CreateInvoicedApplyPageQuery;
import com.jwipc.finance.model.query.IaApproveQuery;
import com.jwipc.finance.service.IInvoicedApplyService;
import com.jwipc.page.PageView;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
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.RestController;

import java.util.Arrays;
import java.util.List;

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

/**
 * @author shenyang.ou
 * @date 2024/3/5 13:56
 * @desc
 */
@RestController
@RequestMapping(MODULE_ROOT + "/invoiced/apply/detail/rest")
@RequiredArgsConstructor
public class InvoicedApplyDetailRestController {
    private final InvoicedApplyDetailLogic invoicedApplyDetailLogic;
    private final InvoicedApplyApproveLogic invoicedApplyApproveLogic;
    private final IInvoicedApplyService invoicedApplyService;

    @PostMapping("/find/by/apply/id")
    public ResponseEntity findByApplyId(Long iaId, Integer becShare) {
        return ResponseEntity.ok(invoicedApplyDetailLogic.findByApplyId(iaId,becShare));
    }


    /**
     * 获取开票申请单审批确认备注
     *
     * @param query 请求参数
     * @return 结果
     */
    @PostMapping("/find/ia/approve/log")
    public PageView findInvoicedApplyApproveLog(IaApproveQuery query) {
        return invoicedApplyApproveLogic.selectDataByQuery(query);
    }

    /**
     * 创建预制发票
     * @param iaId 开票申请id
     * @param type 1:预制 2:删除
     * @return
     */
    @PostMapping("/create/prefabricate/invoice")
    public ResponseEntity createPrefabricateInvoice(String iaIds,Integer type,String invoicePostDate,String statementType){
        List<String> iaIdList = Arrays.asList(StringUtils.split(iaIds, ","));
        List<InvoicedApply> invoicedApplies = invoicedApplyService.listByIds(iaIdList);
        //判断财务复核人是否一样
        if (invoicedApplies.stream().map(InvoicedApply::getFinanceConfirmUserId).distinct().count() > 1){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("财务复核人不一致，请重新选择");
        }
        for (String iaId : iaIdList){
            invoicedApplyDetailLogic.createPrefabricateInvoice(Long.valueOf(iaId),type,invoicePostDate,statementType);
        }
        return ResponseEntity.ok(true);
    }
}
