package com.hzya.frame.u9c.itemmaster.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.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.hzya.frame.u9c.constant.U9Constant;
import com.hzya.frame.u9c.itemmaster.entity.VU9cItemmasterEntity;
import com.hzya.frame.u9c.itemmaster.dao.IVU9cItemmasterDao;
import com.hzya.frame.u9c.itemmaster.service.IVU9cItemmasterService;
import com.hzya.frame.u9c.util.CrmUtil;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
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;


import java.util.ArrayList;
import java.util.List;

/**
 * (VU9cItemmaster)表服务实现类
 *
 * @author xiaoguo
 * @since 2023-10-25 14:30:38
 */
@Service(value = "vU9cItemmasterService")
public class VU9cItemmasterServiceImpl extends BaseService<VU9cItemmasterEntity, String> implements IVU9cItemmasterService {

    private IVU9cItemmasterDao vU9cItemmasterDao;

    @Autowired
	public void setVU9cItemmasterDao(IVU9cItemmasterDao dao) {
		this.vU9cItemmasterDao = dao;
		this.dao = dao;
	}

    @Override
    public JsonResultEntity queryU9cItemMaster(JSONObject requestObj) {
        List<VU9cItemmasterEntity> vu9cItemmasterEntities = new ArrayList<>();
        return BaseResult.getFailureMessageEntity("获取数据成功",vu9cItemmasterEntities);
    }

    /**
     * 查询U9C物料档案， 同步睿本云专用接口
     *
     * @param entity 参数
     * @return 物料档案
     */
    @DS(U9Constant.DATA_SOURCE_CODE)
    @Override
    public List<VU9cItemmasterEntity> query2Reabam(VU9cItemmasterEntity entity) {
        List<VU9cItemmasterEntity> list = vU9cItemmasterDao.queryList(entity, "VU9cItemmasterEntity_entity_list_base_reabam");
        return list;
    }

