package com.hzya.frame.u9c.salereceiver.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.entity.VU9cSaledeliverEntity;
import com.hzya.frame.u9c.saledeliver.service.IVU9cSaledeliverService;
import com.hzya.frame.u9c.salereceiver.dao.IVU9cSalereceiverDetailsDao;
import com.hzya.frame.u9c.salereceiver.entity.VU9cSalereceiverDetailsEntity;
import com.hzya.frame.u9c.salereceiver.entity.VU9cSalereceiverEntity;
import com.hzya.frame.u9c.salereceiver.dao.IVU9cSalereceiverDao;
import com.hzya.frame.u9c.salereceiver.service.IVU9cSalereceiverService;
import com.hzya.frame.u9c.util.CrmUtil;
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;

/**
 * (VU9cSalereceiver)表服务实现类
 *
 * @author makejava
 * @since 2023-10-26 11:32:09
 */
@Service("vU9cSalereceiverService")
public class VU9cSalereceiverServiceImpl extends BaseService<VU9cSalereceiverEntity, String> implements IVU9cSalereceiverService {
     
    private IVU9cSalereceiverDao vU9cSalereceiverDao;
    @Autowired
    private IVU9cSaledeliverService v9cSaledeliverService;

    @Autowired
    private IVU9cSalereceiverDetailsDao u9cSalereceiverDetailsDao;
    
