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


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huigou.cache.DictUtil;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.data.domain.model.Creator;
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.MaterialNameElement;
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.nonProdApply.repository.MaterialNameElementRepository;
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.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.bmp.doc.attachment.application.AttachmentApplication;
import com.huigou.uasp.bmp.doc.attachment.domain.model.Attachment;
import com.huigou.uasp.bmp.opm.domain.model.access.Role;
import com.huigou.uasp.bmp.opm.repository.org.RoleRepository;
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.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@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;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    private MaterialNameElementRepository materialNameElementRepository;
    @Resource
    private SapDictionaryApplication sapDictionaryApplication;
    @Autowired
    private AttachmentApplication attachmentApplication;

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

    public String forwardNonProdApplyList(){
        this.putAttribute("statusKindsList", BillStatus.getValidMap());
        List<String> roleIds = this.getOperator().getRoleIds();
        List<String> roleCodes = roleRepository.findAll(roleIds).stream().map(Role::getCode).collect(Collectors.toList());
        String roleCode = String.join(",", roleCodes);
        this.putAttribute("roleCode", roleCode);
        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");
                Map<String, String> unMapTmp = new HashMap();
                for (Map.Entry<String, String> entry : dictMapUsage.entrySet()) {
                    String key = entry.getKey().toUpperCase();
                    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()));

            if (StringUtil.isNotBlank(bizId)) {
                //复制正反面图片
                List<Attachment> frontAttachments = attachmentApplication.queryAttachments("frontPicture", bizId);
                List<Attachment> backAttachments = attachmentApplication.queryAttachments("backPicture", bizId);
                if (frontAttachments.size() > 0) {
                    Attachment attachment = frontAttachments.get(0);
                    Attachment attachmentNew = new Attachment();
                    ClassHelper.copyProperties(attachment, attachmentNew);
                    attachmentNew.setId(null);
                    attachmentNew.setBizId(nonProdApplyBaseInfo.getAttbizId());
                    Creator creator = attachmentNew.getCreator();
                    creator.setCreatedDate(new Date());
                    attachmentNew.setCreator(creator);
                    attachmentApplication.saveAttachment(attachmentNew);
                    this.putAttribute("frontPicturePath", StringUtil.encode(attachment.getPath()));
                }
                if (backAttachments.size() > 0) {
                    Attachment attachment = backAttachments.get(0);
                    Attachment attachmentNew = new Attachment();
                    ClassHelper.copyProperties(attachment, attachmentNew);
                    attachmentNew.setId(null);
                    attachmentNew.setBizId(nonProdApplyBaseInfo.getAttbizId());
                    Creator creator = attachmentNew.getCreator();
                    creator.setCreatedDate(new Date());
                    attachmentNew.setCreator(creator);
                    attachmentApplication.saveAttachment(attachmentNew);
                    this.putAttribute("backPicturePath", StringUtil.encode(attachment.getPath()));
                }
            }

            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);
        //处理维护类型
        //新建-待填报 0 新建-已办结 1 变更-待填报 2 变更-已办结 3 扩展-待填报 4 扩展-已办结 5
        if (StringUtil.isNotBlank(queryRequest.getMaintainTypeDetail())){
            if ("0".equals(queryRequest.getMaintainTypeDetail())){
                queryRequest.setMaintenanceType("new");
                queryRequest.setDistribute(0);
            }else if ("1".equals(queryRequest.getMaintainTypeDetail())) {
                queryRequest.setMaintenanceType("new");
                queryRequest.setDistribute(2);
            } else if ("2".equals(queryRequest.getMaintainTypeDetail())) {
                queryRequest.setMaintenanceType("modify");
                queryRequest.setDistribute(0);
            } else if ("3".equals(queryRequest.getMaintainTypeDetail())) {
                queryRequest.setMaintenanceType("modify");
                queryRequest.setDistribute(2);
            }else if ("4".equals(queryRequest.getMaintainTypeDetail())) {
                queryRequest.setMaintenanceType("extend");
                queryRequest.setDistribute(0);
            }else if ("5".equals(queryRequest.getMaintainTypeDetail())) {
                queryRequest.setMaintenanceType("extend");
                queryRequest.setDistribute(2);
            }
        }
        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);
            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);
        }
        if (StringUtil.isNotBlank(nonProdApplyBaseInfo.getAttbizId())){
            List<Attachment> frontAttachments = attachmentApplication.queryAttachments("frontPicture", nonProdApplyBaseInfo.getAttbizId());
            List<Attachment> backAttachments = attachmentApplication.queryAttachments("backPicture", nonProdApplyBaseInfo.getAttbizId());

            if (frontAttachments.size() > 0) {
                Attachment attachment = frontAttachments.get(0);
                this.putAttribute("frontPicturePath", StringUtil.encode(attachment.getPath()));
            }
            if (backAttachments.size() > 0) {
                Attachment attachment = backAttachments.get(0);
                this.putAttribute("backPicturePath", StringUtil.encode(attachment.getPath()));
            }
        }

        Map <String,String>dictMapUsage=DictUtil.getDictionary("serviceusage");
        String dictMapUsages="";
        for (Map.Entry<String, String> entry: dictMapUsage.entrySet()) {
            dictMapUsages+=entry.getKey().toUpperCase()+","+entry.getValue()+";";
        }
        dictMapUsages=dictMapUsages.substring(0,dictMapUsages.length()-1);
        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("CODE","S");
        messageMap.put("MSG","成功");
        messageMap.put("DATA","");
        LOG.info("参数:=={}", JSONUtil.toString(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", JSONUtil.toString(prodApplyFromSapVO));
        String message="";
        try {
            //resultMap.put("sequence", resultMap.get("row"));
            //根据数据字典接口。查询物料组大类
            List<Map<String, String>> mapList = sapDictionaryApplication.getSapDictionary("MATKL");
            //获取物料组编码
            String matkl = prodApplyFromSapVO.getMatkl();
            String matklType = "";
            String matklTypeName = "";
            if (matkl.length() > 3){
                //截取前三位，是物料组大类编码
                String substring = matkl.substring(0, 3);
                //获取物料组名称
                List<Map<String, String>> matkl1 = mapList
                        .stream()
                        .filter(map -> substring.equals(map.get("MATKL")))
                        .collect(Collectors.toList());
                if (matkl1.size() > 0){
                    matklType = matkl1.get(0).get("MATKL");
                    matklTypeName = matkl1.get(0).get("WGBEZ");
                }
            }else {
                matklType = matkl;
                matklTypeName = prodApplyFromSapVO.getMatklName();
            }

            List<SapNonProdApplyDept> sapNonProdApplyDepts=nonProdApplyDeptApplication.getNonProdApplyDeptByMatnr(prodApplyFromSapVO.getMatnr());
            if (!CollectionUtils.isEmpty(sapNonProdApplyDepts)){
                for (SapNonProdApplyDept sapNonProdApplyDept : sapNonProdApplyDepts) {
                    //更新产品名称、物料组、单位、规格
                    sapNonProdApplyDept.setMaktx(prodApplyFromSapVO.getMaktx());
                    sapNonProdApplyDept.setMaktxRemZh(prodApplyFromSapVO.getMaktxRemZh());
                    sapNonProdApplyDept.setMeins(prodApplyFromSapVO.getMeins());
                    sapNonProdApplyDept.setMeinsName(prodApplyFromSapVO.getMeinsName());
                    sapNonProdApplyDept.setMatkl(prodApplyFromSapVO.getMatkl());
                    sapNonProdApplyDept.setMatklName(prodApplyFromSapVO.getMatklName());
                    sapNonProdApplyDept.setGroes(prodApplyFromSapVO.getGroes());
                    sapNonProdApplyDept.setMaktxEn(prodApplyFromSapVO.getMaktxEn());
                    sapNonProdApplyDept.setMatklType(matklType);
                    sapNonProdApplyDept.setMatklTypeName(matklTypeName);
                    nonProdApplyDeptApplication.save(sapNonProdApplyDept);
                }
//                message="产品编号"+prodApplyFromSapVO.getMatnr()+"已经存在！";
//                messageMap.put("CODE","E");
//                messageMap.put("MSG",message);
//                resultMap.put("TYPE", "E");
             } else {
                SapNonProdApplyDept sapNonProdApplyDept = new SapNonProdApplyDept();
                sapNonProdApplyDept.setMatklType(matklType);
                sapNonProdApplyDept.setMatklTypeName(matklTypeName);
                message=nonProdApplyApplication.saveProdApplyFromSapVO(prodApplyFromSapVO,sapNonProdApplyDept);
                if (StringUtil.isNotBlank(message)){
                  resultMap.put("TYPE", "E");
                }
            }
             resultMap.put("MESSAGE",message);
        }catch (Exception e){
            messageMap.put("CODE","E");
            messageMap.put("MSG",e);
            resultMap.put("TYPE", "E");
            resultMap.put("MESSAGE",e.getMessage());
        }
        sapMutualEpLogApplication.saveSapMutualEpLog(resultMap);
        return messageMap;
    }

    public String showMaterialNameElement(){
        SDO sdo = this.getSDO();
        String billCode = sdo.getString("billCode");
        MaterialNameElement materialNameElement = materialNameElementRepository.findByBillCode(billCode);
        if (materialNameElement==null){
            materialNameElement=new MaterialNameElement();
            materialNameElement.setBillCode(billCode);
        }
        return forward("materialNameElement",materialNameElement);
    }

    public String saveMaterialNameElement(){
        SDO sdo = this.getSDO();
        MaterialNameElement materialNameElement = sdo.toObject(MaterialNameElement.class);
        materialNameElementRepository.save(materialNameElement);
        return success();
    }
}


