package com.org.hktshop.service.product;

import com.alibaba.fastjson.JSON;
import com.org.hktshop.Interface.global.IHktLanguageService;
import com.org.hktshop.Interface.product.IHktGoodsActivityService;
import com.org.hktshop.Interface.product.IHktGoodsCategoryService;
import com.org.hktshop.Interface.product.IHktPriceRegulationService;
import com.org.hktshop.base.BaseService;
import com.org.hktshop.base.MongoHelper;
import com.org.hktshop.entity.product.*;
import com.org.hktshop.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 java.text.DecimalFormat;
import java.util.*;

/**
 * @author owen
 */
@Service
public class HktPriceRegulationServiceImpl extends BaseService<HktPriceRegulation> implements IHktPriceRegulationService {

    private Logger logger = LoggerFactory.getLogger(HktPriceRegulationServiceImpl.class);
    @Autowired
    private MongoHelper<HktPriceRegulation> mongoHelper;

    @Autowired
    private MongoHelper<HktCountRegulation> hktCountRegulationMongoHelper;

    @Autowired
    IHktGoodsActivityService goodsActivityService;

    @Autowired
    IHktGoodsCategoryService categoryService;

    @Autowired
    private MongoHelper<HktGoodItem> goodItemMongoHelper;

//    @Autowired
//    private IHktLanguageService hktLanguageService;

    @Autowired
    private GoodsUtils goodsUtils;

    @Override
    public void updatePriceTemplate(HktPriceRegulation priceRegulation) throws Exception {

        if (StringUtils.isNull(priceRegulation.getId())) {
            String sql = ExecSqlLib.GetInsertSql(priceRegulation);
            int autoId = this.baseJdbcDao.getAutoId(priceRegulation);
            boolean execute = this.baseJdbcDao.execute(sql);
            if (execute) {
                priceRegulation.setId(autoId + "");
                mongoHelper.save(priceRegulation);
            }
        } else {
            String sql = ExecSqlLib.GetUpdateSql(priceRegulation);
            boolean execute = this.baseJdbcDao.execute(sql);
            if (execute) {
                mongoHelper.mongoUpdate(priceRegulation.getId(), priceRegulation, HktPriceRegulation.class);
            }
        }
    }

    @Override
    public void delPriceTemplate(HktPriceRegulation priceRegulation) {
        String sql = ExecSqlLib.GetDeleteByIdSql(priceRegulation.getId(), priceRegulation);
        boolean execute = this.baseJdbcDao.execute(sql);
        if (execute) {
            mongoHelper.removeById(priceRegulation.getId(), HktPriceRegulation.class);
        }
    }

    @Override
    public Object queryPriceRegulationByPage(HktPriceRegulation priceRegulation) {
        return mongoHelper.findPage(priceRegulation, HktPriceRegulation.class);
    }

    @Override
    public HktPriceRegulation findPriceRegulation(HktPriceRegulation priceRegulation) {
        return mongoHelper.findOne(priceRegulation, HktPriceRegulation.class);
    }

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


