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


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.huigou.cache.DictUtil;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.topsun.common.BillStatus;
import com.huigou.topsun.sap.common.application.SapMutualEpLogApplication;
import com.huigou.topsun.sap.nonProdApply.application.NonProdApplyApplication;
import com.huigou.topsun.sap.nonProdApply.application.NonProdApplyDeptApplication;
import com.huigou.topsun.sap.nonProdApply.domain.NonProdApplyBaseInfo;
import com.huigou.topsun.sap.nonProdApply.domain.SapNonProdApplyDept;
import com.huigou.topsun.sap.nonProdApply.domain.query.NonProdApplyBaseInfoQueryRequest;
import com.huigou.topsun.sap.nonProdApply.domain.vo.ProdApplyFromSapVO;
import com.huigou.topsun.sap.purchaseApproval.controller.SapPurchaseApprovalController;
import com.huigou.topsun.sap.purchaseApproval.domain.vo.SapPurchaseApprovalDto;
import com.huigou.topsun.sap.suppliers.application.SuppliersDataApplication;
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.CommonUtil;
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.*;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@ControllerMapping("/sapNonProdApply")
public class NonProdApplyController extends CommonController {

    protected String getPagePath() {
        return "/biz/topsun/sap/nonProdApply/";
    }
    @Autowired
    NonProdApplyApplication nonProdApplyApplication;
    @Autowired
    NonProdApplyDeptApplication nonProdApplyDeptApplication;
    @Autowired
    SapMutualEpLogApplication sapMutualEpLogApplication;

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

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

