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


import com.alibaba.fastjson.JSONObject;
import com.huigou.cache.DictUtil;
import com.huigou.topsun.base.bsnMessage.appliction.BsnMessageApplication;
import com.huigou.topsun.base.bsnMessage.domain.ActiveStatus;
import com.huigou.topsun.base.bsnMessage.domain.BsnMessageExecute;
import com.huigou.topsun.base.bsnMessage.domain.BsnMessageReject;
import com.huigou.topsun.base.bsnMessage.domain.BsnMessageSponsor;
import com.huigou.topsun.base.bsnMessage.repository.BsnMessageExecuteRepository;
import com.huigou.topsun.base.bsnMessage.repository.BsnMessageSponsorRepository;
import com.huigou.topsun.sap.common.DefaultHttpClient;
import com.huigou.topsun.sap.common.domain.EpResult;
import com.huigou.topsun.sap.common.domain.SapResult;
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.uasp.annotation.ControllerMapping;
import com.huigou.uasp.bmp.opm.application.OrgApplication;
import com.huigou.uasp.bmp.opm.domain.model.org.Org;
import com.huigou.uasp.client.CommonController;
import com.huigou.util.SDO;
import com.huigou.util.StringUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.persistence.Transient;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@ControllerMapping("/sapNonProdApplyNext")
public class NonProdApplyNextController extends CommonController {

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

    @Autowired
    NonProdApplyApplication nonProdApplyApplication;
    @Autowired
    NonProdApplyDeptApplication nonProdApplyDeptApplication;
    @Autowired
    BsnMessageApplication bsnMessageApplication;
    @Autowired
    BsnMessageSponsorRepository bsnMessageSponsorRepository;
    @Autowired
    BsnMessageExecuteRepository bsnMessageExecuteRepository;
    @Autowired
    OrgApplication orgApplication;
    @Autowired
    DefaultHttpClient defaultHttpClient;

    public String forwardNonProdApplyNext() {
        SDO sdo = this.getSDO();
        String id = sdo.getBizId();
//        this.putAttribute("active", ActiveStatus.UNFINISHED.getValue() );//定义流程环节的id
        if (StringUtil.isNotBlank(sdo.getString("prod"))){  //首页进入的产品信息 如果ID是传的ApplyDeptId
            SapNonProdApplyDept applyDept=nonProdApplyDeptApplication.getNonProdApplyDeptById(id);
            if (applyDept!=null){
               id=applyDept.getBaseInfoId();
            }
        }
        NonProdApplyBaseInfo nonProdApplyBaseInfo = nonProdApplyApplication.loadNonProdApplyBaseInfoById(id);
        nonProdApplyBaseInfo.setApplyType("0");
        this.putAttribute("applyType", "0");
        SapNonProdApplyDept nonProdApplyDept = nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(id);
        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");
        }
        if (nonProdApplyBaseInfo.getMaintenanceType().equals("modify")){
            nonProdApplyBaseInfo.setApplyType("1");
            this.putAttribute("applyType", "1");
        }  if (nonProdApplyBaseInfo.getMaintenanceType().equals("extend")){
            nonProdApplyBaseInfo.setApplyType("2");
            this.putAttribute("applyType", "2");

           // NonProdApplyBaseInfo sourceNonProdApplyBaseInfo=nonProdApplyApplication.loadNonProdApplyBaseInfoById(nonProdApplyBaseInfo.getSourceId());
            String  usedBusiness=nonProdApplyApplication.getChangeBusinessUsage(id,"扩展");
            //去掉当前的
            usedBusiness=usedBusiness.replaceAll(nonProdApplyBaseInfo.getBusinessUsage(),"");
            String []usages=usedBusiness.split(",");//sourceNonProdApplyBaseInfo.getBusinessUsage().split(",");

            nonProdApplyBaseInfo.setBusinessUsageSeled(usedBusiness);
            //String []exdusages=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());
                }
            }
