package com.org.hktshop.Dao.Impl;

import com.org.hktshop.Dao.Intface.IGoodsAttrItemDao;
import com.org.hktshop.Dao.Intface.IGoodsItemDao;
import com.org.hktshop.Interface.brand.IHktBrandService;
import com.org.hktshop.Interface.global.IHktLanguageService;
import com.org.hktshop.Interface.product.IHktGoodsCategoryService;
import com.org.hktshop.base.BaseDaoJdbc;
import com.org.hktshop.base.MongoHelper;
import com.org.hktshop.constant.CommonConstant;
import com.org.hktshop.entity.global.HktLanguage;
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.utils.ExecSqlLib;
import com.org.hktshop.utils.GoodsUtils;
import com.org.hktshop.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class HktGoodsItemDaoImpl extends BaseDaoJdbc<HktGoodItem> implements IGoodsItemDao {

    @Autowired
    IHktLanguageService languageService;

    @Autowired
    IGoodsAttrItemDao attrItemDao;

    @Autowired
    IHktBrandService brandService;

    @Autowired
    private GoodsUtils goodsUtils;

    @Value("${aliyun.oss.endpoint}")
    String prefix;

    @Autowired
    IHktGoodsCategoryService categoryService;

    MongoHelper<HktGoodItem> mongoHelper = new MongoHelper<>();

    /****
     * 更新缓存
     * @param goods 全部通过id传递
     * @return
     */
    @Override
    public boolean UpdateCache(HktGoods goods) {

      try{
          String sql = "select gd.ksn as ksn,gd.id as id,category_id as categoryId,gd.hj_type as hjType,gd.hkt_type as hktType,gd.hkt_on_sale as hktOnSale,gd.step_sample as stepSample,gd.is_sample as isSample,hot_sample as hotSample,gd.material_sn as materialSn,gd.brand_id as brandId,gd.ksn as ksn,price as price, " +
                  "gd.k3_price as k3Price,gd.store_count as storeCount,gd.store_company as storeCompany, gd.goods_manual as goodsManual," +
                  "ifnull(gd.goods_img,hgci.image) as goodsImg,ifnull(gd.en_img,hgci.image) as enImg, gd.set_up as setUp,gd.sales_sum as salesSum,gd.goods_type as goodsType, " +
                  "gd.pack_count as packCount,gd.package_specification as packageSpecification, " +
                  "gd.is_on_sale as isOnSale,gd.create_time as createTime,gd.modify_time as modifyTime,gd.data_state as dataState, " +
                  "des.language_id as language,  des.name as name, " +
                  "des.good_remark as goodRemark,des.industry_id as industryId, " +
                  "des.technology_id as technologyId, concat(hgd.ldata,'~',hgd.rdata,' ', hgd.unit) as deliveryNo, " +
                  "des.spec_param as specParam,des.sort as sort,hgci.parent_id as parentCategoryId,  " +
                  " gd.activity_id as activityId, gd.good_use_type as goodUseType," +
                  "CASE des.language_id WHEN 1 THEN hgci.name_ch else hgci.name_en end as parentCategoryName  " +
                  "from hkt_goods gd  left join hkt_goods_desc des on des.goods_id = gd.ksn  " +
                  "left join hkt_goods_delivery hgd on  des.delivery_no = hgd.fno LEFT JOIN ( select hgc.id, hgc.parent_id ,hgc1.name_ch,hgc1.name_en, hgc.image " +
                  "from hkt_goods_category hgc INNER JOIN hkt_goods_category hgc1 ON hgc.parent_id = hgc1.id) as hgci ON gd.category_id = hgci.id" +
                  " where des.goods_id = '" + goods.getKsn() + "'";

          List<HktGoodItem> items = this.queryList(sql, new HktGoodItem());

          List<HktLanguage> languages = languageService.queryList();
          Map<String, HktLanguage> languageMap = new HashMap<>();
          for (HktLanguage l : languages) languageMap.put(l.getId(), l);

          HktBrandInfo find = new HktBrandInfo();
          find.setFno(items.get(0).getBrandId());

          List<HktGoodsAttrItem> attrItems = attrItemDao.queryLists(goods.getKsn());
          Map<String, List<HktGoodsAttrItem>> listMap = new HashMap<>();
          for (HktGoodsAttrItem item : attrItems) {
              if (!listMap.containsKey(item.getLanguageId())) {
                  listMap.put(item.getLanguageId(), new ArrayList<>());
              }
              listMap.get(item.getLanguageId()).add(item);
          }
          HktBrandInfo hktBrandInfo = brandService.queryBrand(find);

          HktGoodsCategory fcate = new HktGoodsCategory();
          fcate.setId(items.get(0).getCategoryId());
          HktGoodsCategory category = categoryService.queryCategory(fcate);
          String goodsRemark = "";
          for (HktGoodItem item : items) {
              HktLanguage language = languageMap.get(item.getLanguage());
              item.setAttrs(listMap.get(item.getLanguage()));
              item.setBrandLogo(hktBrandInfo.getLogo());
              if (StringUtils.isNull(item.getGoodsImg())) item.setGoodsImg(category.getImage());

              if (StringUtils.isNull(item.getEnImg())) item.setEnImg(category.getImage());

              if ("1".equals(language.getId())) {
                  String brandName = hktBrandInfo.getBrandDesc_ch().getName();
                  if (!brandName.equals(hktBrandInfo.getBrandDesc_en().getName()))
                      brandName += "|" + hktBrandInfo.getBrandDesc_en().getName();
                  item.setBrandName(brandName);
                  item.setCategoryName(category.getNameCh());
                  item.setEnImg(item.getGoodsImg());
              } else {
                  item.setBrandName(hktBrandInfo.getBrandDesc_en().getName());
                  item.setCategoryName(category.getNameEn());
                  item.setGoodsImg(item.getEnImg());
              }

//              item.setGoodsManual("http://" + prefix + "/" + item.getGoodsManual());

              String queryValue = item.getMaterialSn() + "|" +
                      item.getCategoryName() + "|" +
                      item.getBrandName() + "|" +
                      item.getName() + "|" +
                      item.getPackageSpecification();
              if(!StringUtils.isNull(item.getSpecParam())){
                  if(item.getSpecParam().endsWith("±5%")){
                      queryValue+="|"+item.getPackageSpecification()+"J";
                  }else if(item.getSpecParam().endsWith("±1%")){
                      queryValue+="|"+item.getPackageSpecification()+"F";
                  }else if(item.getSpecParam().endsWith("±0.1%")){
                      queryValue+="|"+item.getPackageSpecification()+"B";
                  }else if(item.getSpecParam().endsWith("±0.5%")){
                      queryValue+="|"+item.getPackageSpecification()+"D";
                  }
              }

              List<HktGoodsAttrItem> attrs = item.getAttrs();
              if(attrs != null && attrs.size() > 0){
                  for(HktGoodsAttrItem ha : attrs){
                      goodsRemark += ha.getAttrId() +":" + ha.getAttrValue()+" ";
                      queryValue+="|"+ha.getAttrValue();
                  }
                  item.setGoodRemark(goodsRemark);
              }
              item.setQueryValue(queryValue.toUpperCase());
              mongoHelper.removeById(item.getId(), CommonConstant.HKT_Goods_Cache_KeyHead + language.getAbbreviate());
              mongoHelper.save(item, CommonConstant.HKT_Goods_Cache_KeyHead + language.getAbbreviate());
          }
      }catch (Exception e){
          e.printStackTrace();
      }
        return true;
    }

    /****
     * 删除缓存
     * @param goods
     * @return
     */
    @Override
    public boolean DeleteCache(HktGoods goods) {

        List<HktLanguage> languages = languageService.queryList();
        for (HktLanguage l : languages) {
            mongoHelper.removeById(goods.getId(), CommonConstant.HKT_Goods_Cache_KeyHead + l.getAbbreviate());
        }
        return true;
    }

    @Override
    public boolean updateGoodsScore(HktGoodItem hktGoodItem) {
        String collectionName = goodsUtils.getCollectionName("1");
        mongoHelper.mongoUpdateById(hktGoodItem.getId(),hktGoodItem.getScore(),collectionName);
        return true;
    }

    @Override
    public void updateGoodsScores(List<HktGoodItem> list) {
        for(HktGoodItem hktGoodItem : list){
            updateGoodsScore(hktGoodItem);
        }
    }
}
