package com.hzya.frame.u9c.warehouse.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.u9c.util.CrmUtil;
import com.hzya.frame.u9c.warehouse.entity.VU9cWarehouseEntity;
import com.hzya.frame.u9c.warehouse.dao.IVU9cWarehouseDao;
import com.hzya.frame.u9c.warehouse.service.IVU9cWarehouseService;
import org.springframework.stereotype.Service; 
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
import com.hzya.frame.basedao.service.impl.BaseService;

import java.util.List;

/**
 * (VU9cWarehouse)表服务实现类
 *
 * @author makejava
 * @since 2023-10-26 10:36:09
 */
@Service("vU9cWarehouseService")
public class VU9cWarehouseServiceImpl extends BaseService<VU9cWarehouseEntity, String> implements IVU9cWarehouseService {
     
    private IVU9cWarehouseDao vU9cWarehouseDao;
    
    @Autowired
	public void setVU9cWarehouseDao(IVU9cWarehouseDao dao) {
		this.vU9cWarehouseDao = dao;
		this.dao = dao;
	}
	//上一次同步时间
	private String LAST_SYNCHRONISED_TIME = "";
	@Override
	public String sendU9cWarehouseToCRM() {
		JSONObject resultObj = new JSONObject();
		//获取待推送的U9c
		VU9cWarehouseEntity category = new VU9cWarehouseEntity();
		if (StrUtil.isBlank(LAST_SYNCHRONISED_TIME)) {
			LAST_SYNCHRONISED_TIME = DateUtil.now();
		}
		//暂存时间
		String temp_time = LAST_SYNCHRONISED_TIME;
		category.setUpdateTime(temp_time);
		List<VU9cWarehouseEntity> VU9cWarehouseEntityList = vU9cWarehouseDao.getu9cWarehouse(category);
		if(VU9cWarehouseEntityList.size()>0){
			for(VU9cWarehouseEntity itemmaster : VU9cWarehouseEntityList){
				LAST_SYNCHRONISED_TIME = DateUtil.now();
				try {
					String permanentCode = "FSUID_DB2D1775B48BCDF893538F8CAB2A0EC7";
					JSONObject tokenObj = CrmUtil.getToken(permanentCode);
					String id = itemmaster.getId();
					//杭州恒华科技有限公司
					String orgCode = itemmaster.getOrgCode();
					String field_ddl10__c = "";
					if(StrUtil.isNotEmpty(orgCode)){
						switch (orgCode){
							//todo 2023年12月18日14:03:28CRM实施与U9实施讨论决定。将博华库存推送到恒华
							//博华推博华
							case "10"://博华
								field_ddl10__c = "a2lmNhpo0";
								break;
							case "1001"://恒华
								field_ddl10__c = "cD2b3f";
								break;
							case "1002"://杭州华耀商贸有限公司
								field_ddl10__c = "sl2qOPMpO";
								break;
							case "1004"://杭州华耀商贸有限公司
								field_ddl10__c = "sl2qOPMpO";
								break;
							case "1003"://杭州胡记食品有限公司
								field_ddl10__c = "eq8LyNWe1";
								break;
							default:
								break;

						}
					}
					//通过OA主键查询CRM该库存是否存在，如果存在则更新，如果不存在则进新增
					String code = itemmaster.getCode();
					String ctmId = getCrmWarehouse(tokenObj,permanentCode,id,itemmaster,field_ddl10__c);
					//拼接传递参数
					JSONObject main = new JSONObject();
					main.put("corpAccessToken",tokenObj.getString("corpAccessToken"));//token
					main.put("corpId",tokenObj.getString("corpId"));//公司
					main.put("currentOpenUserId",permanentCode);//操作员主键
					main.put("duplicateCheck",true);
					main.put("triggerWorkFlow",true);
					JSONObject data = new JSONObject();
					data.put("editFlag","1");//状态 暂时默认1
					data.put("name",itemmaster.getName());//分类名称
					data.put("category_code",itemmaster.getCode());//分类编码
					data.put("orderField","1");//排序号 暂时默认1
					main.put("data",data);
					JSONObject object_data = new JSONObject();
					JSONArray owner = new JSONArray();
					owner.add(permanentCode);

					object_data.put("dataObjectApiName","object_1nkMM__c");
					object_data.put("owner",owner);
					object_data.put("field_ddl10__c",field_ddl10__c);//组织
					String supId = itemmaster.getInvId();
//				String proId = CrmUtil.getProIdBySupId(supId,tokenObj.getString("corpAccessToken"),permanentCode,tokenObj.getString("corpId"));
					String proId = CrmUtil.getProIdByCode(itemmaster.getCode(),field_ddl10__c,tokenObj.getString("corpAccessToken"),permanentCode,tokenObj.getString("corpId"));
					object_data.put("field_qAQj5__c",proId);//产品主键
//				object_data.put("field_qAQj5__c","65386572741efa00012ca6c6");//产品主键
//				object_data.put("field_K7oi6__c","");//规格
					object_data.put("field_MM6hR__c",itemmaster.getUnit());//库存计量单位
					object_data.put("field_xkvpd__c",itemmaster.getBatch());//批号
					object_data.put("field_5ugda__c",itemmaster.getInvAvailability());//可用库存
					object_data.put("field_b1j2M__c",itemmaster.getInvStock());//实际库存
					object_data.put("field_r169q__c",itemmaster.getReserveQuantity());//库存预留量
					object_data.put("field_u4s12__c",itemmaster.getWarehouseName());//仓库
					object_data.put("field_2JAJ3__c",itemmaster.getAllocation());//货位
					object_data.put("field_6x27n__c",itemmaster.getId());//U9C库存ID
					object_data.put("field_QO1ic__c",itemmaster.getCode());//料品编码
					data.put("object_data",object_data);
					String apiCode = "";
					if(StrUtil.isEmpty(ctmId)){
						apiCode = "8000090009";
					}else{//更新
						object_data.put("_id",ctmId);
	//					object_data.put("_id","654366aa6de7a000013a8245");
						apiCode = "8000090010";
					}
					resultObj = CrmUtil.sendU9cTOCrmEsb(main.toString(),apiCode);
					String errorDescription = resultObj.getString("errorDescription");
					if(null != errorDescription){
						if("success".equals(errorDescription)){
							String dataId = resultObj.getString("dataId");
							if(StrUtil.isNotEmpty(dataId)){
								logger.info("更新CRM库存信息成功："+dataId);
							}
						}
					}

					logger.info(resultObj.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return resultObj.toString();
	}

	public String getCrmWarehouse(JSONObject tokenObj, String permanentCode,String id,VU9cWarehouseEntity itemmaster,String org) {
		JSONObject main = new JSONObject();
		main.put("corpAccessToken",tokenObj.getString("corpAccessToken"));//token
		main.put("corpId",tokenObj.getString("corpId"));//公司
		main.put("currentOpenUserId",permanentCode);//操作员主键
		JSONObject data = new JSONObject();
		data.put("dataObjectApiName","object_1nkMM__c");
		JSONObject search_query_info = new JSONObject();
		search_query_info.put("offset",0);
		search_query_info.put("limit",2);
		JSONArray filters = new JSONArray();
		JSONObject filtersObj = new JSONObject();
		filtersObj.put("field_name","field_QO1ic__c");//编码
		filtersObj.put("field_values",itemmaster.getCode());
		filtersObj.put("operator","EQ");

		JSONObject filtersObjOrg = new JSONObject();
		filtersObjOrg.put("field_name","field_ddl10__c");//组织
		filtersObjOrg.put("field_values",org);
		filtersObjOrg.put("operator","EQ");

		JSONObject filtersLife = new JSONObject();
		filtersLife.put("field_name","life_status");//生命状态
		filtersLife.put("field_values","normal");
		filtersLife.put("operator","EQ");


		if(StrUtil.isNotEmpty(itemmaster.getWarehouseName())){
			JSONObject filtersObjWare = new JSONObject();
			filtersObjWare.put("field_name","field_u4s12__c");//仓库
			filtersObjWare.put("field_values",itemmaster.getWarehouseName());
			filtersObjWare.put("operator","EQ");
			filters.add(filtersObjWare);
		}

		if(StrUtil.isNotEmpty(itemmaster.getBatch())){
			JSONObject filtersObjBatch = new JSONObject();
			filtersObjBatch.put("field_name","field_xkvpd__c");//批号
			filtersObjBatch.put("field_values",itemmaster.getBatch());
			filtersObjBatch.put("operator","EQ");
			filters.add(filtersObjBatch);
		}


		if(StrUtil.isNotEmpty(itemmaster.getAllocation())){
			JSONObject filtersObjAll = new JSONObject();
			filtersObjAll.put("field_name","field_2JAJ3__c");//货位
			filtersObjAll.put("field_values",itemmaster.getAllocation());
			filtersObjAll.put("operator","EQ");
			filters.add(filtersObjAll);
		}





		filters.add(filtersObj);
		filters.add(filtersObjOrg);
		search_query_info.put("filters",filters);
		data.put("search_query_info",search_query_info);
		main.put("data",data);
		String apiCode = "8000090011";
		JSONObject resultObj = CrmUtil.sendU9cTOCrmEsb(main.toString(),apiCode);
		JSONObject resultData = resultObj.getJSONObject("data");
		JSONArray dataList = resultData.getJSONArray("dataList");
		if(null != dataList && dataList.size() > 0 ){
			Object obj = dataList.get(0);
			JSONObject warehouse = JSON.parseObject(obj.toString());
			return warehouse.getString("_id");
		}
    	return "";
	}
}