*/
            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);
           // this.putAttribute("businessUsageSeledList",mapTmp);
           // this.putAttribute("businessUsageUnSeledList",unMapTmp);
        }
        int slen=0;
        if (StringUtil.isNotBlank(nonProdApplyBaseInfo.getBusinessUsage())){
            slen=nonProdApplyBaseInfo.getBusinessUsage().split(",").length;
        }
        this.putAttribute("busiLens",slen);
        if (nonProdApplyDept != null) {
            getBaseInfoAttrs(nonProdApplyBaseInfo, nonProdApplyDept);
            if (nonProdApplyBaseInfo.getDistribute()!=null){
                this.putAttribute("active",nonProdApplyBaseInfo.getDistribute());
            } else { // 未分发
                this.putAttribute("active",0);
            }
            if ("product".equals(nonProdApplyDept.getKind())){
                this.putAttribute("kind","product");
            } else{
                this.putAttribute("kind","materiel");
            }
            return forward("nonProdApplyNext", nonProdApplyDept);
        } else {
            this.putAttribute("active",0);
            return forward("nonProdApplyNext", nonProdApplyBaseInfo);
        }
    }

    //部门相关
    public String slicedDeptList() {
        SDO sdo = this.getSDO();
        String septString = sdo.getString("dept");
        if (StringUtil.isBlank(septString)){
            String id = sdo.getString("id");
            NonProdApplyBaseInfo nonProdApplyBaseInfo = nonProdApplyApplication.loadNonProdApplyBaseInfoById(id);
            septString = nonProdApplyBaseInfo.getBusinessUsage();
        }
//        String applyDeptId = sdo.getString("applyDeptId");
//        List<BsnMessage> bsnMessageAll = bsnMessageApplication.getBsnMessageByBusinessId(applyDeptId);
        List<String> deptList =new ArrayList<>();
        if (StringUtil.isNotBlank(septString)){
          deptList=Arrays.asList(septString.split(","));
        }
         Map<String, String> serviceusage = DictUtil.getDictionary("serviceusage");
        String deptId=sdo.getString("deptId");
        BsnMessageSponsor sponsor = bsnMessageSponsorRepository.findByBusinessId(deptId);
        List<HashMap<String, String>> list = new ArrayList<>();
        Map<String, List<HashMap<String, String>>> map = new HashMap<>(); // 用于存储结果的字典
        if (sponsor!=null) {
            List<BsnMessageExecute> executeLists = bsnMessageExecuteRepository.findAllByMessageSponsorId(sponsor.getId());
            String businessCode = sdo.getString("businessCode");
            // 用于存储结果的字典
             for (String key : deptList) {
                HashMap<String, String> resultMap = new HashMap<>();
                String value = serviceusage.get(key);
                resultMap.put("deptCode", key);
                resultMap.put("deptName", value);

                for (BsnMessageExecute executor : executeLists) {
                    if (key.equals(executor.getBusinessCode())) {
                        resultMap.put("userCode", executor.getTaskExecute());
                        Org org = orgApplication.loadMainOrgByPersonId(executor.getTaskExecute());
                        resultMap.put("userName", org.getName());
                        resultMap.put("active",executor.getActive().toString());
                        resultMap.put("updateDate", executor.getUpdateDate().toString().substring(0,19));
                        resultMap.put("finishedDate",executor.getFinishedDate()!=null?executor.getFinishedDate().toString().substring(0,19):"");
                        break;
                    }
                }
                list.add(resultMap);
            }
       } else {
            for (String key : deptList) {
                HashMap<String, String> resultMap = new HashMap<>();
                String value = serviceusage.get(key);
                resultMap.put("deptCode", key);
                resultMap.put("deptName", value);
                list.add(resultMap);
            }
        }
        map.put("Rows", list);
        return toResult(map);
    }

    /**
     * 保存 /提交
     */
    public String saveSapNonProdApplyDept() {
        SDO sdo = this.getSDO();
        if (StringUtil.isNotBlank(sdo.getString("maktx"))) {
            NonProdApplyBaseInfoQueryRequest query = new NonProdApplyBaseInfoQueryRequest();
            query.setMaktx(sdo.getString("maktx"));
            Map<String, Object> map=nonProdApplyApplication.slicedNonApplyBaseInfoByMaktx(query);
            List <Map <String,Object>>baseList=(List)map.get("Rows");
            sdo.putProperty("baseList",baseList);
        }
        Map<String, Object> map = nonProdApplyDeptApplication.saveSapNonProdApplyDept(sdo);
        return toResult(map);
    }

    /**
     * 领导确认和回退
     */
    public String confirmSapNonProdApplyDept() {
        SDO sdo = this.getSDO();
        Map<String, Object> map = nonProdApplyDeptApplication.confirmNonProdApplyDept(sdo);
        return toResult(map);
    }


    /**
     * 分发表单
     */
    public String distributeSapNonProdApplyDept() {
        SDO sdo = this.getSDO();
        nonProdApplyDeptApplication.distributeSapNonProdApplyDept(sdo);
        return success();
    }

    /**
     * 各业务部门填写收到的任务表单 （不用了）
     *
     * @return
     */
    public String fillInNonProdApplyDept() {
        SDO sdo = this.getSDO();
        String bizId = sdo.getBizId();
        String meId = sdo.getString("taskId");
        Map<String, Object> circulate = bsnMessageApplication.circulate(meId);
        this.putAttribute(circulate);
        SapNonProdApplyDept nonProdApplyDept = nonProdApplyDeptApplication.getNonProdApplyDeptById(bizId);
        if (nonProdApplyDept == null) {
            throw new RuntimeException("不存在该业务或未发布！");
        }
        NonProdApplyBaseInfo baseInfo = nonProdApplyApplication.loadNonProdApplyBaseInfoById(nonProdApplyDept.getBaseInfoId());
        if (circulate!=null&&circulate.get("deptCode")!=null) {
            nonProdApplyDept.setBusinessCode(circulate.get("deptCode").toString());
        }
         getBaseInfoAttrs(baseInfo,nonProdApplyDept);
        int slen=1;
        if (StringUtil.isNotBlank(baseInfo.getBusinessUsage())){
            slen=baseInfo.getBusinessUsage().split(",").length+1;
        }
        this.putAttribute("busiLens",slen);
        this.putAttribute("active",baseInfo.getDistribute());
        String businessCode=circulate.get("deptCode")!=null?circulate.get("deptCode").toString():"";
        switch (businessCode) {
            case "INIT_DPT": //推送SAP错误 产生的待办消息
                baseInfo.setApplyType("0");
                if (baseInfo.getMaintenanceType().equals("modify")) {
                    baseInfo.setApplyType("1");
                } else if  (baseInfo.getMaintenanceType().equals("extend")) {
                    baseInfo.setApplyType("2");
                }
                this.putAttribute("applyType",baseInfo.getApplyType());
                this.putAttribute("active",baseInfo.getDistribute());
                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);
                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);
               return forward("nonProdApplyNext", nonProdApplyDept);
            case "HYZY":
                baseInfo.setApplyType("0");
                if (baseInfo.getMaintenanceType().equals("modify")) {
                    baseInfo.setApplyType("1");
                } else if  (baseInfo.getMaintenanceType().equals("extend")) {
                    baseInfo.setApplyType("2");
                }
                this.putAttribute("applyType",baseInfo.getApplyType());
                this.putAttribute("active",baseInfo.getDistribute());
                Map <String,String>dictMapUsage2=DictUtil.getDictionary("serviceusage");
                String dictMapUsages2="";
                for (Map.Entry<String, String> entry: dictMapUsage2.entrySet()) {
                    // String key = entry.getKey().toUpperCase();
                    dictMapUsages2+=entry.getKey().toUpperCase()+","+entry.getValue()+";";
                }
                dictMapUsages=dictMapUsages2.substring(0,dictMapUsages2.length()-1);
                this.putAttribute("dictUsages",dictMapUsages);
                Map <String, String>unMapTmp2=new HashMap();
                for (Map.Entry<String, String> entry : dictMapUsage2.entrySet()) {
                    String key = entry.getKey().toUpperCase();
                    //  boolean isexists = false;
                    if (!"K".equals(key)) {
                        unMapTmp2.put(key, entry.getValue());
                    }
                }
                this.putAttribute("businessUsageUnSeledList",unMapTmp2);
                return forward("nonProdApplyNext", nonProdApplyDept);
            case "K":
                this.putAttribute("active",2); //已经分发的 填写基本数据
                this.putAttribute("applyType",3);
                return forward("nonProdApplyNext", nonProdApplyDept);
            case "C":
                return forward("nonProdApplyClass", nonProdApplyDept);
            case "V": //销售
               if (StringUtils.isNotBlank(nonProdApplyDept.getMatnr())) {
                  String url = "md/mdItem/queryBrandByItemCode/" + nonProdApplyDept.getMatnr();
                     Map map = new HashMap();
                try {
                    //{msg:"","code":"",data:{"code":"","name":}}
                    String result = defaultHttpClient.executeForEp(map, url);
                    EpResult epResult = JSONObject.parseObject(result, EpResult.class);
                    if ("200".equals(epResult.getCode())) {
                        if (epResult.getData()!=null){
                            nonProdApplyDept.setBrand(epResult.getData().getCode());
                            nonProdApplyDept.setBrandName(epResult.getData().getName());
                            nonProdApplyDept.setMvgr1(epResult.getData().getCode());
                        }
                    } else {
                        throw new RuntimeException("从EP查询品牌错误:" + epResult.getMsg());
                    }
                 } catch (IOException e) {
                    throw new RuntimeException("EP服务器无响应请稍后手动重试！error:" + e.getMessage());
                 }
               }
                return forward("nonProdApplySale", nonProdApplyDept);
            case "E":
                return forward("nonProdApplyPurchase", nonProdApplyDept);
            case "D":
                return forward("nonProdApplyMRP", nonProdApplyDept);
            case "A":
                return forward("nonProdApplyProduce", nonProdApplyDept);
            case "L":
                return forward("nonProdApplyStore", nonProdApplyDept);
            case "S":
                return forward("nonProdApplyWarehouse", nonProdApplyDept);
            case "Q":
                return forward("nonProdApplyMass", nonProdApplyDept);
            case "B":
                return forward("nonProdApplyFinancial", nonProdApplyDept);
            case "G":
                return forward("nonProdApplyCost", nonProdApplyDept);
        }
        return null;
    }

    public String slicedRejectCauseList(){
        SDO sdo = this.getSDO();
        String meId = sdo.getString("meId");
        List<BsnMessageReject> rejectAll = bsnMessageApplication.getRejectDetail(meId);
        return toResult(rejectAll);
    }

