package com.org.hktshop.service.hotking.impl;

import com.org.hktshop.Dao.Intface.IGoodsItemDao;
import com.org.hktshop.Interface.product.IHktGoodsAttrService;
import com.org.hktshop.Interface.product.IHktGoodsCategoryService;
import com.org.hktshop.base.BaseService;
import com.org.hktshop.base.MongoHelper;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.product.HktGoodItem;
import com.org.hktshop.entity.product.HktGoods;
import com.org.hktshop.entity.product.HktGoodsAttrItem;
import com.org.hktshop.entity.product.HktGoodsCategory;
import com.org.hktshop.entity.vo.HktBrandInfo;
import com.org.hktshop.entity.vo.HktGoodsCategoryVo;
import com.org.hktshop.service.hotking.SampleGoodsAttrQueryService;
import com.org.hktshop.service.hotking.SampleService;
import com.org.hktshop.utils.ExecSqlLib;
import com.org.hktshop.utils.GoodsUtils;
import com.org.hktshop.utils.MathUtil;
import com.org.hktshop.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author hotking03
 */
@Service
public class SampleServiceImpl extends BaseService<HktGoods> implements SampleService {
    @Autowired
    private IHktGoodsCategoryService hktGoodsCategoryService;

    @Autowired
    private GoodsUtils goodsUtils;

    @Autowired
    IGoodsItemDao goodsItemDao;

    @Autowired
    private IHktGoodsAttrService hktGoodsAttrService;

    @Autowired
    private SampleGoodsAttrQueryService sampleGoodsAttrQueryService;

    private MongoHelper<HktGoodItem> hktGoodsPageItemMongoHelper = new MongoHelper<>();

    @Override
    public Object queryList(HktGoodItem hktGoods) {
        List<Criteria> criteriaList = new ArrayList<>();
        Criteria criatira = new Criteria();
        String categoryId = hktGoods.getCategoryId();
        HktGoodsCategory category = new HktGoodsCategory();
        category.setId(categoryId);
        HktGoodsCategory categoryTail = hktGoodsCategoryService.queryCategory(category);
        if (categoryTail != null && categoryTail.getLevel() == 1) {
            categoryTail.setLanguage(hktGoods.getLanguage());
            Criteria[] criteriaAttrs = getCriteriaAttr(hktGoods, true);
            for (Criteria cr : criteriaAttrs) {
                criteriaList.add(cr);
            }
        } else {
            criteriaList.add(getCriteriaAttr(hktGoods, false)[0]);
        }

        if (!StringUtils.isNull(hktGoods.getQueryValue())) {
            criteriaList.add(Criteria.where("materialSn").is(hktGoods.getQueryValue()));
        }

        criteriaList.add(Criteria.where("isSample").is("1"));
        Criteria[] criterialist = new Criteria[criteriaList.size()];
        for (int i = 0; i < criteriaList.size(); i++) {
            criterialist[i] = criteriaList.get(i);
        }
        if (criterialist.length > 0) {
            criatira.andOperator(criterialist);
        }

        Query query = new Query(criatira);
        query.with(new Sort(Sort.Direction.ASC, "brandId"));
        //1:升序  2:降序
        if ("2".equals(hktGoods.getSort())) {
            query.with(new Sort(Sort.Direction.DESC, "price"));
        } else {
            query.with(new Sort(Sort.Direction.ASC, "price"));
        }

        String collectionName = goodsUtils.getCollectionName(hktGoods.getLanguage());
        Page<HktGoodItem> hktGoodsItem = hktGoodsPageItemMongoHelper.findPage(hktGoods, query, HktGoodItem.class, collectionName);

        Map<String, Object> objectMap = new HashMap<>();


        HktGoodsCategory cg = new HktGoodsCategory();
        cg.setId(hktGoods.getCategoryId());
        cg.setLevel(categoryTail.getLevel());
        cg.setLanguage(hktGoods.getLanguage());
        Object hktGoodsAttrQueryItems = sampleGoodsAttrQueryService.selectSampleAttr(cg);
        objectMap.put("QueryItems", hktGoodsAttrQueryItems);
        hktGoodsItem.setObject(objectMap);
        return hktGoodsItem;
    }


