package com.huigou.topsun.sap.costReimbursement.controller;


import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.topsun.common.BillStatus;
import com.huigou.topsun.sap.costReimbursement.application.SapCostReimbursementApplication;
import com.huigou.topsun.sap.costReimbursement.application.SapCostReimbursementDetailApplication;
import com.huigou.topsun.sap.costReimbursement.domain.SapCostReimbursement;
import com.huigou.topsun.sap.costReimbursement.domain.query.SapCostReimbursementQueryRequest;
import com.huigou.topsun.sap.costReimbursement.domain.vo.PaymentReceiptVo;
import com.huigou.topsun.sap.sapApplication.application.SapPaymentApplication;
import com.huigou.uasp.annotation.ControllerMapping;
import com.huigou.uasp.annotation.SkipAuth;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.client.CommonController;
import com.huigou.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;


@Controller
@ControllerMapping("/sapCostReimbursement")
public class SapCostReimbursementController extends CommonController {

    private final static Logger LOG = LoggerFactory.getLogger(SapCostReimbursementController.class);

    protected String getPagePath() {
        return "/biz/topsun/sap/costReimbursement/";
    }

    @Autowired
    SapCostReimbursementApplication costReimbursementApplication;
    @Autowired
    SapCostReimbursementDetailApplication costReimbursementDetailApplication;
    @Autowired
    private SapPaymentApplication sapPaymentApplication;


    public String forwardCostReimbursementList(){
        return forward("costReimbursementList");
    }
    public String forwardPayApplyNoPOList(){
        return forward("payApplyNoPOList");
    }

    public String forwardAdvancePaymentList(){
        this.putAttribute("statusKindsList", BillStatus.getValidMap());
        return forward("advancePaymentList");
    }

    public String forwardEmployeeLoanList(){
        return forward("employeeLoanList");
    }

    public String forwardPayApplyList(){
        this.putAttribute("statusKindsList", BillStatus.getValidMap());
        return forward("payApplyList");
    }

    public String forwardRefundApplyList(){
        return forward("refundApplyList");
    }

    public String forwardCostReimbursement(){
        //定义流程
        this.putAttribute("processDefinitionKey", SapCostReimbursementApplication.PROCESS_DEFINITION_KEY);
        this.putAttribute("procUnitId", "Apply");//定义流程环节的id
        SDO sdo = this.getSDO();
        String type=  sdo.getProperty("type").toString();
        SapCostReimbursement sapCostReimbursement = new SapCostReimbursement();
        sapCostReimbursement.setStatusId(BizBillStatus.APPLYING.getId());
        Operator operator = getOperator();//获取当前操作员的详情信息
        sapCostReimbursement.setDefaultValues(new OrgUnit(operator.getFullId(), operator.getFullName()));
        sapCostReimbursement.setZepNo(sapCostReimbursement.getBillCode());
        sapCostReimbursement.setZepDepart(operator.getDeptCode());
        sapCostReimbursement.setZepDepartname(operator.getDeptName());
        sapCostReimbursement.setZepAppli(operator.getLoginName());
        sapCostReimbursement.setZepAppliname(operator.getName());
        sapCostReimbursement.setZepFcrdate(new Date());
        switch (type) {
            case "cost":
                sapCostReimbursement.setZepFtype("A");
                sapCostReimbursement.setZepFtypename("费用报销流程");
                return forward("costReimbursement",sapCostReimbursement);
            case "payNoPo":
                sapCostReimbursement.setZepFtype("H");
                sapCostReimbursement.setZepFtypename("付款申请(无PO)流程");
                return forward("payApplyNoPO",sapCostReimbursement);
            case "borrow":
                sapCostReimbursement.setZepFtype("B");
                sapCostReimbursement.setZepFtypename("员工借款流程");
                return forward("employeeLoan",sapCostReimbursement);
            case "advance":
                sapCostReimbursement.setZepFtype("D");
                sapCostReimbursement.setZepFtypename("预付款申请流程");
                return forward("advancePayment",sapCostReimbursement);
            case "pay":
                sapCostReimbursement.setZepFtype("C");
                sapCostReimbursement.setZepFtypename("付款申请流程");
                return forward("payApply",sapCostReimbursement);
            case "refund":
                sapCostReimbursement.setZepFtype("E");
                sapCostReimbursement.setZepFtypename("客户退款申请流程");
                return forward("refundApply",sapCostReimbursement);
        }
        return null;
    }


    public String slicedSapCostReimbursementList(){
        SDO sdo = this.getSDO();
        SapCostReimbursementQueryRequest queryRequest = sdo.toQueryRequest(SapCostReimbursementQueryRequest.class);
        Map<String, Object> map = costReimbursementApplication.slicedSapCostReimbursementQuery(queryRequest);
        return toResult(map);
    }

    /**
     * 预付款列表查询
     * @return
     */
    public String slicedAdvancePaymentList(){
        SDO sdo = this.getSDO();
        SapCostReimbursementQueryRequest queryRequest = sdo.toQueryRequest(SapCostReimbursementQueryRequest.class);
        Map<String, Object> map = costReimbursementApplication.slicedAdvancePaymentList(queryRequest);
        return toResult(map);
    }