public void getBaseInfoAttrs(NonProdApplyBaseInfo baseInfo,SapNonProdApplyDept nonProdApplyDept){
        nonProdApplyDept.setBillCode(baseInfo.getBillCode());
        nonProdApplyDept.setStatusId(baseInfo.getStatusId());
        nonProdApplyDept.setPersonMemberName(baseInfo.getPersonMemberName());
        nonProdApplyDept.setFillinDate(baseInfo.getFillinDate());
        nonProdApplyDept.setMaintenanceType(baseInfo.getMaintenanceType());
        nonProdApplyDept.setBusinessUsage(baseInfo.getBusinessUsage());

        nonProdApplyDept.setId(nonProdApplyDept.getBaseInfoId());
        //物品总属性
        nonProdApplyDept.setGenericName(baseInfo.getGenericName());

        nonProdApplyDept.setApplicableStandard(baseInfo.getApplicableStandard());
        nonProdApplyDept.setBaseUnit(baseInfo.getBaseUnit());
        nonProdApplyDept.setSpecifications(baseInfo.getSpecifications());
        nonProdApplyDept.setMaterial(baseInfo.getMaterial());
        nonProdApplyDept.setDesign(baseInfo.getDesign());
        nonProdApplyDept.setSize(baseInfo.getSize());
        nonProdApplyDept.setBrand(baseInfo.getBrand());
        nonProdApplyDept.setBrandName(baseInfo.getBrandName());

        nonProdApplyDept.setMaterialUsage(baseInfo.getMaterialUsage());
        nonProdApplyDept.setItemAttributes(baseInfo.getItemAttributes());
        nonProdApplyDept.setDistribute(baseInfo.getDistribute());
        nonProdApplyDept.setKind(baseInfo.getKind());
        nonProdApplyDept.setCreatedDate(baseInfo.getCreatedDate());

        nonProdApplyDept.setMaktxRemEn(baseInfo.getMaktxRemEn());
        nonProdApplyDept.setMaktxRemZh(baseInfo.getMaktxRemZh());
        nonProdApplyDept.setTextDescription(baseInfo.getTextDescription());

        nonProdApplyDept.setBaseUnitName(baseInfo.getBaseUnitName());
    }