    //上一次同步时间
    private String LAST_SYNCHRONISED_TIME = "";
    @Override
    public String sendU9cItemmasterToCRM() {
        JSONObject resultObj = new JSONObject();
        //获取待推送的U9c
        VU9cItemmasterEntity entity = new VU9cItemmasterEntity();
        if (StrUtil.isBlank(LAST_SYNCHRONISED_TIME)) {
            LAST_SYNCHRONISED_TIME = DateUtil.now();
        }
        //暂存时间
        String temp_time = LAST_SYNCHRONISED_TIME;
        entity.setUpdatetime(temp_time);
        List<VU9cItemmasterEntity> vu9cItemmasterEntityList = vU9cItemmasterDao.getu9cItemMaster(entity);
        if(vu9cItemmasterEntityList.size()>0){
            LAST_SYNCHRONISED_TIME = DateUtil.now();
            int i = 0;
            for(VU9cItemmasterEntity itemmaster : vu9cItemmasterEntityList) {
                i++;
                try {
                    String permanentCode = "FSUID_DB2D1775B48BCDF893538F8CAB2A0EC7";
                    //获取token信息
                    JSONObject tokenObj = CrmUtil.getToken(permanentCode);
                    //通过产品分类主键获取分类编码信息
                    String categoryCode  ="";
                    JSONObject category = new JSONObject();
                    category.put("corpAccessToken",tokenObj.getString("corpAccessToken"));//token
                    category.put("corpId",tokenObj.getString("corpId"));//公司
                    category.put("currentOpenUserId",permanentCode);//操作员主键
                    JSONObject categoryData = new JSONObject();
                    String crmCategoryId = itemmaster.getCrmCategoryId();
                    if(StrUtil.isNotEmpty(crmCategoryId)){
                        categoryData.put("objectDataId",crmCategoryId);
                        category.put("data",categoryData);
                        String apiCode = "8000090005";
                         resultObj = CrmUtil.sendU9cTOCrmEsb(category.toString(),apiCode);
                        String errorDescription = resultObj.getString("errorDescription");
                        if("success".equals(errorDescription)){
                            JSONObject dataObj = resultObj.getJSONObject("data");
                             categoryCode = dataObj.getString("code");
                        }
                    }
                    //格式化料品名称，拼接公司
                    String name = itemmaster.getNameOrg();
                    String orgName = itemmaster.getOrgName();
                    String orgCode = "";
                    itemmaster.getProType();
                    switch (orgName){
                        case "杭州博华食品科技有限公司":
                            name = name + "-博华";
                            orgCode = "a2lmNhpo0";
                            break;
                        case "浙江恒华食品科技有限公司":
                            name = name + "-恒华";
                            orgCode = "cD2b3f";
                            break;
                        case "杭州华耀科技食品有限责任公司":
                            itemmaster.setProType("");
                            name = name + "-华耀";
                            orgCode = "sl2qOPMpO";
                            break;
                        case "杭州胡记食品有限公司":
                            itemmaster.setProType("");
                            name = name + "-胡记";
                            orgCode = "eq8LyNWe1";
                            break;
                    }
                    itemmaster.setNameOrg(name);
                    String requestParm = "";
                    String apiCode = "";
                    //通过主键是否为空 判断新增还是更新
                    String crmId = CrmUtil.getProIdByName(name,tokenObj.getString("corpAccessToken"),permanentCode,tokenObj.getString("corpId"));
                    //格式化单位信息
                    //todo 2023年12月18日20:56:48 CRM实施提出将U9C销售计量单位传递到他们单位上
                    String unitName = itemmaster.getSaleUnit();
                    String unit = formatUnit(unitName,tokenObj,permanentCode);
                    //为了防止再次出现本应该是更新却走了新增方法
                    logger.info("商品新增还是更新的参数"+JSON.toJSONString(itemmaster));
                    if(StrUtil.isEmpty(crmId)){
                        requestParm = bindingAdd(itemmaster,tokenObj,permanentCode,categoryCode,unit, orgCode);
                        apiCode = "8000090000";
                    }else{
                        requestParm = bindingEdit(itemmaster,tokenObj,permanentCode,categoryCode,unit,orgCode);
                        apiCode = "8000090006";
                    }
                    resultObj = CrmUtil.sendU9cTOCrmEsb(requestParm,apiCode);

                    String errorDescription = resultObj.getString("errorDescription");
                    if("success".equals(errorDescription)){
                        if(StrUtil.isNotEmpty(crmId)){
                            //得到商品ID 通过商品ID查询产品信息用于修改产品档案
                            String proId = CrmUtil.getProIdBySupId(crmId,tokenObj.getString("corpAccessToken"),permanentCode,tokenObj.getString("corpId"));
                            requestParm = bindingProEdit(itemmaster,tokenObj,permanentCode,categoryCode,unit,proId,orgCode);
                            apiCode = "8000090014";
                            logger.info("商品修改→请求数据：{}",requestParm);
                            resultObj = CrmUtil.sendU9cTOCrmEsb(requestParm,apiCode);
                            logger.info("商品修改→返回数据：{}",resultObj.toString());
//                            String dataId = resultObj.getString("dataId");
//                            if(StrUtil.isNotEmpty(dataId)){
//                                itemmaster.setDataId(dataId);
//                                int state = vU9cItemmasterDao.updateItemMaster(itemmaster);
//                            }
                        }
                    }
//                    System.out.println(resultObj);
                } catch (Exception e) {
//                    itemmaster.setDataId("接口错误，请联系管理员");
                    logger.info(e.getMessage());
//                    vU9cItemmasterDao.updateItemMaster(itemmaster);
                    e.printStackTrace();
                }
            }
        }
        return resultObj.toString();
    }
    /**
     *
     * @content 组装产品信息修改产品
     * @author makejava
     * @date 2023/12/17 0017 13:43
     *
     */