    private MongoHelper<HktGoodsCategory> mongoHelperSampleCategory = new MongoHelper<>();
    @Override
    public void addSapmle(HktGoods hktGoods) {
        String sql = ExecSqlLib.GetUpdateSql(hktGoods);
        if(this.baseJdbcDao.execute(sql)){
            sql = ExecSqlLib.GetQuerySql(hktGoods);
            HktGoods query = this.baseJdbcDao.query(sql, hktGoods);
            goodsItemDao.UpdateCache(query);
            sampleGoodsAttrQueryService.saveSampleAttr(query);
            String categoryId = query.getCategoryId();
            HktGoodsCategory hgc = new HktGoodsCategory();
            hgc.setId(categoryId);
            HktGoodsCategory hktGoodsCategory = hktGoodsCategoryService.queryCategory(hgc);
            HktGoodsCategory sampleCategory = mongoHelperSampleCategory.findOne(hktGoodsCategory, "sampleCategory",HktGoodsCategory.class);
            if(sampleCategory == null){
                mongoHelperSampleCategory.save(hktGoodsCategory,"sampleCategory");
            }
            HktGoodsCategory hgc1 = new HktGoodsCategory();
            hgc1.setId(hktGoodsCategory.getParentId());
            HktGoodsCategory hktGoodsCategory1 = hktGoodsCategoryService.queryCategory(hgc1);
            HktGoodsCategory sampleCategory1 = mongoHelperSampleCategory.findOne(hktGoodsCategory1, "sampleCategory", HktGoodsCategory.class);
            if(sampleCategory1 == null){
                mongoHelperSampleCategory.save(hktGoodsCategory1,"sampleCategory");
            }
        }
    }

    @Override
    public void delSample(HktGoods hktGoods) {
        String sql = ExecSqlLib.GetUpdateSql(hktGoods);
        if(this.baseJdbcDao.execute(sql)){
            HktGoods query = this.baseJdbcDao.query(sql, hktGoods);
            goodsItemDao.UpdateCache(query);
        }
    }

    @Override
    public long sampleCount(HktGoods hktGoods) {
        Criteria criteria = Criteria.where("isSample").is("1");
        Query query = new Query(criteria);
        String collectionName = goodsUtils.getCollectionName(hktGoods.getLanguage());
        return hktGoodsPageItemMongoHelper.count(query,HktGoodItem.class,collectionName);
    }

    @Override
    public List<HktGoodsCategoryVo> queryCategoryVo(HktGoodsCategory hktGoodsCategory) {
        List<HktGoodsCategory> list = mongoHelperSampleCategory.find(hktGoodsCategory, HktGoodsCategory.class, "sampleCategory");
        //排序算法
        Collections.sort(list, new Comparator<HktGoodsCategory>() {
            @Override
            public int compare(HktGoodsCategory o1, HktGoodsCategory o2) {
                if (o1.getLevel().compareTo(o2.getLevel()) == 0) {
                    if (o1.getSort().compareTo(o2.getSort()) == 0) {
                        Integer t1 = Integer.parseInt(o1.getId());
                        Integer t2 = Integer.parseInt(o2.getId());
                        if (t1 == t2) return 0;
                        else if (t1 > t2) return 1;
                        else return -1;
//                        return t1>t2;
                    } else {
                        return o1.getSort().compareTo(o2.getSort());
                    }
                } else {
                    if (o1.getSort().compareTo(o2.getSort()) == 0) {
                        Integer t1 = Integer.parseInt(o1.getId());
                        Integer t2 = Integer.parseInt(o2.getId());
                        if (t1 == t2) return 0;
                        else if (t1 > t2) return 1;
                        else return -1;

//                        return t1.compareTo(t2);
                    } else {
                        return o1.getSort().compareTo(o2.getSort());
                    }
                }
            }
        });

        //todo 如何转义
        List<HktGoodsCategoryVo> voList = new ArrayList<>();
        for (HktGoodsCategory cate : list) {
            if (cate.getLevel() == 1) {
                HktGoodsCategoryVo vo = new HktGoodsCategoryVo();
                vo.setId(cate.getId());
                vo.setLevel(cate.getLevel());
                vo.setFno(cate.getFno());
                vo.setNameCh(cate.getNameCh());
                vo.setNameEn(cate.getNameEn());
                vo.setImage(cate.getImage());
                vo.setIsHot(cate.getIsHot());
                vo.setIsShow(cate.getIsShow());
                vo.setSort(cate.getSort());
                vo.setGoodsNum(cate.getGoodsNum());
                vo.setOnSaleNum(cate.getOnSaleNum());
                vo.setCreateTime(cate.getCreateTime());
                vo.setModifyTime(cate.getModifyTime());
                voList.add(vo);
            } else {
                for (HktGoodsCategoryVo vo : voList) {
                    if (cate.getParentId().equals(vo.getId())) {
                        vo.getSubCategory().add(cate);
                        //统计商品数量
                        Integer n = MathUtil.addInt(vo.getGoodsNum(), cate.getGoodsNum());
                        vo.setGoodsNum(n);

                        n = MathUtil.addInt(vo.getOnSaleNum(), cate.getOnSaleNum());
                        vo.setOnSaleNum(n);
                        break;
                    }
                }
            }
        }
        return voList;

    }