    @Autowired
	public void setVU9cSalereceiverDao(IVU9cSalereceiverDao dao) {
		this.vU9cSalereceiverDao = dao;
		this.dao = dao;
	}
    //上一次同步时间
    private String LAST_SYNCHRONISED_TIME = "";
    @Override
    public String sendU9cSalereceiverToCRM() {
        //获取待推送的U9c
        VU9cSalereceiverEntity category = new VU9cSalereceiverEntity();
        if (StrUtil.isBlank(LAST_SYNCHRONISED_TIME)) {
            LAST_SYNCHRONISED_TIME = DateUtil.now();
        }
        //暂存时间
        String temp_time = LAST_SYNCHRONISED_TIME;
        category.setUpdateTime(temp_time);
        List<VU9cSalereceiverEntity> VU9cSalereceiverEntityList = vU9cSalereceiverDao.getu9cSalereceiver(category);
        if(VU9cSalereceiverEntityList.size()>0){
            for(VU9cSalereceiverEntity itemmaster : VU9cSalereceiverEntityList){
                LAST_SYNCHRONISED_TIME = DateUtil.now();
                //因纷享销客接口性质不同 表头表体分开传递，则机型分开推送
//                String permanentCode = "FSUID_DB2D1775B48BCDF893538F8CAB2A0EC7";
                String permanentCode =itemmaster.getOperatorsId();
                JSONObject tokenObj = CrmUtil.getToken(permanentCode);
                //推送表头信息
                String dataId = sendSalereceiverMain(itemmaster, permanentCode, tokenObj);
//                String id = itemmaster.getId();
//                String billCode = itemmaster.getBillCode();
                //查询明细信息并推送
//                sendSalereceiverDetails(id, permanentCode, tokenObj,billCode,dataId);

            }
        }
        return null;
    }
    /**
     *
     * @content 将删除的应收单同步删除CRM单据
     * @author makejava
     * @date 2024/1/10 0010 14:38
     *
     */
    @Override
    public void sendU9cSalereceiverToCRMOfDetele() {
        VU9cSalereceiverEntity category = new VU9cSalereceiverEntity();
        List<VU9cSalereceiverEntity> VU9cSalereceiverEntityList = vU9cSalereceiverDao.getu9cSalereceiverForDelete(category);
        if(null != VU9cSalereceiverEntityList && VU9cSalereceiverEntityList.size()>0){
            for(VU9cSalereceiverEntity entity : VU9cSalereceiverEntityList){
                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","object_ab2ol__c");
                        state = "1";
                        String apiCode = "8000090019";
                        //回款单解锁
                        String r = CrmUtil.unLockAndLock("8000090016","object_ab2ol__c",crmId,tokenObj.getString("corpAccessToken"),CrmUtil.MANAGERCODE,tokenObj.getString("corpId"));
                        //推送数据到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);
                    vU9cSalereceiverDao.updateStateForDelete(entity);
                }
            }
        }
    }

    private void sendSalereceiverDetails(String mainId, String permanentCode, JSONObject tokenObj,String billCode,String dataId) {
        VU9cSalereceiverDetailsEntity details = new VU9cSalereceiverDetailsEntity();
        details.setMainId(mainId);
        List<VU9cSalereceiverDetailsEntity> detailsList = u9cSalereceiverDetailsDao.getu9cSalereceiverDetails(details);
        if(null != detailsList && detailsList.size()>0){
            for(VU9cSalereceiverDetailsEntity d : detailsList){
                String id = d.getId();
                //拼接传递参数
                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);
                JSONObject data = new JSONObject();
                main.put("data",data);
                JSONObject object_data = new JSONObject();
                JSONArray owner = new JSONArray();
                owner.add(permanentCode);
                object_data.put("dataObjectApiName","object_1n255__c");
                object_data.put("owner",owner);
//                object_data.put("field_q18s0__c","6549e908e6767b0001fe6a68");//todo 等待对接发货单号主键
                object_data.put("field_q18s0__c",d.getDeliverBillId());//todo 等待对接发货单号主键
                object_data.put("field_126Mr__c",dataId);// CRM表头主键
                object_data.put("field_8v8Np__c",d.getInvName());// 产品名称
                object_data.put("field_hog9b__c",d.getNum());// 数量
                object_data.put("field_bumZ5__c",d.getTaxPrice());// 单价
                object_data.put("field_oZ129__c","");// 回款方式
                object_data.put("field_Tt1kg__c",d.getTaxPriceSum());// 金额
                object_data.put("field_e3NWX__c","");// 备注
                object_data.put("field_y67ja__c",billCode);// 回款单编号
                object_data.put("field_4gcxj__c",d.getsRowId());// 发货单明细行号
                object_data.put("field_0dmOD__c",d.getProId());// 产品ID

                object_data.put("field_0I0C5__c",d.getRmaMoney());// 本次退款金额
                object_data.put("field_Fl2r5__c",d.getRmaLine());// 退货单金额
                object_data.put("field_6gfrJ__c",d.getRmaId());// 退货单ID
                object_data.put("field_j8Kdx__c",d.getSoId());// 销售订单ID
                object_data.put("field_vE2T3__c",d.getDocLineNo());//发货单行号
                String billType = d.getBillType();
                String record_type = "";
                if("退回".equals(billType)){
                    record_type = "record_EjW1M__c";
                }
                if("出货".equals(billType)){
                    record_type = "default__c";
                }
                object_data.put("record_type",record_type);// 业务类型
                data.put("object_data",object_data);
                String apiCode = "8000090012";
                JSONObject resultObj = CrmUtil.sendU9cTOCrmEsb(main.toString(),apiCode);
                try {
                    String errorDescription = resultObj.getString("errorDescription");
                    if("success".equals(errorDescription)){
                        String dataIdDetails = resultObj.getString("dataId");
                        if(StrUtil.isNotEmpty(dataIdDetails)){
                            d.setDataId(dataIdDetails);
                            u9cSalereceiverDetailsDao.updateState(d);
                        }
                    }
                } catch (Exception e) {
                    d.setDataId("系统异常，请联系管理员");
                    u9cSalereceiverDetailsDao.updateState(d);
                    e.printStackTrace();
                }
                logger.info("CRM应收单明细返回信息"+resultObj);
            }
        }
    }

    /***
 * @Content:推送表头信息
 * @Author 👻👻👻👻yqh👻👻👻👻
 * @Date  2023年11月9日15:03:19
 * @Param
 * @return
 **/
    private String sendSalereceiverMain(VU9cSalereceiverEntity itemmaster, String permanentCode, JSONObject tokenObj) {
        String id = itemmaster.getId();
        String dataId = null;
        JSONObject resultObj = new JSONObject();
        try {
            //拼接传递参数
            String crmId = itemmaster.getCrmId();
            JSONObject main = new JSONObject();
            main.put("corpAccessToken",tokenObj.getString("corpAccessToken"));//token
            main.put("corpId",tokenObj.getString("corpId"));//公司
            main.put("currentOpenUserId",permanentCode);//操作员主键
            main.put("triggerWorkFlow",true);//是否触发流程，不需要
            main.put("includeDetailIds",true);
            JSONObject data = new JSONObject();
            main.put("data",data);
            JSONObject object_data = new JSONObject();
            JSONArray owner = new JSONArray();
            owner.add(permanentCode);
            object_data.put("dataObjectApiName","object_ab2ol__c");
            object_data.put("owner",owner);
            String custName = itemmaster.getCustName();
            String custId = CrmUtil.getCustIdByCustName(custName,tokenObj.getString("corpAccessToken"),permanentCode,tokenObj.getString("corpId"));
            object_data.put("field_e0335__c",custId);//客户名称
//            object_data.put("field_c4r1p__c",itemmaster.getSoId());// CRM销售订单主键
            object_data.put("field_l3g1v__c",itemmaster.getBillCode());//U9C回款编号
    //        object_data.put("field_l3g1v__c",itemmaster.getBillCode());//U9C回款编号
            String orgCode = itemmaster.getOrgCode();
            //如果CRMID存在，则走修改流程
            if(StrUtil.isNotEmpty(crmId)){
                object_data.put("_id",itemmaster.getCrmId());//todo 等待对接发货单号主键
            }
            String field_J0EN1__c = "";

            if(StrUtil.isNotEmpty(orgCode)){
                switch (orgCode){
                    case "1001"://杭州恒华科技有限公司
                        field_J0EN1__c = "cD2b3f";
                        break;
                    case "1002"://杭州华耀商贸有限公司
                        field_J0EN1__c = "sl2qOPMpO";
                        break;
                    case "1004"://诚艺传递华耀
                        field_J0EN1__c = "sl2qOPMpO";
                        break;
                    case "1003"://杭州胡记食品有限公司
                        field_J0EN1__c = "eq8LyNWe1";
                        break;
                    default:
                        break;
                }
            }
            object_data.put("field_J0EN1__c",field_J0EN1__c); //组织
            //拼接组装明细数据
            VU9cSalereceiverDetailsEntity details = new VU9cSalereceiverDetailsEntity();
            details.setMainId(itemmaster.getId());
            List<VU9cSalereceiverDetailsEntity> detailsList = u9cSalereceiverDetailsDao.getu9cSalereceiverDetails(details);
            JSONArray object_1n255__cArr = new JSONArray();
            JSONObject detailsObj = new JSONObject();
            if(null != detailsList && detailsList.size()>0){
                for(VU9cSalereceiverDetailsEntity d : detailsList){


                    JSONObject object_1n255__c = new JSONObject();

                    object_1n255__c.put("field_q18s0__c",d.getDeliverBillId());//todo 等待对接发货单号主键
                    object_1n255__c.put("field_126Mr__c",dataId);// CRM表头主键
                    object_1n255__c.put("field_8v8Np__c",d.getInvName());// 产品名称
                    object_1n255__c.put("field_hog9b__c",d.getNum());// 数量
                    object_1n255__c.put("field_bumZ5__c",d.getTaxPrice());// 单价
                    object_1n255__c.put("field_oZ129__c","");// 回款方式
                    object_1n255__c.put("field_Tt1kg__c",d.getTaxPriceSum());// 金额
                    object_1n255__c.put("field_e3NWX__c","");// 备注
                    object_1n255__c.put("field_y67ja__c",itemmaster.getBillCode());// 回款单编号
                    object_1n255__c.put("field_4gcxj__c",d.getsRowId());// 发货单明细行号
                    object_1n255__c.put("field_0dmOD__c",d.getProId());// 产品ID
                    object_1n255__c.put("field_0I0C5__c",d.getRmaMoney());// 本次退款金额
                    object_1n255__c.put("field_Fl2r5__c",d.getRmaLine());// 退货单金额
                    object_1n255__c.put("field_6gfrJ__c",d.getRmaId());// 退货单ID
                    object_1n255__c.put("field_j8Kdx__c",d.getSoId());// 销售订单ID
                    object_1n255__c.put("field_vE2T3__c",d.getDocLineNo());//发货单行号
                    String billType = d.getBillType();
                    String record_type = "";
                    if("退回".equals(billType)){
                        record_type = "record_EjW1M__c";
                    }
                    if("出货".equals(billType)){
                        record_type = "default__c";
                    }
                    object_1n255__c.put("record_type",record_type);// 业务类型
                    object_1n255__cArr.add(object_1n255__c);
                }

            }
            detailsObj.put("object_1n255__c",object_1n255__cArr);
//            object_data.put("details",detailsObj);

            //拼接结束

            data.put("object_data",object_data);
            data.put("details",detailsObj);
            String apiCode = "";
            if(StrUtil.isEmpty(crmId)){
                apiCode = "8000090004";
            }else{
                apiCode = "8000090010";
                String r = CrmUtil.unLockAndLock("8000090016","object_ab2ol__c",crmId,tokenObj.getString("corpAccessToken"),CrmUtil.MANAGERCODE,tokenObj.getString("corpId"));
                logger.info("回款单解锁"+r);
            }
            //推送数据到CRM
             resultObj = CrmUtil.sendU9cTOCrmEsb(main.toString(),apiCode);
            //todo CRM傅佳敏提出 不管任何原因修改失败都需要再次锁定
            if(StrUtil.isNotEmpty(crmId)){
                //修改完数据之后需要再次锁定
                String r = CrmUtil.unLockAndLock("8000090017","object_ab2ol__c",crmId,tokenObj.getString("corpAccessToken"),CrmUtil.MANAGERCODE,tokenObj.getString("corpId"));
                logger.info("回款单锁定"+r);
            }
                String errorDescription = resultObj.getString("errorDescription");

                if("success".equals(errorDescription)){
                     dataId = resultObj.getString("dataId");
                    if(StrUtil.isNotEmpty(dataId)){
                        itemmaster.setDataId(dataId);
                        vU9cSalereceiverDao.updateState(itemmaster);
                    }
             }
        } catch (Exception e) {
            itemmaster.setDataId("系统异常，请联系管理员");
            vU9cSalereceiverDao.updateState(itemmaster);
            e.printStackTrace();
        }
        logger.info("CRM应收单主表返回信息"+resultObj);
        return dataId;
    }
}