    public String forwardNonProdApplyDetail(){
        this.putAttribute("processDefinitionKey", NonProdApplyApplication.PROCESS_DEFINITION_KEY);
        this.putAttribute("procUnitId", "Apply");//定义流程环节的id
        this.putAttribute("applyType","0");
        SDO sdo = this.getSDO();
        String bizId=sdo.getString("bizId");
        String extended=sdo.getString("extend");
        NonProdApplyBaseInfo nonProdApplyBaseInfo = new NonProdApplyBaseInfo();
        nonProdApplyBaseInfo.setMaintenanceType("new");
        nonProdApplyBaseInfo.setApplyType("0");
        nonProdApplyBaseInfo.setKind("materiel");
        this.putAttribute("kind","materiel");
        nonProdApplyBaseInfo.setCreatedDate(new Date());
          if (StringUtil.isNotBlank(extended)) { //扩展流程
                nonProdApplyBaseInfo = nonProdApplyApplication.loadNonProdApplyBaseInfoById(bizId);
                if (!isLastedData(nonProdApplyBaseInfo.getBillCode(), nonProdApplyBaseInfo.getMatnr())) {
                    throw new RuntimeException("请选择物料"+nonProdApplyBaseInfo.getMatnr()+"的最新数据进行扩展！");
                }
                this.putAttribute("processDefinitionKey", NonProdApplyApplication.PROCESS_DEFINITION_KEY_EXD);
                this.putAttribute("applyType", "2");
                nonProdApplyBaseInfo.setMaintenanceType("extend");
                nonProdApplyBaseInfo.setBillCode("");
                nonProdApplyBaseInfo.setId("");
                // suppliersInfo.setSId(bizId);
                Map<String, Object> map = new HashMap();
                map.put("bizId", "");
                sdo.setProperties(map);
                nonProdApplyBaseInfo.setFullId("");
                nonProdApplyBaseInfo.setSourceId(bizId);

                Map<String, String> dictMapUsage = DictUtil.getDictionary("serviceusage");
                List<Map<String, String>> list = new ArrayList<>();
                //for (Map maps:mapUsage){
                //查询扩展前所有的 业务部门
          /*  String usedBusiness=nonProdApplyApplication.getChangeBusinessUsage(bizId,"扩展");
            String []usages=usedBusiness.split(",");//nonProdApplyBaseInfo.getBusinessUsage().split(",");
            Map <String, String>mapTmp=new HashMap();
            Map <String, String>unMapTmp=new HashMap();
            for (Map.Entry<String, String> entry : dictMapUsage.entrySet()) {
                String key = entry.getKey().toUpperCase();
               for (String usage:usages){
                  if (key.equals(usage)){
                      mapTmp.put(key, entry.getValue());
                      break;
                  }
               }
            }
            for (Map.Entry<String, String> entry : dictMapUsage.entrySet()) {
                 String key = entry.getKey().toUpperCase();
                 boolean isexists=false;
                for (Map.Entry<String, String> entry2 : mapTmp.entrySet()) {
                     if (entry2.getKey().toUpperCase().equals(key)){
                        isexists=true;
                        break;
                    }
                }
                if (!isexists) {
                    unMapTmp.put(key, entry.getValue());
                }
            }

           this.putAttribute("businessUsageSeledList",mapTmp); */
                Map<String, String> unMapTmp = new HashMap();
                for (Map.Entry<String, String> entry : dictMapUsage.entrySet()) {
                    String key = entry.getKey().toUpperCase();
                    boolean isexists = false;
                    if (!"K".equals(key)) {
                        unMapTmp.put(key, entry.getValue());
                    }
                }
                this.putAttribute("businessUsageUnSeledList", unMapTmp);
                // nonProdApplyBaseInfo.setBusinessUsageSeled(nonProdApplyBaseInfo.getBusinessUsage());
                //  nonProdApplyBaseInfo.setBusinessUsageSeled(usedBusiness);
                nonProdApplyBaseInfo.setApplyType("2");
                this.putAttribute("bizId", "");
                this.putAttribute("sourceId", bizId);
                this.putAttribute("id", "");
            } else if (StringUtil.isNotBlank(sdo.getString("modify"))) {   //变更
                if (StringUtil.isNotBlank(bizId)) {
                    nonProdApplyBaseInfo = nonProdApplyApplication.loadNonProdApplyBaseInfoById(bizId);
                    if (!isLastedData(nonProdApplyBaseInfo.getBillCode(), nonProdApplyBaseInfo.getMatnr())) {
                        throw new IllegalArgumentException("请选择物料"+nonProdApplyBaseInfo.getMatnr()+"的最新数据进行变更！");
                    }

                    this.putAttribute("processDefinitionKey", NonProdApplyApplication.PROCESS_DEFINITION_KEY_MOD);
                    this.putAttribute("applyType", "1");
                    nonProdApplyBaseInfo.setMaintenanceType("modify");
                    nonProdApplyBaseInfo.setBillCode("");
                    nonProdApplyBaseInfo.setId("");
                    nonProdApplyBaseInfo.setApplyType("1");
                    // suppliersInfo.setSId(bizId);
                    //获取变更前的业务状态
                    String usedBusiness = nonProdApplyApplication.getChangeBusinessUsage(bizId, "变更");
                    Map<String, Object> map = new HashMap();
                    map.put("bizId", "");
                    sdo.setProperties(map);
                    nonProdApplyBaseInfo.setFullId("");
                    nonProdApplyBaseInfo.setSourceId(bizId);
                    this.putAttribute("bizId", "");
                    this.putAttribute("sourceId", bizId);
                    this.putAttribute("id", "");
                }
            }
            nonProdApplyBaseInfo.setAttbizId(CommonUtil.createGUID()); // 自动生成附件id
            nonProdApplyBaseInfo.setStatusId(BizBillStatus.APPLYING.getId());
            Operator operator = getOperator();//获取当前操作员的详情信息
            nonProdApplyBaseInfo.setDefaultValues(new OrgUnit(operator.getFullId(), operator.getFullName()));
            return forward("nonProdApplyDetail",nonProdApplyBaseInfo);
    }

   // 查询当前物料是否最新的数据进行变更或扩展
    public boolean isLastedData(String billCode,String matnr){

        NonProdApplyBaseInfoQueryRequest query =new NonProdApplyBaseInfoQueryRequest();
        query.setMatnr(matnr);
        Map exmap=nonProdApplyApplication.slicedNonApplyBaseInfoByMatnr(query);

        List <Map <String,Object>>extendedList=(List)exmap.get("Rows");

        Map  <String,Object> map=extendedList.get(0);
        String newBillCode=map.get("billCode").toString();
        if (newBillCode.equals(billCode)){
            return true;
        } else {
            return false;
        }
    }

