package com.kxs.transfer.api.service.product.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dts.subscribe.clients.record.OperationType;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.util.RetOps;
import com.kxs.product.api.model.KxsShopGoods;
import com.kxs.product.api.model.KxsShopGoodsPic;
import com.kxs.product.api.model.KxsShopGoodsSku;
import com.kxs.product.api.model.KxsShopGoodsSpec;
import com.kxs.transfer.api.mapper.product.KxsShopGoodsMapper;
import com.kxs.transfer.api.mapper.product.KxsShopGoodsPicMapper;
import com.kxs.transfer.api.mapper.product.KxsShopGoodsSkuMapper;
import com.kxs.transfer.api.mapper.product.KxsShopGoodsSpecMapper;
import com.kxs.transfer.api.model.table.DMLData;
import com.kxs.transfer.api.model.table.FieldData;
import com.kxs.transfer.api.service.product.KxsShopGoodsPicService;
import com.kxs.transfer.api.service.product.KxsShopGoodsService;
import com.kxs.transfer.api.service.product.KxsShopGoodsSkuService;
import com.kxs.transfer.api.service.product.KxsShopGoodsSpecService;
import com.kxs.user.api.model.KxsLeaderAmountLog;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 商城商品表(KxsShopGoods)表服务实现类
 *
 * @author 系统
 * @since 2023-12-20 10:09:35
 */
@Service("kxsShopGoodsService")
@RequiredArgsConstructor
public class KxsShopGoodsServiceImpl extends ServiceImpl<KxsShopGoodsMapper, KxsShopGoods> implements KxsShopGoodsService {

    private final KxsShopGoodsSkuService kxsShopGoodsSkuService;
    private final KxsShopGoodsSpecService kxsShopGoodsSpecService;

    private final KxsShopGoodsPicService kxsShopGoodsPicService;