    private String bindingProEdit(VU9cItemmasterEntity itemmaster, JSONObject tokenObj, String permanentCode, String categoryCode, String unit,String proId,String orgCode) {
        String Effective_IsEffective = itemmaster.getEffective_IsEffective();
        String state = "2";
        if(StrUtil.isNotEmpty(Effective_IsEffective)&& "1".equals(Effective_IsEffective)){
            state = "1";
        }
        JSONObject main = new JSONObject();
        main.put("corpAccessToken",tokenObj.getString("corpAccessToken"));//token
        main.put("corpId",tokenObj.getString("corpId"));//公司
        main.put("currentOpenUserId",permanentCode);//操作员主键
        JSONObject object_data =  new JSONObject();
        JSONObject data =  new JSONObject();
        data.put("object_data",object_data);
        main.put("data",data);
        object_data.put("dataObjectApiName","ProductObj");
        object_data.put("product_status",state);//上架状态
        object_data.put("name",itemmaster.getNameOrg());//产品名称
        object_data.put("product_code",itemmaster.getCode());//产品编码
        object_data.put("UDSText2__c",itemmaster.getSpecs());//规格
        object_data.put("UDSText1__c",itemmaster.getSaleUnit());//销售计量单位
        object_data.put("field_HV195__c",itemmaster.getLotValidDate());//保质期
        object_data.put("price",itemmaster.getStandardPrice());//标准价格
        object_data.put("unit",unit);//单位
        object_data.put("field_z5Z43__c",itemmaster.getProType());//产品大类
        object_data.put("field_wq5S2__c",itemmaster.getUnitName());//基本计量单位
        object_data.put("_id",proId);//基本计量单位
        object_data.put("field_s1Mw1__c",itemmaster.getCrmCostPrice());//成本价
        object_data.put("field_lmTK1__c",itemmaster.getCRMSalesRate());//销售换算率
        object_data.put("field_1J9OY__c",orgCode);//产品归属组织
        object_data.put("field_bd1Vb__c",itemmaster.getName());//产品售卖名称
        return main.toString();
    }

    /**
     * 绑定新增的参数
     */
    public String bindingEdit(VU9cItemmasterEntity itemmaster,JSONObject tokenObj,String permanentCode,String categoryCode,String unit,String orgCode){
        //拼接传递参数
        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();
        JSONObject object_data = new JSONObject();
        data.put("object_data",object_data);
        object_data.put("dataObjectApiName","SPUObj");
        String unitName = itemmaster.getUnitName();
        object_data.put("unit",unit);//计量单位
        JSONArray ownerArr = new JSONArray();
        ownerArr.add(permanentCode);
        object_data.put("owner",ownerArr);//负责人
        object_data.put("is_spec",false);//规格属性
        object_data.put("batch_sn","1");//批次与序列号管理默认不开启 有需求再议
        object_data.put("field_LwLE9__c",itemmaster.getLotValidDate());//有效期
        object_data.put("_id",itemmaster.getCrmId());//批次与序列号管理默认不开启 有需求再议
        object_data.put("remark","");//备注
        object_data.put("product_line","0");//产品线
        object_data.put("name",itemmaster.getNameOrg());//名称
        object_data.put("category",categoryCode);//分类
        object_data.put("standard_price",itemmaster.getStandardPrice());//标准价格
        object_data.put("field_d93lT__c",orgCode);//商品归属组织
        object_data.put("field_QB22i__c",itemmaster.getName());//商品售卖名称
        object_data.put("field_kU8p1__c",itemmaster.getCrmCostPrice());//成本价格
        object_data.put("field_tb4hq__c",itemmaster.getCRMSalesRate());//销售换算率
        JSONObject details = new JSONObject();
        main.put("data",data);
        object_data.put("details",details);
        return main.toString();
    }

