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

import com.org.hktshop.Dao.Intface.IGoodsItemDao;
import com.org.hktshop.base.BaseResult;
import com.org.hktshop.base.BaseService;
import com.org.hktshop.base.MongoHelper;
import com.org.hktshop.constant.CommonConstant;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.enquiry.HktEnquiry;
import com.org.hktshop.entity.order.HktOrderGoods;
import com.org.hktshop.entity.product.HktGoodItem;
import com.org.hktshop.entity.product.HktGoods;
import com.org.hktshop.service.hotking.SampleGoodsAttrQueryService;
import com.org.hktshop.service.hotking.SampleService;
import com.org.hktshop.service.order.HktOrderGoodsService;
import com.org.hktshop.service.sample.HktSampleService;
import com.org.hktshop.utils.ExecSqlLib;
import com.org.hktshop.utils.GoodsUtils;
import com.org.hktshop.utils.HttpCode;
import com.org.hktshop.utils.StringUtils;
import com.org.hktshop.utils.excel.ExcelUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 样品
 * @author hotking03
 */
@Service
public class HktSampleServiceImpl extends BaseService<HktGoodItem> implements HktSampleService {

    @Autowired
    private MongoHelper<HktGoodItem> mongoHelper;

    @Autowired
    IGoodsItemDao goodsItemDao;

    @Autowired
    private HktOrderGoodsService hktOrderGoodsService;

    @Autowired
    private SampleService sampleService;

    @Autowired
    private GoodsUtils goodsUtils;

    @Override
    public Page<HktEnquiry> selectSample(HktGoodItem hktGoodItem) {


        return null;
    }

    @Override
    public void updateSampleGoods(HktGoods hktGoods) {
        if(StringUtils.isNull(hktGoods.getIsSample())){
            hktGoods.setIsSample("1");
        }
        if(StringUtils.isNull(hktGoods.getStepSample())){
            hktGoods.setStepSample("5");
        }

        if(StringUtils.isNull(hktGoods.getHotSample())){
            hktGoods.setHotSample("0");
        }

        String sql = ExecSqlLib.GetUpdateSql(hktGoods);
        if(this.baseJdbcDao.execute(sql)){

            sql = ExecSqlLib.GetQuerySql(hktGoods);
            HktGoodItem query = this.baseJdbcDao.query(sql, new HktGoodItem());
            goodsItemDao.UpdateCache(query);
           /* String sqlSample = "select DISTINCT gd.id ,gd.ksn,gd.category_id as categoryId,hgc.name_ch as categoryName,gd.step_sample as stepSample,gd.brand_id as brandId,hgc.name_ch as typeName, gd.material_sn as materialSn, gd.ksn as k3id,\n" +
                    "                                                 hbd.name as brandName,gd.price,  gd.goods_type as goodsType,\n" +
                    "                                                 ifnull( gd.goods_img,hgc.image) as goodsImg,gd.step_sample as stepSample,gd.hot_sample as hotSample,gd.is_sample as isSample,\n" +
                    "                                                 concat(hgc.name_ch,'  ', ds.name) as name,gd.create_time as createTime\n" +
                    "                                                 from hkt_goods gd left join hkt_goods_desc ds on ds.language_id = 1 and ds.goods_id = gd.ksn\n" +
                    "                                                left join hkt_brand_desc hbd on ds.language_id = hbd.language_id and  hbd.brand_id = gd.brand_id\n" +
                    "                                                left join hkt_goods_category hgc on gd.category_id = hgc.id where gd.data_state=2 and gd.is_on_sale = 1 and gd.is_sample = 1 and gd.id = "+hktGoods.getId();

            HktGoodItem query = this.baseJdbcDao.query(sqlSample, new HktGoodItem());
            HktGoods hktGoods1 = new HktGoods();
            hktGoods1.setKsn(query.getKsn());
            goodsItemDao.UpdateCache(hktGoods1);
            mongoHelper.removeById(hktGoods.getId(), CommonConstant.HKT_SAMPLE_CACHE_GOODS);
            mongoHelper.save(query, CommonConstant.HKT_SAMPLE_CACHE_GOODS);

            HktGoods hi = new HktGoods();
            hi.setId(hktGoods.getId());
            hi.setIsSample("1");
            sampleService.addSapmle(hi);*/
        }
    }

    @Override
    public void delSampleGoods(HktGoods hktGoods) {
        hktGoods.setIsSample("0");
        String sql = ExecSqlLib.GetUpdateSql(hktGoods);
        if(this.baseJdbcDao.execute(sql)){
            sql = ExecSqlLib.GetQuerySql(hktGoods);
            HktGoodItem query = this.baseJdbcDao.query(sql, new HktGoodItem());
            goodsItemDao.UpdateCache(query);
        }
    }

