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

import cn.hutool.core.collection.CollectionUtil;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.topsun.common.BillStatus;
import com.huigou.topsun.sap.purchase.application.SapPurchaseApplication;
import com.huigou.topsun.sap.purchase.domain.SapPurchase;
import com.huigou.topsun.sap.purchase.domain.query.SapPurchaseQueryRequest;
import com.huigou.topsun.sap.purchase.domain.vo.SapPurchaseItemDto;
import com.huigou.topsun.sap.purchaseApproval.controller.SapPurchaseApprovalController;
import com.huigou.topsun.sap.purchaseApproval.domain.vo.SapPurchaseApprovalDto;
import com.huigou.topsun.sap.sapApplication.application.SapDictionaryApplication;
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.JSONUtil;
import com.huigou.util.SDO;
import com.huigou.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: xin.lu
 * @Date: 2023/12/27/10:21
 * @Description:
 */
@Controller
@ControllerMapping("/sapPurchase")
public class SapPurchaseController extends CommonController {
    private final static Logger LOG = LoggerFactory.getLogger(SapPurchaseController.class);
    @Override
    protected String getPagePath() {
        return "/biz/topsun/sap/purchase/";
    }

    @Resource
    private SapPurchaseApplication sapPurchaseApplication;

    @Resource
    private SapDictionaryApplication sapDictionaryApplication;

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

    public String slicedSapPurchaseList(){
        SDO sdo = this.getSDO();
        SapPurchaseQueryRequest queryRequest = sdo.toQueryRequest(SapPurchaseQueryRequest.class);
        Map<String, Object> map = sapPurchaseApplication.slicedSapPurchaseList(queryRequest);
        return toResult(map);
    }

    public String choosePurchaseDetail(){
        return forward("choosePurchaseDetail");
    }

    public String forwardSapPurchaseDetail(){
        this.putAttribute("processDefinitionKey", SapPurchaseApplication.PROCESS_DEFINITION_KEY);
        // 新增的时候procUnitId一定要设置成Apply，不然jsp页面的所有表单元素是readonly状态
        this.putAttribute("procUnitId", "Apply");
        String bsart = getSDO().getString("bsart");
        SapPurchase sapPurchase = new SapPurchase();
        sapPurchase.setBsart(bsart);
        sapPurchase.setStatusId(BizBillStatus.APPLYING.getId());
        /**
         * 设置jsp页面初始化填充数据，如果不设置， 那么在jsp页面上填写完表单之后立即提交申请TaskDescription获取不到时间和相关人员信息
         */
        Operator operator = getOperator();
        sapPurchase.setDefaultValues(new OrgUnit(operator.getFullId(), operator.getFullName()));
        switch (bsart){
            case "ZNE1"://固定资产采购申请
                return forward("sapZNE1PurchaseDetail",sapPurchase);
            case "ZFW"://服务类采购申请
                return forward("sapPurchaseDetail",sapPurchase);
            case "ZNE2"://非资产类消耗性采购申请
                sapPurchase.setKnttp("K");
                return forward("sapZNE2PurchaseDetail",sapPurchase);
        }
        return null;
    }

    public String showSapPurchaseDetail(){
        SDO sdo = this.getSDO();
        String id = sdo.getBizId();
        SapPurchase sapPurchase = sapPurchaseApplication.loadSapPurchase(id);
        switch (sapPurchase.getBsart()){
            case "ZNE1":
                return forward("sapZNE1PurchaseDetail",sapPurchase);
            case "ZFW":
                return forward("sapPurchaseDetail",sapPurchase);
            case "ZNE2":
                return forward("sapZNE2PurchaseDetail",sapPurchase);
        }
        return null;
    }

   //撤销审批
    public String revokeApproval(){
        SDO sdo = this.getSDO();
        String id=sdo.getString("id");
        String newId=sapPurchaseApplication.revokeApproval(id);
        return success();
    }

    public String showBindAnln1(){
        SDO sdo = this.getSDO();
        String itemId = sdo.getString("itemId");
        String werks = sdo.getString("werks");
        String matkl = sdo.getString("matkl");
        String anln1 = sdo.getString("anln1");
        this.putAttribute("werks",werks);
        this.putAttribute("matkl",matkl);
        this.putAttribute("selectValues",anln1);
        return forward("purchaseAnln1Detail",itemId);
    }

    public String queryAnlanFromSap() throws IOException {
        SDO sdo = this.getSDO();
        String param = sdo.getString("paramValue");
        String werks = sdo.getString("werks");
        String matkl = sdo.getString("matkl");
        List<Map<String, String>> mapList = new ArrayList<>();
        if (StringUtil.isBlank(param)){
            return packGridDataAndResult(mapList);
        }
        mapList = sapDictionaryApplication.getSapDictionary("ANLN1");
        if (CollectionUtil.isNotEmpty(mapList)) {
            mapList = mapList
                    .stream()
                    .filter(map -> map.values().stream().anyMatch(value -> value.contains(werks)))
                    .collect(Collectors.toList());
            //根据物料组筛选对应资产类型下的资产编号
//            if ("A0001".equals(matkl)){//固定资产-房屋及建筑物
//                mapList = mapList
//                       .stream()
//                       .filter(map -> map.values().stream().anyMatch(value -> value.contains("Z101")))
//                       .collect(Collectors.toList());
//            }
            if (StringUtil.isNotBlank(param)){//输入查询条件过滤
                mapList = mapList
                        .stream()
                        .filter(map -> map.values().stream().anyMatch(value->value.contains(param)))
                        .collect(Collectors.toList());
            }
        }
        return packGridDataAndResult(mapList);
    }

    @SkipAuth
    @RequestMapping( value = "/getEPPurchaseItem")
    @ResponseBody
    public HashMap<String, Object> getEPPurchaseItem(@RequestBody SapPurchaseItemDto sapPurchaseItemDto){
        HashMap<String, Object> messageMap = new HashMap<>();
        LOG.info("EP打样采购申请数据=={}", JSONUtil.toString(sapPurchaseItemDto));
        SapPurchase sapPurchase = new SapPurchase();
        try {
            sapPurchase = this.sapPurchaseApplication.saveEPPurchaseItem(sapPurchase,sapPurchaseItemDto);
            messageMap.put("Message_Status","S");
            messageMap.put("Message_Text","成功");
            messageMap.put("DATA",sapPurchase.getBillCode());
        }catch (RuntimeException e){
            messageMap.put("Message_Status","E");
            messageMap.put("Message_Text",e.getMessage());
            messageMap.put("DATA","");
        }
        return messageMap;
    }
}