    @Override
    public void changeData(DMLData dmlData) {
        //修改的字段值
        Map<String, Object> validFieldDataMap = dmlData.getValidFieldDataMap();
        //全部字段值
        Map<String, FieldData> fieldDataMap = dmlData.getFieldDataMap();
        //修改的字段
        List<String> changeFieldList = dmlData.getChangeFieldList();
        //操作的主键
        int id = Integer.parseInt(dmlData.getId());

        KxsShopGoods goods = new KxsShopGoods();
        goods.setId(id);

        List<KxsShopGoodsPic> picList = new ArrayList<>();

        if(fieldDataMap.get("ProductKind").getValue() != null){
            int kind = Integer.parseInt(fieldDataMap.get("ProductKind").getValue().toString());
            if(kind == 1){
                goods.setGoodsType(0);
            }else{
                goods.setGoodsType(1);
            }
        }
        if(fieldDataMap.get("Sort").getValue() != null){
            goods.setSort(Integer.valueOf(fieldDataMap.get("Sort").getValue().toString()));
        }
        if(fieldDataMap.get("ListPicPath").getValue() != null){
            String pics = fieldDataMap.get("ListPicPath").getValue().toString();
            if(StrUtil.isNotBlank(pics)){
                String[] imgs = pics.split(",");
                //封面图
                goods.setPicUrl(imgs[0]);
                //同步商品图片表
                for (String img : imgs) {
                    KxsShopGoodsPic shopGoodsPic = new KxsShopGoodsPic();
                    shopGoodsPic.setUrl(img);
                    shopGoodsPic.setGoodsId(id);
                    picList.add(shopGoodsPic);
                }
            }
        }
        if(fieldDataMap.get("Status").getValue() != null){
            goods.setStatus(Integer.valueOf(fieldDataMap.get("Status").getValue().toString()));
        }
        if(fieldDataMap.get("ProductName").getValue() != null){
            goods.setGoodsName(fieldDataMap.get("ProductName").getValue().toString());
        }
        if(fieldDataMap.get("Details").getValue() != null){
            goods.setSubtitle(fieldDataMap.get("Details").getValue().toString());
        }
        if(fieldDataMap.get("NormJson").getValue() != null){
            String value = fieldDataMap.get("NormJson").getValue().toString();
            if(StrUtil.isNotBlank(value) && value.contains("#cut#")){
                String sku = value.substring(0, value.indexOf("#cut#"));
                goods.setSpecList(sku);
            }
        }
        if(fieldDataMap.get("Contents").getValue() != null){
            goods.setDetails(fieldDataMap.get("Contents").getValue().toString());
        }
        if(fieldDataMap.get("ColId").getValue() != null){
            goods.setColId(fieldDataMap.get("ColId").getValue().toString());
        }
        if(fieldDataMap.get("Price").getValue() != null){
            goods.setPrice(new BigDecimal(fieldDataMap.get("Price").getValue().toString()));
        }
        if(fieldDataMap.get("LimitCount").getValue() != null){
            goods.setLimitCount(Integer.valueOf(fieldDataMap.get("LimitCount").getValue().toString()));
        }
        if(fieldDataMap.get("StartBuyCount").getValue() != null){
            goods.setLimitCount(Integer.valueOf(fieldDataMap.get("StartBuyCount").getValue().toString()));
        }
        if(fieldDataMap.get("PublishDate").getValue() != null){
            goods.setUpTime(LocalDateTimeUtil.parse(fieldDataMap.get("PublishDate").getValue().toString(), DatePattern.NORM_DATETIME_PATTERN));
        }
        if(fieldDataMap.get("CreateDate").getValue() != null){
            goods.setCreateTime(LocalDateTimeUtil.parse(fieldDataMap.get("CreateDate").getValue().toString(), DatePattern.NORM_DATETIME_PATTERN));
        }
        if(fieldDataMap.get("UpdateDate").getValue() != null){
            goods.setUpdateTime(LocalDateTimeUtil.parse(fieldDataMap.get("UpdateDate").getValue().toString(), DatePattern.NORM_DATETIME_PATTERN));
        }
//        for (String field : changeFieldList) {
//
//            switch (field) {
//                case "ProductKind":
//                    int kind = Integer.parseInt(fieldDataMap.get(field).getValue().toString());
//                    if(kind == 1){
//                        goods.setGoodsType(0);
//                    }else{
//                        goods.setGoodsType(1);
//                    }
//                    break;
//                case "Sort":
//                    goods.setSort(Integer.parseInt(fieldDataMap.get(field).getValue().toString()));
//                    break;
//                case "ListPicPath":
//                    String pics = fieldDataMap.get(field).getValue().toString();
//                    if(StrUtil.isNotBlank(pics)){
//                        String[] imgs = pics.split(",");
//                        //封面图
//                        goods.setPicUrl(imgs[0]);
//                        //同步商品图片表
//                        for (String img : imgs) {
//                            KxsShopGoodsPic shopGoodsPic = new KxsShopGoodsPic();
//                            shopGoodsPic.setUrl(img);
//                            shopGoodsPic.setGoodsId(id);
//                            picList.add(shopGoodsPic);
//                        }
//                    }
//                    break;
//                case "Status":
//                    goods.setStatus(Integer.valueOf(validFieldDataMap.get(field).toString()));
//                    break;
//                case "ProductName":
//                    goods.setGoodsName(fieldDataMap.get(field).getValue().toString());
//                    break;
//                case "Details":
//                    goods.setSubtitle(fieldDataMap.get(field).getValue().toString());
//                    break;
//                case "NormJson":
//                    String value = validFieldDataMap.get(field).toString();
//                    if(StrUtil.isNotBlank(value) && value.contains("#cut#")){
//                        String sku = value.substring(0, value.indexOf("#cut#"));
//                        goods.setSpecList(sku);
//                    }
//                    break;
//                case "Contents":
//                    goods.setDetails(fieldDataMap.get(field).getValue().toString());
//                    break;
//                case "ColId":
//                    goods.setColId(fieldDataMap.get(field).getValue().toString());
//                    break;
//                case "Price":
//                    goods.setPrice(new BigDecimal(fieldDataMap.get(field).getValue().toString()));
//                    break;
//                case "LimitCount":
//                    goods.setLimitCount(Integer.valueOf(fieldDataMap.get(field).getValue().toString()));
//                    break;
//                case "StartBuyCount":
//                    goods.setStartByCount(Integer.valueOf(fieldDataMap.get(field).getValue().toString()));
//                    break;
//                case "PublishDate":
//                    goods.setUpTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
//                    break;
//                case "CreateDate":
//                    goods.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
//                    break;
//                case "UpdateDate":
//                    goods.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
//                    break;
//            }
//        }
        //商品图片
        if(!picList.isEmpty()){
            kxsShopGoodsPicService.remove(Wrappers.<KxsShopGoodsPic>lambdaQuery().eq(KxsShopGoodsPic::getGoodsId, goods.getId()));
            for (KxsShopGoodsPic shopGoodsPic : picList) {
                kxsShopGoodsPicService.save(shopGoodsPic);
            }
        }
        if(StrUtil.isNotBlank(goods.getSpecList())){
            kxsShopGoodsSpecService.remove(Wrappers.<KxsShopGoodsSpec>lambdaQuery().eq(KxsShopGoodsSpec::getGoodsId, goods.getId()));

            JSONArray goodsSpecs = JSON.parseArray(goods.getSpecList());
            for (Object goodsSpec : goodsSpecs) {
                KxsShopGoodsSpec kxsShopGoodsSpec = new KxsShopGoodsSpec();
                kxsShopGoodsSpec.setGoodsId(goods.getId());
                JSONObject jsonObject = JSON.parseObject(goodsSpec.toString());
                kxsShopGoodsSpec.setSpecification(jsonObject.getString("name"));

                JSONArray vallist = jsonObject.getJSONArray("vallist");
                JSONArray skus = new JSONArray();
                for (Object val : vallist) {
                    JSONObject valSku = JSON.parseObject(val.toString());
                    skus.add(valSku.getString("name"));
                }
                kxsShopGoodsSpec.setValue(skus.toJSONString());
                kxsShopGoodsSpecService.save(kxsShopGoodsSpec);
            }
        }
        //获取sku列表
        FieldData fieldData = fieldDataMap.get("NormJson");
        if(fieldData.getValue() != null && StrUtil.isNotBlank(fieldData.getValue().toString()) && fieldData.getValue().toString().contains("#cut#") ){

            String value = fieldData.getValue().toString();

            List<KxsShopGoodsSku> specs = new ArrayList<>();

            String goodsSku = value.substring(value.indexOf("#cut#") + 5);
            JSONArray goodsSkus = JSON.parseArray(goodsSku);
            for (Object sku : goodsSkus) {
                JSONObject jsonObject = JSON.parseObject(sku.toString());
                KxsShopGoodsSku kxsShopGoodsSku = new KxsShopGoodsSku();
                kxsShopGoodsSku.setGoodId(id);
                kxsShopGoodsSku.setPrice(jsonObject.getBigDecimal("price"));
                kxsShopGoodsSku.setLimitCount(jsonObject.getInteger("limitcount"));
                kxsShopGoodsSku.setStartByCount(jsonObject.getInteger("startbuycount"));
                kxsShopGoodsSku.setStockNum(jsonObject.getInteger("stock"));

                String specStr = jsonObject.getString("title");
                List<String> specifications = new ArrayList<>();
                for (Object spec : JSON.parseArray(specStr)) {
                    JSONObject specObj = JSON.parseObject(spec.toString());
                    specifications.add(specObj.getString("name"));
                }
                kxsShopGoodsSku.setSpecifications(JSON.toJSONString(specifications));
                specs.add(kxsShopGoodsSku);
            }
            for (KxsShopGoodsSku spec : specs) {
                KxsShopGoodsSku skuServiceOne = kxsShopGoodsSkuService.getOne(Wrappers.<KxsShopGoodsSku>lambdaQuery()
                        .eq(KxsShopGoodsSku::getGoodId, id)
                        .eq(KxsShopGoodsSku::getSpecifications, spec.getSpecifications()));

                if(skuServiceOne == null){
                    kxsShopGoodsSkuService.save(spec);
                }else{
                    spec.setId(skuServiceOne.getId());
                    kxsShopGoodsSkuService.updateById(spec);
                }
            }

        }else{
            //添加默认规格
            KxsShopGoodsSku kxsShopGoodsSku = new KxsShopGoodsSku();
            kxsShopGoodsSku.setGoodId(id);
            kxsShopGoodsSku.setPrice(new BigDecimal(fieldDataMap.get("Price").getValue().toString()));
            kxsShopGoodsSku.setLimitCount(Integer.valueOf(fieldDataMap.get("LimitCount").getValue().toString()));
            kxsShopGoodsSku.setStartByCount(Integer.valueOf(fieldDataMap.get("StartBuyCount").getValue().toString()));
            kxsShopGoodsSku.setStockNum(Integer.valueOf(fieldDataMap.get("Stock").getValue().toString()));
            kxsShopGoodsSku.setSpecifications("[\"默认\"]");
            KxsShopGoodsSku skuServiceOne = kxsShopGoodsSkuService.getOne(Wrappers.<KxsShopGoodsSku>lambdaQuery()
                    .eq(KxsShopGoodsSku::getGoodId, id)
                    .eq(KxsShopGoodsSku::getSpecifications, kxsShopGoodsSku.getSpecifications()));
            if(skuServiceOne == null){
                kxsShopGoodsSkuService.save(kxsShopGoodsSku);
            }else{
                kxsShopGoodsSku.setId(skuServiceOne.getId());
                kxsShopGoodsSkuService.updateById(kxsShopGoodsSku);
            }
        }
        //添加商品
        KxsShopGoods kxsShopGoods = baseMapper.selectById(goods.getId());
        if(kxsShopGoods == null){
            baseMapper.insert(goods);
        }else{
            baseMapper.updateById(goods);
        }
    }
}