//    @EasySearch(queryName = "userNameSelect")
//    public Map<String, Object> queryResourceNameGroup(SDO sdo){
//        Integer intPage = sdo.getInteger("intPage", 1);
//        Integer pageSize = sdo.getInteger("pageSize",10);
//        PageRequest pageRequest = new PageRequest(intPage - 1, pageSize);
//        List<QuerySchemeField> fields =
//                Arrays.asList(new QuerySchemeField("id", "id", "hidden"),
//                        new QuerySchemeField("资源名称", "gxmc", "string", 200L),
//                        new QuerySchemeField("资源编码", "gxbm", "string", 100L),
//                        new QuerySchemeField("单位", "dw", "string", 100L),
//                        new QuerySchemeField("用量", "yl", "string", 100L),
//                        new QuerySchemeField("工作中心", "gzzx", "string", 100L));
//        EasySearchParse easySearchParse = new EasySearchParse();
//        easySearchParse.setFields(fields);
//        easySearchParse.setWidth(450L);
//        String processType = sdo.getString("paramValue");
////        List<Map<String, Object>> mapList = resourceFiledService.getResourceFieldValueListByProcess(processType);
//        MemEasySearcher<Map<String, Object>> memEasySearcher = new MemEasySearcherImpl<>();
//        Map<String, Object> model = memEasySearcher.search(mapList, easySearchParse, pageRequest, null);
//        return model;
//        return null;
//    }

    /**
     * 驳回
     * @return
     */
    public String rejectNonProdApplyDept() {
        SDO sdo = this.getSDO();
        nonProdApplyDeptApplication.rejectNonProdApplyDept(sdo);
        return success();
    }
}


