package com.hzya.frame.u9c.saledeliver.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.saledeliver.dao.IVU9cSaledeliverDetailsDao;
import com.hzya.frame.u9c.saledeliver.entity.VU9cSaledeliverDetailsEntity;
import com.hzya.frame.u9c.saledeliver.entity.VU9cSaledeliverEntity;
import com.hzya.frame.u9c.saledeliver.dao.IVU9cSaledeliverDao;
import com.hzya.frame.u9c.saledeliver.service.IVU9cSaledeliverService;
import com.hzya.frame.u9c.util.CrmUtil;
import com.hzya.frame.web.exception.BaseSystemException;
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.Date;
import java.util.List;
import java.util.UUID;

/**
 * (VU9cSaledeliver)表服务实现类
 *
 * @author makejava
 * @since 2023-10-26 11:29:53
 */
@Service("vU9cSaledeliverService")
public class VU9cSaledeliverServiceImpl extends BaseService<VU9cSaledeliverEntity, String> implements IVU9cSaledeliverService {
     
    private IVU9cSaledeliverDao vU9cSaledeliverDao;
    @Autowired
    private IVU9cSaledeliverDetailsDao U9cSaledeliverDetailsDao;

    @Autowired
	public void setVU9cSaledeliverDao(IVU9cSaledeliverDao dao) {
		this.vU9cSaledeliverDao = dao;
		this.dao = dao;
	}
	//上一次同步时间
	private String LAST_SYNCHRONISED_TIME = "";
	private String LAST_SYNCHRONISED_TIME_UPDATE = "";
	@Override
	public String sendU9cSaledeliverToCRM() {
		//获取待推送的U9c
		VU9cSaledeliverEntity category = new VU9cSaledeliverEntity();
		if (StrUtil.isBlank(LAST_SYNCHRONISED_TIME)) {
			LAST_SYNCHRONISED_TIME = DateUtil.now();
		}
		//暂存时间
		//暂存时间
		String temp_time = LAST_SYNCHRONISED_TIME;
		category.setUpdatetime(temp_time);
		List<VU9cSaledeliverEntity> VU9cSaledeliverEntityList = vU9cSaledeliverDao.getu9cSaledeliver(category);
		if(VU9cSaledeliverEntityList.size()>0){
			for(VU9cSaledeliverEntity itemmaster : VU9cSaledeliverEntityList){
				try {
					LAST_SYNCHRONISED_TIME = DateUtil.now();
					String crmId = itemmaster.getCrmId();
					String permanentCode = itemmaster.getOperatorsId();
//				String permanentCode = "FSUID_DB2D1775B48BCDF893538F8CAB2A0EC7";
					JSONObject tokenObj = CrmUtil.getToken(CrmUtil.MANAGERCODE);
					//拼接传递参数
					JSONObject main = new JSONObject();
					main.put("corpAccessToken",tokenObj.getString("corpAccessToken"));//token
					main.put("corpId",tokenObj.getString("corpId"));//公司
					main.put("currentOpenUserId",permanentCode);//操作员主键// todo 默认了操作员ID 等员工对接完成之后实际传入
					main.put("duplicateCheck",true);
					JSONObject data = new JSONObject();
					JSONObject object_data = new JSONObject();
//				object_data.put("name",itemmaster.getBillCode());//发货单编号
					JSONArray ownerArr = new JSONArray();

					ownerArr.add(permanentCode);
					object_data.put("owner",ownerArr);//创建人
					object_data.put("dataObjectApiName","DeliveryNoteObj");//接口名称
//					object_data.put("sales_order_id",itemmaster.getSalesOrderId());//销售订单主键 //
					object_data.put("field_W7k8T__c",itemmaster.getSrcDocTransType());// 来源单据类型
					object_data.put("field_dp6ZV__c",itemmaster.getSoOrder()); //来源单据单号
					object_data.put("field_6u2rk__c",itemmaster.getTotalMoneyTC()); //发货金额 --- 含税金额
					object_data.put("field_5gwye__c",itemmaster.getBillCode()); //U9发货单号
					object_data.put("field_J3s50__c",itemmaster.getAddress()); //收货联系地址
					object_data.put("field_44TwV__c",itemmaster.getLinkman()); //收货联系人
					object_data.put("field_s0L0r__c",itemmaster.getPhone()); //收货联系电话
					if(StrUtil.isNotEmpty(crmId)){
						object_data.put("_id",crmId); //发货单主键
					}
					String orgCode = itemmaster.getOrgCode();
					String field_0alrS__c = "";
					if(StrUtil.isNotEmpty(orgCode)){
						switch (orgCode){
							case "1001"://杭州恒华科技有限公司
								field_0alrS__c = "cD2b3f";
								break;
							case "1002"://杭州华耀商贸有限公司
								field_0alrS__c = "sl2qOPMpO";
								break;
							case "1004"://诚艺传递华耀
								field_0alrS__c = "sl2qOPMpO";
								break;
							case "1003"://杭州胡记食品有限公司
								field_0alrS__c = "eq8LyNWe1";
								break;
							default:
								break;

						}
					}
					object_data.put("field_0alrS__c",field_0alrS__c); //组织
					//通过客户名称查询客户主键
					String custName = itemmaster.getCustName();
					String accountId = CrmUtil.getCustIdByCustName(custName,tokenObj.getString("corpAccessToken"),permanentCode,tokenObj.getString("corpId"));
					object_data.put("account_id",accountId);//客户
					object_data.put("field_1UjHy__c",itemmaster.getBillDate());//单据日期

					String  delivery_date = itemmaster.getShipmentTime();
					if(StrUtil.isNotEmpty(delivery_date)){
						object_data.put("delivery_date",com.hzya.frame.dateutil.DateUtil.dateStrToLong(itemmaster.getShipmentTime()));//发货日期
					}
					JSONObject details = new JSONObject();
					data.put("object_data",object_data);
					data.put("details",details);
					//获取明细信息
					VU9cSaledeliverDetailsEntity invDetails = new VU9cSaledeliverDetailsEntity();
					invDetails.setSalesOrderId(itemmaster.getSalesOrderId());
					invDetails.setMainId(itemmaster.getId());
					List<VU9cSaledeliverDetailsEntity> invDetailsList = U9cSaledeliverDetailsDao.getu9cSaledeliverDetails(invDetails);
					JSONArray deliveryNoteProduct = new JSONArray();
					for(VU9cSaledeliverDetailsEntity d : invDetailsList){
						JSONObject deliveryNoteProductObj = new JSONObject();
						long _id = UUID.randomUUID().getMostSignificantBits();
						deliveryNoteProductObj.put("_id",String.valueOf(_id));// 明细ID 自动生成
	//					deliveryNoteProductObj.put("_id",d.getId());// 明细ID 自动生成
						deliveryNoteProductObj.put("field_Rc82I__c",d.getRowId());// 来源ID
						deliveryNoteProductObj.put("sales_order_id",d.getSalesOrderId());// 销售订单主键
						String supId = d.getCrmProId();
	//					String proId = CrmUtil.getProIdBySupId(supId,tokenObj.getString("corpAccessToken"),permanentCode,tokenObj.getString("corpId"));
						deliveryNoteProductObj.put("product_id",supId);// 产品ID
						deliveryNoteProductObj.put("field_Xjo2j__c",d.getStorageLocationName());//发货仓库
						deliveryNoteProductObj.put("field_h9puj__c",d.getPeriod());//保质期
						deliveryNoteProductObj.put("field_F6iOS__c",d.getBatch());//批号
						deliveryNoteProductObj.put("sales_order_product_id",d.getSalesOrderProductId());//  订单产品主键（CRM销售订单的行ID）
						deliveryNoteProductObj.put("delivery_num",d.getNum());// 发货数量
						deliveryNoteProductObj.put("order_product_amount",d.getOrderByQtyTU());// 订单产品数量
						String field_ci5By__c = d.getTotalMoneyTC();
						if(StrUtil.isEmpty(d.getTotalMoneyTC()) || "0.0000".equals(d.getTotalMoneyTC())){
							field_ci5By__c = "0";
	//						field_ci5By__c = "1111.0000";
						}
						deliveryNoteProductObj.put("field_ci5By__c",field_ci5By__c);// 发货金额
	//					deliveryNoteProductObj.put("field_ci5By__c","1.00");// 发货金额
						String field_rz9y2__c = d.getShipConfirmDate();
						if(StrUtil.isNotEmpty(field_rz9y2__c)){
	//						Date field_rz9y2__cDate = DateUtil.parse(field_rz9y2__c,"yyyy-MM-dd HH:mm:ss");
							deliveryNoteProductObj.put("field_rz9y2__c", com.hzya.frame.dateutil.DateUtil.dateStrToLong(field_rz9y2__c));// 发货日期
						}
						deliveryNoteProduct.add(deliveryNoteProductObj);
					}
					details.put("DeliveryNoteProductObj",deliveryNoteProduct);
					main.put("data",data);
					String apiCode = "8000090003";
					if(StrUtil.isEmpty(crmId)){
						apiCode = "8000090003";
					}else{
						apiCode = "8000090015";
						//如果想要修改CRM数据需要先解锁数据
						String r = CrmUtil.unLockAndLock("8000090016","DeliveryNoteObj",crmId,tokenObj.getString("corpAccessToken"),CrmUtil.MANAGERCODE,tokenObj.getString("corpId"));
						logger.info("发货单解锁"+r);
					}
					//推送数据到CRM进行新增或修改
					JSONObject resultObj = CrmUtil.sendU9cTOCrmEsb(main.toString(),apiCode);
					//todo CRM傅佳敏提出 不管任何原因修改失败都需要再次锁定
					if(StrUtil.isNotEmpty(crmId)){
						//修改完数据之后需要再次锁定
						String r = CrmUtil.unLockAndLock("8000090017","DeliveryNoteObj",crmId,tokenObj.getString("corpAccessToken"),CrmUtil.MANAGERCODE,tokenObj.getString("corpId"));
						logger.info("发货单锁定"+r);
					}
					if(null != resultObj ){
						String dataId = resultObj.getString("dataId");
						String errorDescription = resultObj.getString("errorDescription");
						if("success".equals(errorDescription)){
							if(StrUtil.isNotEmpty(dataId)){
								itemmaster.setDataId(dataId);
								vU9cSaledeliverDao.updateCrmId(itemmaster);
							}
						}
					}else{
						LAST_SYNCHRONISED_TIME = DateUtil.now();
						if(StrUtil.isEmpty(crmId)){
							itemmaster.setDataId("系统错误，请联系管理员");
							vU9cSaledeliverDao.updateCrmId(itemmaster);
						}
						new BaseSystemException("系统错误，请联系管理员");
					}
					logger.info("发货单返回信息：{}",resultObj);
				} catch (Exception e) {
					LAST_SYNCHRONISED_TIME = DateUtil.now();
					logger.info("发货单错误，错误信息为：{}",e.getMessage());
					logger.info("发货单错误，发货单信息为：{}",JSON.toJSONString(itemmaster));
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	/**
	 *
	 * @content 将删除的出货单同步删除CRM
	 * @author makejava
	 * @date 2024/1/10 0010 10:18
	 *
	 */
    @Override
    public void sendU9cSaledeliverToCRMOfDetele() {
		VU9cSaledeliverEntity category = new VU9cSaledeliverEntity();
		List<VU9cSaledeliverEntity> VU9cSaledeliverEntityList = vU9cSaledeliverDao.getu9cSaledeliverForDelete(category);
		if(null != VU9cSaledeliverEntityList && VU9cSaledeliverEntityList.size()>0){
			for(VU9cSaledeliverEntity entity : VU9cSaledeliverEntityList){
				String state = "2";
				String permanentCode = "FSUID_DB2D1775B48BCDF893538F8CAB2A0EC7";
				JSONObject tokenObj = CrmUtil.getToken(CrmUtil.MANAGERCODE);
				//拼接传递参数
				try {
					JSONObject main = new JSONObject();
					main.put("corpAccessToken",tokenObj.getString("corpAccessToken"));//token
					main.put("corpId",tokenObj.getString("corpId"));//公司
					main.put("currentOpenUserId",permanentCode);//操作员主键// todo 默认了操作员ID 等员工对接完成之后实际传入
					main.put("duplicateCheck",true);
					String crmId = entity.getCrmId();
					if(StrUtil.isNotEmpty(crmId)){
						JSONObject data = new JSONObject();
						main.put("data",data);
						data.put("object_data_id",crmId);
						data.put("dataObjectApiName","DeliveryNoteObj");
						state = "1";
						String apiCode = "8000090018";
						//发货单解锁
						String r = CrmUtil.unLockAndLock("8000090016","DeliveryNoteObj",crmId,tokenObj.getString("corpAccessToken"),CrmUtil.MANAGERCODE,tokenObj.getString("corpId"));
						logger.info("发货单解锁"+r);
						//推送数据到CRM进行新增或修改
						JSONObject resultObj = CrmUtil.sendU9cTOCrmEsb(main.toString(),apiCode);
						if(null != resultObj ){
							String errorDescription = resultObj.getString("errorDescription");
							if(!"success".equals(errorDescription)){
								state = "2";
							}
						}else{
							state = "2";
						}
					}
				} finally {
					//修改删除状态
					entity.setState(state);
					vU9cSaledeliverDao.updateDeleteState(entity);
				}
			}
		}
    }
	/**
	 *
	 * @content 将实际收货数量更新到CRM
	 * @author javaboy
	 * @date 2024/1/11 0011 9:34
	 *
	 */
    @Override
    public void sendU9cSaledeliverToCRMOfUpdate() {
//获取待推送的U9c
		VU9cSaledeliverEntity category = new VU9cSaledeliverEntity();
		if (StrUtil.isBlank(LAST_SYNCHRONISED_TIME_UPDATE)) {
			LAST_SYNCHRONISED_TIME_UPDATE = DateUtil.now();
		}
		//暂存时间
		String temp_time = LAST_SYNCHRONISED_TIME_UPDATE;
		category.setUpdatetime(temp_time);
		List<VU9cSaledeliverEntity> VU9cSaledeliverEntityList = vU9cSaledeliverDao.getu9cSaledeliverForUpdate(category);
		if(VU9cSaledeliverEntityList.size()>0) {
			for (VU9cSaledeliverEntity itemmaster : VU9cSaledeliverEntityList) {
				LAST_SYNCHRONISED_TIME_UPDATE = DateUtil.now();
				try {
					String permanentCode = "FSUID_DB2D1775B48BCDF893538F8CAB2A0EC7";
					JSONObject tokenObj = CrmUtil.getToken(CrmUtil.MANAGERCODE);
					//拼接传递参数
					JSONObject main = new JSONObject();
					main.put("corpAccessToken",tokenObj.getString("corpAccessToken"));//token
					main.put("corpId",tokenObj.getString("corpId"));//公司
					main.put("currentOpenUserId",permanentCode);//操作员主键// todo 默认了操作员ID 等员工对接完成之后实际传入
					JSONObject data = new JSONObject();
					JSONObject object_data = new JSONObject();
					String id = itemmaster.getCrmId();
					object_data.put("_id",id);
					object_data.put("dataObjectApiName","ReturnedGoodsInvoiceObj");
					//获取明细数据，并组装数据
					VU9cSaledeliverEntity deteils = new VU9cSaledeliverEntity();
					deteils.setId(id);
					JSONObject detailsObj = new JSONObject();
					JSONArray ReturnedGoodsInvoiceProductObj = new JSONArray();
					List<VU9cSaledeliverEntity> VU9cSaledeliverEntityDetailsList = vU9cSaledeliverDao.getu9cSaledeliverForUpdateDetails(deteils);
					if(VU9cSaledeliverEntityDetailsList.size()>0){
						for(VU9cSaledeliverEntity VU9cSaledeliverEntityDetails : VU9cSaledeliverEntityDetailsList){
							JSONObject body = new JSONObject();
							String _id = VU9cSaledeliverEntityDetails.getCrmId();
							String RcvQtyTU = VU9cSaledeliverEntityDetails.getRcvQtyTU();
							body.put("_id",_id);
							body.put("field_HE24V__c",RcvQtyTU);
							ReturnedGoodsInvoiceProductObj.add(body);
						}
					}else{
						//如果没有明细信息跳过当前循环
						continue;
					}
					detailsObj.put("ReturnedGoodsInvoiceProductObj",ReturnedGoodsInvoiceProductObj);
					data.put("object_data",object_data);
					main.put("data",data);
					data.put("details",detailsObj);
					String apiCode = "8000090020";
					//退货单解锁
					String unLockAndLock = CrmUtil.unLockAndLock("8000090016","ReturnedGoodsInvoiceObj",itemmaster.getCrmId(),tokenObj.getString("corpAccessToken"),CrmUtil.MANAGERCODE,tokenObj.getString("corpId"));
					logger.info("退货单解锁"+unLockAndLock);
					//推送数据到CRM修改
					JSONObject resultObj = CrmUtil.sendU9cTOCrmEsb(main.toString(),apiCode);
					//退货单锁定
					String r = CrmUtil.unLockAndLock("8000090017","ReturnedGoodsInvoiceObj",itemmaster.getCrmId(),tokenObj.getString("corpAccessToken"),CrmUtil.MANAGERCODE,tokenObj.getString("corpId"));
					logger.info("退货单锁定"+r);
				} catch (Exception e) {
					LAST_SYNCHRONISED_TIME_UPDATE = DateUtil.now();
					logger.info("退货单更新异常，错误信息为：{}",JSON.toJSONString(itemmaster));
					e.printStackTrace();
				}
			}
		}
    }
}