    public String slicedSapCostReimbursementDetailList(){
        SDO sdo = this.getSDO();
        SapCostReimbursementQueryRequest queryRequest = sdo.toQueryRequest(SapCostReimbursementQueryRequest.class);
        Map<String, Object> map = new HashMap<>();
        if (StringUtil.isNotBlank(queryRequest.getReimbursementBaseInfoId())){
            map = costReimbursementDetailApplication.slicedSapCostReimbursementDetail(queryRequest);
        }else {
            map.put("Rows",new ArrayList<>());
        }
        return toResult(map);
    }

    /**
     * 工作流审核跳转页面
     * @return
     */
    public String showSapCostReimbursement() {
        SDO sdo = this.getSDO();
        String id = sdo.getBizId();
        String isDetailPage = sdo.getString("isDetailPage");
        if("true".equals(isDetailPage))this.putAttribute("isReadOnly","true");
        SapCostReimbursement sapCostReimbursement = costReimbursementApplication.loadSapCostReimbursementById(id);
        String zepFtype = sapCostReimbursement.getZepFtype();
        switch (zepFtype) {
            case "A":
                return forward("costReimbursement",sapCostReimbursement);
            case "H":
                return forward("payApplyNoPO",sapCostReimbursement);
            case "B":
                return forward("employeeLoan",sapCostReimbursement);
            case "D":
                return forward("advancePayment",sapCostReimbursement);
            case "C":
                return forward("payApply",sapCostReimbursement);
            case "E":
                return forward("refundApply",sapCostReimbursement);
        }
        return null;
    }

    public String deleteSapCostReimbursementDetails(){
        SDO sdo = this.getSDO();
        List<String> ids = sdo.getIds();
        costReimbursementDetailApplication.deleteSapCostReimbursementDetails(ids);
        return success();
    }
//
//    /**
//     * 手动发送数据到sap
//     * @return
//     */
//    public String againSendSapDate(){
//        SDO sdo = this.getSDO();
//        String id = sdo.getBizId();
//        sapStatsIndicatorsApplication.sendSapDate(id);
//        return success();
//    }


    @SkipAuth
    @RequestMapping( value = "/paymentReceipt")
    @ResponseBody
    public HashMap<String, Object> paymentReceipt(@RequestBody PaymentReceiptVo paymentReceiptVo){
        HashMap<String, Object> messageMap = new HashMap<>();
        messageMap.put("CODE","S");
        messageMap.put("MSG","成功");
        messageMap.put("DATA",paymentReceiptVo.getBillCode());
        LOG.info("SAP财务付款凭证数据=={}", JSONUtil.toString(paymentReceiptVo));
        try {
            this.costReimbursementApplication.savePaymentReceiptVo(paymentReceiptVo);
        }catch (RuntimeException e){
            messageMap.put("CODE","E");
            messageMap.put("MSG",e.getMessage());
            messageMap.put("DATA",paymentReceiptVo.getBillCode());
        }
        return messageMap;
    }

    /**
     * 根据发票号校验是否已经提交过该发票号
     * @return
     */
    public String checkzyl06(){
        SDO sdo = this.getSDO();
        String zyl06 = sdo.getString("zyl06");
        Integer count = 0;
        if (StringUtil.isNotBlank(zyl06)){
            count = costReimbursementApplication.checkzyl06(zyl06);
        }
        return success(count);
    }

    public String queryKostlByPersonCode(){
        SDO sdo = this.getSDO();
        String personCode = sdo.getString("personCode");
        if (StringUtil.isNotBlank(personCode)){
            personCode = personCode.replaceFirst("^0*","");
        }
        Map<String, Object> map = costReimbursementApplication.queryKostlByPersonCode(personCode);
        return toResult(map);
    }

    public String showAddPayApplyDetail(){
        SDO sdo = this.getSDO();
        String partner = sdo.getString("partner");
        String bukrs = sdo.getString("bukrs");
        this.putAttribute("partner",partner);
        this.putAttribute("bukrs",bukrs);
        return forward("payApplyDetail");
    }

    public String showAddAdvancePaymentDetail(){
        SDO sdo = this.getSDO();
        String partner = sdo.getString("partner");
        String bukrs = sdo.getString("bukrs");
        this.putAttribute("partner",partner);
        this.putAttribute("bukrs",bukrs);
        return forward("advancePaymentDetail");
    }

    public String getPartnerInvs() {
        SDO sdo = this.getSDO();
        SapCostReimbursementQueryRequest queryRequest = sdo.toQueryRequest(SapCostReimbursementQueryRequest.class);
        List<Map<String, String>> mapList = sapPaymentApplication.getPartnerInvs(queryRequest.getBukrs(),queryRequest.getPartner(),queryRequest.getZepFtype());
        //查询申请中、审批中、已完成的发票号
        List<String> excludeCompletePartnerInvs = costReimbursementApplication.excludeCompletePartnerInvs(queryRequest.getPartner());

        //遍历mapList,把采购发票号相同的排除掉
        mapList.removeIf(stringStringMap -> {
            String belnr2 = stringStringMap.get("BELNR2");
            return excludeCompletePartnerInvs.stream().anyMatch(value -> value.equals(belnr2));
        });
        return packGridDataAndResult(mapList);
    }

    public String getPurchaseOrders() {
        SDO sdo = this.getSDO();
        SapCostReimbursementQueryRequest queryRequest = sdo.toQueryRequest(SapCostReimbursementQueryRequest.class);
        List<Map<String, String>> mapList = sapPaymentApplication.getPurchaseOrders(queryRequest.getBukrs(),queryRequest.getPartner(),queryRequest.getZepFtype());
        return packGridDataAndResult(mapList);
    }
}