    @Override
    public Page<HktGoodItem> selectSampleGoods(HktGoodItem hktGoodItem) {
        String collectionName = goodsUtils.getCollectionName(hktGoodItem.getLanguage());
        Criteria criteria = Criteria.where("isSample").is("1");
        if(!StringUtils.isNull(hktGoodItem.getCategoryId())){
            criteria.and("categoryId").is(hktGoodItem.getCategoryId());
        }
        if(!StringUtils.isNull(hktGoodItem.getMaterialSn())){
            criteria.and("materialSn").is(hktGoodItem.getMaterialSn());
        }
        if(!StringUtils.isNull(hktGoodItem.getHotSample())){
            criteria.and("hotSample").is(hktGoodItem.getHotSample());
        }
        Query query = new Query(criteria);
        return mongoHelper.findPage(hktGoodItem, query, HktGoodItem.class, collectionName);
    }

    @Override
    public Object importBomExcel(MultipartFile file) throws Exception{
        InputStream is = null;
        List<Map> list = new ArrayList<>();
        is = file.getInputStream();
        Workbook workBook = WorkbookFactory.create(is);
        Sheet sheet = workBook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum() + 1;
        if (lastRowNum > 20) {
            return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(), "上传数据不能超过20条");
        }
        Row titleRow = sheet.getRow(0);
        short lastCellNum = titleRow.getLastCellNum();
        for (int i = 1; i < lastRowNum; i++) {
            Map<String, Object> map = new HashMap<>();
            Row row = sheet.getRow(i);
            for (int j = 0; j < lastCellNum; j++) {
                Cell cell = row.getCell(j);
                String cellValue = ExcelUtil.getCellValue(cell);
                if (j == 0) {
                    map.put("materialSn", cellValue);
                } else {
                    try {
                        Integer.parseInt(cellValue);
                        map.put("num", cellValue);
                    }catch (Exception e){
                        return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"第"+i+"行数量不正确");
                    }
                }
            }
            list.add(map);
        }
        return BaseResult.successWithData(selectBomList(list));
    }

    @Override
    public Object findSampleGoods(HktGoodItem hktGoods) {
        Criteria criteria = new Criteria();
        Criteria a = Criteria.where("ksn").is(hktGoods.getId());
        Criteria b = Criteria.where("_id").is(hktGoods.getId());
        criteria.orOperator(a,b);

        Query query = new Query(criteria);
        List<HktGoodItem> list = mongoHelper.find(query, HktGoodItem.class, CommonConstant.HKT_SAMPLE_CACHE_GOODS);
        if(list != null && list.size() > 0){
            return BaseResult.successWithData(list.get(0));
        }
        return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"无效的ID,KSN");
    }

    @Override
    public Object addOrderSampleByGoods(HktOrderGoods hktGoods) {
        Criteria criteria = new Criteria();
        Criteria a = Criteria.where("ksn").is(hktGoods.getId());
        Criteria b = Criteria.where("_id").is(hktGoods.getId());
        criteria.orOperator(a,b);

        Query query = new Query(criteria);
        List<HktGoodItem> list = mongoHelper.find(query, HktGoodItem.class, CommonConstant.HKT_SAMPLE_CACHE_GOODS);
        if(list != null && list.size() > 0){
            HktGoodItem hktGoodItem = list.get(0);
            hktGoods.setMaterialSn(hktGoodItem.getMaterialSn());
            hktGoods.setBrandName(hktGoodItem.getBrandName());
            hktGoods.setGoodsCategoryId(hktGoodItem.getCategoryId());
            hktGoods.setGoodsCategoryName(hktGoodItem.getCategoryName());
            hktGoods.setGoodsNum(hktGoodItem.getStepSample());
            hktGoods.setGoodsName(hktGoodItem.getName());
            hktGoods.setGoodsPrice(hktGoodItem.getPrice()+"");
            hktGoods.setGoodsId(hktGoodItem.getId());
            hktGoods.setId("");
            hktOrderGoodsService.updateOrderGoods(hktGoods);
            return BaseResult.success();
        }
        return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"无效的ID,KSN");
    }


    public List<HktGoodItem> selectBomList(List<Map> maps) {
        String collectionName = CommonConstant.HKT_SAMPLE_CACHE_GOODS;
        List<HktGoodItem> list = new ArrayList<>();
        for (Map map : maps) {
            Criteria a = Criteria.where("materialSn").is(map.get("materialSn"));
            Query query = new Query(a);
            List<HktGoodItem> hktGoodItemList = mongoHelper.find(query, HktGoodItem.class, collectionName);
            if(hktGoodItemList != null && hktGoodItemList.size() > 0){
                list.add(hktGoodItemList.get(0));
            }
        }
        return list;
    }
}