    public String slicedNonProdApplyList(){
        SDO sdo = this.getSDO();
        NonProdApplyBaseInfoQueryRequest queryRequest = sdo.toQueryRequest(NonProdApplyBaseInfoQueryRequest.class);
        Map<String, Object> map = nonProdApplyApplication.slicedNonProdApplyBaseInfoQuery(queryRequest);
        return toResult(map);
    }


    /**
     * 工作流审核跳转页面
     * @return
     */
    public String showNonProdApply() {
        SDO sdo = this.getSDO();
        String id = sdo.getBizId();
        String isDetailPage = sdo.getString("isDetailPage");
        if("true".equals(isDetailPage)) this.putAttribute("isDetailPage","true");
        NonProdApplyBaseInfo nonProdApplyBaseInfo = nonProdApplyApplication.loadNonProdApplyBaseInfoById(id);
        SapNonProdApplyDept nonProdApplyDept = nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(id);
        if (ObjectUtil.isNotNull(nonProdApplyDept)){
            nonProdApplyBaseInfo.setMatnr(nonProdApplyDept.getMatnr());
        }
        nonProdApplyBaseInfo.setApplyType("0");
        if (nonProdApplyBaseInfo.getMaintenanceType().equals("modify")){
            nonProdApplyBaseInfo.setApplyType("1");
            this.putAttribute("applyType", "1");
        }  if (nonProdApplyBaseInfo.getMaintenanceType().equals("extend")){
            nonProdApplyBaseInfo.setApplyType("2");
            this.putAttribute("applyType", "2");
            Map <String,String>dictMapUsage=DictUtil.getDictionary("serviceusage");
            NonProdApplyBaseInfo sourceNonProdApplyBaseInfo=nonProdApplyApplication.loadNonProdApplyBaseInfoById(nonProdApplyBaseInfo.getSourceId());
           // String []usages=sourceNonProdApplyBaseInfo.getBusinessUsage().split(",");

            //String []exdusages=nonProdApplyBaseInfo.getBusinessUsage().split(",");
            //查询扩展前所有的 业务部门
            NonProdApplyBaseInfoQueryRequest queryRequest=new NonProdApplyBaseInfoQueryRequest();
            queryRequest.setMatnr(nonProdApplyDept.getMatnr());
            Map exmap=nonProdApplyApplication.slicedNonApplyBaseInfoByMatnr(queryRequest);

            List <Map <String,Object>>extendedList=(List)exmap.get("Rows");
            String usedBusiness="";
            for (Map <String,Object>mapExd:extendedList) {
                usedBusiness+=mapExd.get("businessUsage").toString()+",";
            }
            if (usedBusiness.length()>1){
                usedBusiness=usedBusiness.substring(0,usedBusiness.length()-1);
            }
            usedBusiness=usedBusiness.replaceAll(nonProdApplyBaseInfo.getBusinessUsage(),"");//去掉本次的
            nonProdApplyBaseInfo.setBusinessUsageSeled(usedBusiness);
            String []usages=usedBusiness.split(",");

           /*   Map <String, String>mapTmp=new HashMap();
            Map <String, String>unMapTmp=new HashMap();
          for (Map.Entry<String, String> entry: dictMapUsage.entrySet()) {
                String key = entry.getKey().toUpperCase();
                for (String usage:usages){
                    if (key.equals(usage)){
                        mapTmp.put(key, entry.getValue());
                        break;
                    }
                }
            }
            for (Map.Entry<String, String> entry : dictMapUsage.entrySet()) {
                String key = entry.getKey().toUpperCase();
                boolean isexists=false;
                for (Map.Entry<String, String> entry2 : mapTmp.entrySet()) {
                    if (entry2.getKey().toUpperCase().equals(key)){
                        isexists=true;
                        break;
                    }
                }
                if (!isexists) {
                    unMapTmp.put(key, entry.getValue());
                }
            }

            this.putAttribute("businessUsageSeledList",mapTmp);
            this.putAttribute("businessUsageUnSeledList",unMapTmp);*/
            Map <String, String>unMapTmp=new HashMap();
            for (Map.Entry<String, String> entry : dictMapUsage.entrySet()) {
                String key = entry.getKey().toUpperCase();
                boolean isexists = false;
                if (!"K".equals(key)) {
                    unMapTmp.put(key, entry.getValue());
                }
            }
            this.putAttribute("businessUsageUnSeledList",unMapTmp);
        }
        Map <String,String>dictMapUsage=DictUtil.getDictionary("serviceusage");
        String dictMapUsages="";
        for (Map.Entry<String, String> entry: dictMapUsage.entrySet()) {
            // String key = entry.getKey().toUpperCase();
            dictMapUsages+=entry.getKey().toUpperCase()+","+entry.getValue()+";";
        }
        dictMapUsages=dictMapUsages.substring(0,dictMapUsages.length()-1);
        //this.putAttribute("dictUsages",dictMapUsages);
        this.putAttribute("isAll","0");
        if (nonProdApplyBaseInfo.getBusinessUsage()!=null&&nonProdApplyBaseInfo.getBusinessUsage().split(",").length==dictMapUsages.split(";").length){
            this.putAttribute("isAll","1");
        }
        return forward("nonProdApplyDetail", nonProdApplyBaseInfo);
    }