    /**
     * 绑定新增的参数
     */
    public String bindingAdd(VU9cItemmasterEntity itemmaster,JSONObject tokenObj,String permanentCode,String categoryCode,String unit,String orgCode){
        //拼接传递参数
        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();
        JSONObject object_data = new JSONObject();
        data.put("object_data",object_data);
        object_data.put("dataObjectApiName","SPUObj");
        String unitName = itemmaster.getUnitName();
        object_data.put("unit",unit);//计量单位
        JSONArray ownerArr = new JSONArray();
        ownerArr.add(permanentCode);
        object_data.put("owner",ownerArr);//负责人
        object_data.put("is_spec",false);//规格属性
        object_data.put("remark","");//备注
        object_data.put("product_line","0");//产品线
        object_data.put("field_LwLE9__c",itemmaster.getLotValidDate());//有效期
        object_data.put("name",itemmaster.getNameOrg());//名称
        object_data.put("category",categoryCode);//分类
        object_data.put("standard_price",itemmaster.getStandardPrice());//标准价格
        object_data.put("field_d93lT__c",orgCode);//商品归属组织
        object_data.put("field_QB22i__c",itemmaster.getName());//商品售卖名称
        object_data.put("field_kU8p1__c",itemmaster.getCrmCostPrice());//成本价格
        object_data.put("field_tb4hq__c",itemmaster.getCRMSalesRate());//销售换算率

        JSONObject sku = new JSONObject();
        JSONArray skuArr = new JSONArray();
        sku.put("object_describe_api_name","ProductObj");
        sku.put("product_status","1");
        sku.put("name",itemmaster.getNameOrg());//产品编码
        sku.put("product_code",itemmaster.getCode());//产品编码
        sku.put("UDSText2__c",itemmaster.getSpecs());//规格
        sku.put("UDSText1__c",itemmaster.getSaleUnit());//销售计量单位
        sku.put("field_HV195__c",itemmaster.getLotValidDate());//保质期
        sku.put("price",itemmaster.getStandardPrice());//标准价格
        sku.put("unit",unit);//单位
        sku.put("field_z5Z43__c",itemmaster.getProType());//产品大类
        sku.put("field_wq5S2__c",itemmaster.getUnitName());//基本计量单位
        sku.put("field_1J9OY__c",orgCode);//产品归属组织
        sku.put("field_bd1Vb__c",itemmaster.getName());//产品售卖名称
        sku.put("field_s1Mw1__c",itemmaster.getCrmCostPrice());//成本价
        sku.put("field_lmTK1__c",itemmaster.getCRMSalesRate());//销售换算率
        main.put("data",data);
        skuArr.add(sku);
        object_data.put("sku",skuArr);
       return main.toString();
    }
    /**
     * 格式化计量单位为CRM单位编码
     * @param unitName
     * @return
     */
    public String formatUnit(String unitName,JSONObject tokenObj ,String permanentCode){
        String apiCode = "8000090013";
        //获取单位的所有信息
        JSONObject main = new JSONObject();
        main.put("corpAccessToken",tokenObj.getString("corpAccessToken"));//token
        main.put("corpId",tokenObj.getString("corpId"));//公司
        main.put("currentOpenUserId",permanentCode);//操作员主键
        main.put("includeDetail",true);
        main.put("apiName","SPUObj");
        JSONObject resultObj = CrmUtil.sendU9cTOCrmEsb(main.toString(),apiCode);
        JSONObject data = resultObj.getJSONObject("data");
        JSONObject describe = data.getJSONObject("describe");
        JSONObject fields = describe.getJSONObject("fields");
        JSONObject unitObj = fields.getJSONObject("unit");
        JSONArray optionsList = unitObj.getJSONArray("options");
        if(null != optionsList && optionsList.size()>0){
            for(Object options : optionsList){
                JSONObject unit = JSON.parseObject(options.toString());
                String crmName = unit.getString("label");
                if(crmName.equals(unitName)){
                    return unit.getString("value");
                }
            }
        }
        logger.info("未匹配到计量单位单位信息");
        return null;
    }
}