    @Override
    public void callPriceRegulation(HktGoods hktGoodItem) {
        boolean flag = false;
        try {
            int address = IpUtils.getAddress();
            Criteria e = Criteria.where("sysType").is(address);

            Criteria criteria = new Criteria();
            Criteria a = Criteria.where("startPrice").lt(hktGoodItem.getPrice());
            Criteria b = Criteria.where("endPrice").gte(hktGoodItem.getPrice());
            criteria.andOperator(a, b, e);
            Query query = new Query(criteria);

            HktPriceRegulation hktPriceRegulation = mongoHelper.findOne(query, HktPriceRegulation.class);

            int goodsType = hktGoodItem.getGoodsType();
            HktGoodsActivity activity = new HktGoodsActivity();
            if (goodsType != 0 && !StringUtils.isNull(hktGoodItem.getActivityId())) {
                activity.setId(hktGoodItem.getActivityId());
                activity = goodsActivityService.queryActivity(activity);
                if (activity != null) {
                    long startTime = DateUtil.StringToDate1(activity.getStartTime()).getTime();
                    long endTime = DateUtil.StringToDate1(activity.getEndTime()).getTime();
                    //活动期间
                    if (DateUtil.getTimeBetween(startTime) >= 0 && DateUtil.getTimeBetween(endTime) <= 0) {
                        flag = true;
                    }
                }
            }

            Criteria cri = new Criteria();

            Criteria  c = Criteria.where("categoryId").is(hktGoodItem.getCategoryId());

            Criteria d = Criteria.where("type").is(hktGoodItem.getGoodUseType());

            cri.andOperator(c, d, e);
            Query queryCount = new Query(cri);

            HktCountRegulation hktCountRegulation = hktCountRegulationMongoHelper.findOne(queryCount, HktCountRegulation.class);
            List<Map<String, Object>> mapList = new ArrayList<>();
            int i=0;
            while (i < 3){
                Map<String, Object> map = new HashMap<>();
                String regulationNum = hktPriceRegulation.getRegulationNum(i);
                if (regulationNum.toUpperCase().contains("M")) {
                    Double aDouble = Double.valueOf(regulationNum.toUpperCase().replace("M", ""));
                    int countNum = (int) (hktGoodItem.getPackCount() * aDouble);
                    /*if(countNum > 500 && i==1){
                        countNum=500;
                    }*/
                    map.put("num", countNum);
                } else {
                    map.put("num", regulationNum);
                }
                //阶梯价格倍数
                double regulationPrice = hktCountRegulation.getRegulationPrice(i);
                DecimalFormat dfs = new DecimalFormat("0.000000");
                double tempPrice = hktGoodItem.getPrice() * regulationPrice;
                if (flag) {
                    map.put("price", dfs.format(tempPrice * activity.getRate()));
                    map.put("oldPrice", dfs.format(tempPrice));
                } else {
                    map.put("price", dfs.format(tempPrice));
                }
                mapList.add(map);
                i++;
            }
//            hktGoodItem.setSetUp(Integer.parseInt(hktPriceRegulation.getRegulationNum(0)));
            hktGoodItem.setSetUp(hktGoodItem.getPackCount());
            hktGoodItem.setPriceTemplate(JSON.toJSONString(mapList));
            double price = Double.parseDouble(mapList.get(2).get("price") + "");
            hktGoodItem.setPrice(price);
        } catch (Exception e) {

            //e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> getPriceRegulationInfo(HktGoodItem hktGoodItem) {
        boolean flag = false;
        DecimalFormat df = new DecimalFormat("#0.000000");
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        Map<String, Object> map = new HashMap<>();
        String collectionName = goodsUtils.getCollectionName(hktGoodItem.getLanguage());
        HktGoodItem one = goodItemMongoHelper.findOne(hktGoodItem, collectionName, HktGoodItem.class);
        Criteria criteria = new Criteria();
        Criteria c = Criteria.where("startPrice").lt(one.getPrice());
        Criteria d = Criteria.where("endPrice").gte(one.getPrice());
        criteria.andOperator(c, d);
        Query query = new Query(criteria);
        HktPriceRegulation hktPriceRegulation = mongoHelper.findOne(query, HktPriceRegulation.class);
        if(hktPriceRegulation == null){
            Query query1 = new Query(Criteria.where("startPrice").lt(100));
            hktPriceRegulation = mongoHelper.findOne(query1, HktPriceRegulation.class);
        }
        int goodsType = one.getGoodsType();
        HktGoodsActivity activity = new HktGoodsActivity();
        if (goodsType != 0 && !StringUtils.isNull(one.getActivityId())) {
            activity.setId(one.getActivityId());
            activity = goodsActivityService.queryActivity(activity);
            if(activity != null){
                logger.info("商品优惠折扣信息为：" + activity);
                long startTime = DateUtil.StringToDate1(activity.getStartTime()).getTime();
                long endTime = DateUtil.StringToDate1(activity.getEndTime()).getTime();
                //活动期间
                if (DateUtil.getTimeBetween(startTime) >= 0 && DateUtil.getTimeBetween(endTime) <= 0) {
                    flag = true;
                }
            }
        }
        Criteria criteriaCount = new Criteria();
        Criteria a = Criteria.where("categoryId").is(one.getCategoryId());
        Criteria b = Criteria.where("type").is(one.getGoodUseType());
        criteriaCount.andOperator(a,b);
        Query queryCount = new Query(criteriaCount);
        HktCountRegulation hktCountRegulation = hktCountRegulationMongoHelper.findOne(queryCount, HktCountRegulation.class);
        int step = hktGoodItem.getNum();
        Double goodsPrice = one.getPrice();
        double goodsMult = 0;

        for (int i = 4; i >= 0; i--) {
            //当前数量
            int cuurrentNum;
            //阶梯数量倍数
            String regulationNum = hktPriceRegulation.getRegulationNum(i);
            if (regulationNum.toUpperCase().contains("M")) {
                Integer packCount = one.getPackCount();
                Double aDouble = Double.valueOf(regulationNum.toUpperCase().replace("M", ""));
                cuurrentNum = (int) (packCount * aDouble);
                /*if(i == 1 && cuurrentNum >500){
                    cuurrentNum = cuurrentNum;
                }*/
            } else {
                cuurrentNum = Integer.parseInt(regulationNum);
            }
            if (step >= cuurrentNum) {
                double regulationPrice = hktCountRegulation.getRegulationPrice(i);
                goodsMult = regulationPrice;
                break;
            }else {
                goodsMult = hktCountRegulation.getRegulationPrice(0);
            }
        }
        if (flag) {
            double price = goodsPrice * goodsMult;
            double realPrice = goodsPrice * goodsMult * activity.getRate();
            map.put("price", df.format(price));
            map.put("realPrice", df.format(realPrice));
            map.put("totalMoney", decimalFormat.format(realPrice * step));
            map.put("discount", decimalFormat.format((price - realPrice) * step));
            return map;
        } else {
            double realPrice = goodsPrice * goodsMult;
            map.put("price", df.format(realPrice));
            map.put("realPrice", df.format(realPrice));
            map.put("totalMoney", decimalFormat.format(realPrice * step));
            map.put("discount", 0);
            return map;
        }
    }

    @Override
    public Map<String, Object> xcxgetPriceRegulationInfo(HktGoodItem hktGoodItem) {
        DecimalFormat df = new DecimalFormat("#0.000000");
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        Map<String, Object> map = new HashMap<>();
        String collectionName = goodsUtils.getCollectionName(hktGoodItem.getLanguage());
        HktGoodItem one = goodItemMongoHelper.findOne(hktGoodItem, collectionName, HktGoodItem.class);

        Criteria criteriaCount = new Criteria();
        Criteria a = Criteria.where("categoryId").is(one.getCategoryId());
        Criteria b = Criteria.where("type").is(one.getGoodUseType());
        criteriaCount.andOperator(a,b);
        Query queryCount = new Query(criteriaCount);
        HktCountRegulation hktCountRegulation = hktCountRegulationMongoHelper.findOne(queryCount, HktCountRegulation.class);
        int step = hktGoodItem.getNum() * 1000;
        Double goodsPrice = one.getPrice();
            double price = goodsPrice * hktCountRegulation.getMultipleOne();
            map.put("price", df.format(price));
            map.put("realPrice", df.format(price));
            map.put("totalMoney", decimalFormat.format(price * step));
            map.put("discount", 0);
            return map;
    }

    @Override
    public void initData() {
        List<HktPriceRegulation> list = mongoHelper.find(new HktPriceRegulation(), HktPriceRegulation.class);
        if (list.isEmpty()) {
            list = queryList(new HktPriceRegulation());
            /*for (HktPriceRegulation detail : list) {
                mongoHelper.save(detail);
            }*/
            mongoHelper.save(list);
        }
    }
}