    @Override
    public Object hotSample(HktGoodItem hktGoodItem) {
        Criteria criteria = Criteria.where("isSample").is(hktGoodItem.getIsSample()).and("hotSample").is(hktGoodItem.getHotSample());
        String collectionName = goodsUtils.getCollectionName(hktGoodItem.getLanguage());
        Query query = new Query(criteria);
        return  hktGoodsPageItemMongoHelper.findPage(hktGoodItem, query, HktGoodItem.class, collectionName);
    }


    private Criteria[] getCriteriaAttr(HktGoodItem hktGoods, boolean flag) {
        List<HktGoodsAttrItem> attrs = hktGoods.getAttrs();
        Criteria[] ct = new Criteria[attrs.size()+1];
        if (attrs.size() > 0) {
            for (int i = 0; i < attrs.size(); i++) {
                String attrValue = attrs.get(i).getAttrValue();

                String[] splitValue = attrValue.split("&");
                String attrId = attrs.get(i).getAttrId();
                if ("封装".equals(attrId) || "specification".equals(attrId)) {
                    ct[i] = Criteria.where("packageSpecification").in(splitValue);
                } else if("品牌".equals(attrId)){
                    if("合科泰".equals(attrValue)){
                        String replace = attrValue.replace("合科泰", "合科泰电子");
                        splitValue = replace.split(",");
                    }
                    List<String> stringList = new ArrayList<>();
                    List<HktBrandInfo> hktBrandInfos = hktGoodsCategoryService.branCategoryList(splitValue);
                    for(HktBrandInfo hbf : hktBrandInfos){
                        stringList.add(hbf.getBrandDesc_ch().getName() + "|" + hbf.getBrandDesc_en().getName());
                    }
                    ct[i] = Criteria.where("brandName").in(stringList);
                }else {
                    ct[i] = Criteria.where("attrs.attrId").is(attrs.get(i).getAttrId()).and("attrs.attrValue").in(splitValue);
                }
            }
            //flag true 一级菜单  false 二级菜单
            if (flag) {
                HktGoodsCategory hg = new HktGoodsCategory();
                hg.setParentId(hktGoods.getCategoryId());
                List<HktGoodsCategory> hktGoodsCategories = hktGoodsCategoryService.queryLists(hg);
                Set<String> set = new HashSet<>();
                for (HktGoodsCategory hc : hktGoodsCategories) {
                    set.add(hc.getId());
                }
                Criteria parentId = Criteria.where("categoryId").in(set);
                ct[ct.length - 1] = parentId;
            } else {
                Criteria categoryCriteria = Criteria.where("categoryId").is(hktGoods.getCategoryId());
                ct[ct.length - 1] = categoryCriteria;
            }
        } else {
            ct = new Criteria[1];
            if (flag) {
                HktGoodsCategory hg = new HktGoodsCategory();
                hg.setParentId(hktGoods.getCategoryId());
                List<HktGoodsCategory> hktGoodsCategories = hktGoodsCategoryService.queryLists(hg);
                Set<String> set = new HashSet<>();
                for (HktGoodsCategory hc : hktGoodsCategories) {
                    set.add(hc.getId());
                }
                Criteria parentId = Criteria.where("categoryId").in(set);
                ct[0] = parentId;
            } else {
                Criteria categoryCriteria = Criteria.where("categoryId").is(hktGoods.getCategoryId());
                ct[0] = categoryCriteria;
            }

        }
        return ct;
    }
}