    public String deleteNonProdApply(){
        SDO sdo = this.getSDO();
        List<String> ids = sdo.getIds();
        nonProdApplyApplication.deleteNonProdApplyBaseInfoByIds(ids);
        return success();
    }

    public String  publishDataToSap(){
        SDO sdo = this.getSDO();

       // System.out.println("id============"+sdo.getString("id"));
        nonProdApplyApplication.publishDataToSap(sdo.getString("id"));
        return success();
    }

    @SkipAuth
    @RequestMapping( value = "/getSapProductApply")
    @ResponseBody
    public HashMap<String, Object> getSapProductApply(@RequestBody ProdApplyFromSapVO prodApplyFromSapVO){
        //SDO sdo = this.getSDO();
        LOG.info("接收SAP产品申请数据.................");
        HashMap<String, Object> messageMap = new HashMap<>();
        messageMap.put("Message_Status","S");
        messageMap.put("Message_Text","成功");
        LOG.info("参数:=={}",prodApplyFromSapVO);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("TYPE", "S");
        resultMap.put("MESSAGE","成功");
        resultMap.put("businessType", "接收SAP产品数据");

        resultMap.put("businessId",prodApplyFromSapVO.getMatnr().length()>31?prodApplyFromSapVO.getMatnr().substring(0,31):prodApplyFromSapVO.getMatnr());
        resultMap.put("parameter", JSON.toJSONString(prodApplyFromSapVO));
        String message="";
        try {
            //resultMap.put("sequence", resultMap.get("row"));
            SapNonProdApplyDept sapNonProdApplyDept=nonProdApplyDeptApplication.getNonProdApplyDeptByMatnr(prodApplyFromSapVO.getMatnr());
            if (sapNonProdApplyDept!=null){
                message="产品编号"+prodApplyFromSapVO.getMatnr()+"已经存在！";
                messageMap.put("Message_Status","E");
                messageMap.put("Message_Text",message);
                resultMap.put("TYPE", "E");
             } else {
                message=nonProdApplyApplication.saveProdApplyFromSapVO(prodApplyFromSapVO);
                if (StringUtil.isNotBlank(message)){
                  resultMap.put("TYPE", "E");
                }
            }
             resultMap.put("MESSAGE",message);
        }catch (Exception e){
            messageMap.put("Message_Status","E");
            messageMap.put("Message_Text",e);
            resultMap.put("TYPE", "E");
            resultMap.put("MESSAGE",e.getMessage());
        }
        sapMutualEpLogApplication.saveSapMutualEpLog(resultMap);
        return messageMap;
    }
}


