package com.fs.his.service.impl;

import cn.hutool.core.codec.Base64Decoder;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.erp.dto.sdk.HzOMS.utils.HzOMSUtils;
import com.fs.his.config.FsSysConfig;
import com.fs.his.domain.FsStoreOrder;
import com.fs.his.domain.FsStoreProduct;
import com.fs.his.domain.FsStoreProductAttrValue;
import com.fs.his.param.HzOMSErpApiParam;
import com.fs.his.service.ErpApiService;
import com.fs.his.service.IFsStoreOrderService;
import com.fs.his.service.IFsStoreProductAttrValueService;
import com.fs.his.service.IFsStoreProductService;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.vo.HzOMSErpResponseDetailVO;
import com.fs.his.vo.HzOMSErpResponseErrorItemVO;
import com.fs.his.vo.HzOMSErpResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class HzOMSErpApiServiceImpl implements ErpApiService {

    @Autowired
    private ConfigUtil configUtil;

    private final Integer HZOMS_ERP_TYPE = 3;

    private final String CODE_SUCCESS = "200";

    @Autowired
    IFsStoreProductService fsStoreProductService;

    @Autowired
    IFsStoreProductAttrValueService fsStoreProductAttrValueService;

    @Autowired
    IFsStoreOrderService fsStoreOrderService;

    /**
     * 平台商品库存同步到第三方
     *
     * @param param
     * @return
     */
    @Override
    public HzOMSErpResponseVO stockSync(HzOMSErpApiParam param) {
        HzOMSErpResponseVO res = new HzOMSErpResponseVO();
        //校验数据合法性
        String v = legitimateVerification(param);
        if (!"".equals(v)) {
            res.setSuccess(Boolean.FALSE);
            res.setMessage(v);
            return res;
        }
        //对方传输的datapacage是base64编码的 先解码得到 json
        JSONObject dataObj = getDecodeDataJSON(param.getDatapakege());
        res.setCode(CODE_SUCCESS);
        res.setMessage(dataObj.toJSONString());
        Long storeId = dataObj.getLong("cptshopcode");
        JSONArray syncstocklist = dataObj.getJSONArray("syncstocklist");
        List<HzOMSErpResponseErrorItemVO> errorlist = new ArrayList<>();
        syncstocklist.forEach(item -> {
            JSONObject o = (JSONObject) item;
            //判断当前店铺是否存在此商品
            FsStoreProduct fsStoreProduct = fsStoreProductService.getStoreProductByProductIdAndStoreId(o.getLong("cptgoodsid"), storeId);
            if (fsStoreProduct != null) {
                fsStoreProductService.updateStoreProductStock(o.getLong("cptgoodsid"), o.getInteger("fptstock"));
            } else {
                HzOMSErpResponseErrorItemVO errorItemVO = new HzOMSErpResponseErrorItemVO();
                errorItemVO.setCptgoodsid(o.getLong("cptgoodsid").toString());
                errorItemVO.setMsg("商品不存在");
                errorlist.add(errorItemVO);
            }
        });
        res.setSuccess(Boolean.TRUE);
        HzOMSErpResponseDetailVO resData = new HzOMSErpResponseDetailVO();
        resData.setErrorlist(errorlist);
        res.setData(resData);
        return res;
    }

    /**
     * 用于将瀚智商品库存同步到第三方
     * @param param
     * @return
     */
    @Override
    public HzOMSErpResponseVO skuStockSync(HzOMSErpApiParam param) {
        HzOMSErpResponseVO res = new HzOMSErpResponseVO();

        String v = legitimateVerification(param);
        if (!"".equals(v)) {
            res.setSuccess(Boolean.FALSE);
            res.setMessage(v);
            return res;
        }
        //对方传输的datapacage是base64编码的 先解码得到 json
        JSONObject dataObj = getDecodeDataJSON(param.getDatapakege());
        res.setCode(CODE_SUCCESS);
        res.setMessage("同步商品规格库存成功");

        Long storeId = dataObj.getLong("cptshopcode");
        JSONArray syncstocklist = dataObj.getJSONArray("syncstocklist");
        List<HzOMSErpResponseErrorItemVO> errorlist = new ArrayList<>();
        syncstocklist.forEach(item -> {
            //商品
            JSONObject o = (JSONObject) item;
            Long productId = o.getLong("cptgoodsid");
            JSONArray skustocklist = o.getJSONArray("skustocklist");
            //规格list
            skustocklist.forEach(skuItem -> {
                JSONObject skuO = (JSONObject) skuItem;
                Long skuId = skuO.getLong("cptspeccode");
                //判断当前店铺是否存在此商品规格
                FsStoreProductAttrValue fsStoreProductAttrValue = fsStoreProductAttrValueService.selectFsStoreProductAttrValueByIdAndPruductId(productId, skuId);
                if (fsStoreProductAttrValue != null) {
                    fsStoreProductAttrValueService.updateStoreProductAttrValueStock(productId, o.getInteger("fptstock"));
                } else {
                    HzOMSErpResponseErrorItemVO errorItemVO = new HzOMSErpResponseErrorItemVO();
                    errorItemVO.setCptgoodsid(productId.toString());
                    errorItemVO.setCptspeccode(skuId.toString());
                    errorItemVO.setMsg("规格不存在");
                    errorlist.add(errorItemVO);
                }
            });
        });
        res.setSuccess(Boolean.TRUE);
        HzOMSErpResponseDetailVO resData = new HzOMSErpResponseDetailVO();
        resData.setErrorlist(errorlist);
        res.setData(resData);
        return res;
    }

    /**
     * 平台订单物流信息回传
     *
     * @param param
     * @return
     */
    @Override
    public HzOMSErpResponseVO logisticsAdd(HzOMSErpApiParam param) {
        HzOMSErpResponseVO res = new HzOMSErpResponseVO();
        //校验方法调用合法性
        String v = legitimateVerification(param);
        if (!"".equals(v)) {
            res.setSuccess(Boolean.FALSE);
            res.setMessage(v);
            return res;
        }
        //对方传输的datapacage是base64编码的 先解码得到 json
        JSONArray dataArr = getDecodeDataJSONArr(param.getDatapakege());
        List<HzOMSErpResponseErrorItemVO> errorlist = new ArrayList<>();
        dataArr.forEach(oItem -> {
            JSONObject item = (JSONObject) oItem;
            //判断订单是否存在
            FsStoreOrder fsOrder = fsStoreOrderService.getOrderByOrderCodeAndStoreId(item.getString("cptordercode"), item.getLong("cptshopcode"));
            if (null != fsOrder) {
                fsOrder.setDeliveryCode(item.getString("cexpresscode"));
                fsOrder.setDeliveryName(item.getString("cexpressname"));
                fsOrder.setDeliverySn(item.getString("clogisticsno"));
                fsStoreOrderService.updateStoreOrderDeliveryInfo(fsOrder);
            } else {
                HzOMSErpResponseErrorItemVO addErrItem = new HzOMSErpResponseErrorItemVO();
                addErrItem.setCptordercode(item.getString("cptordercode"));
                addErrItem.setCptshopcode(item.getString("cptshopcode"));
                addErrItem.setMsg("订单不存在");
                errorlist.add(addErrItem);
            }
        });
        res.setCode(CODE_SUCCESS);
        res.setMessage("平台订单物流信息回传成功");
        HzOMSErpResponseDetailVO resData = new HzOMSErpResponseDetailVO();
        resData.setErrorlist(errorlist);
        return res;
    }

    /**
     * 校验方法调用合法性
     *
     * @param param
     * @return
     */
    public String legitimateVerification(HzOMSErpApiParam param) {
        FsSysConfig sysConfig = configUtil.getSysConfig();
        Integer erpType = sysConfig.getErpType();
        //校验系统配置
        if (!HZOMS_ERP_TYPE.equals(erpType)) {
            return "系统配置ERP不匹配,请联系管理员。";
        }
        String erpHzOMSAppKey = sysConfig.getErpHzOMSAppKey();
        //校验传参appKey是否相符
        if (!erpHzOMSAppKey.equals(param.getAppkey())) {
            return "系统配置appKey不匹配,请联系管理员。";
        }
        //校验数据签名是否合法
        try {
            Boolean b = HzOMSUtils.signValidate(param.getTimestamp(), param.getDatapakege(), sysConfig.getErpHzOMSAppsecret(), param.getSign());
            if (!b) {
                return "非法数据，签名校验失败。";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "数据签名校验失败。";
        }
        return "";
    }

    /**
     * 获取解码后的JSON数据
     *
     * @param s
     * @return
     */
    public JSONObject getDecodeDataJSON(String s) {
        JSONObject dataObj = JSONObject.parseObject(new String(Base64Utils.decode(s.getBytes(StandardCharsets.UTF_8))));
        return dataObj;
    }

    /**
     * 获取解码后的JSONArray数据
     *
     * @param s
     * @return
     */
    public JSONArray getDecodeDataJSONArr(String s) {
        JSONArray arr = JSONArray.parseArray(new String(Base64Utils.decode(s.getBytes(StandardCharsets.UTF_8))));
        return arr;
    }
}
