package com.org.hktshop.service.portal.product;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.org.hktshop.Interface.global.IHktLanguageService;
import com.org.hktshop.Interface.portal.IPortalBomService;
import com.org.hktshop.Interface.product.IHktGoodsService;
import com.org.hktshop.Interface.product.IHktPriceRegulationService;
import com.org.hktshop.Interface.product.IHktSearchReplacementService;
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.global.HktLanguage;
import com.org.hktshop.entity.hotking.BomOrder;
import com.org.hktshop.entity.hotking.BomOrderDetail;
import com.org.hktshop.entity.product.HktGoodItem;
import com.org.hktshop.entity.product.HktGoods;
import com.org.hktshop.entity.user.HktUser;
import com.org.hktshop.properties.AliyunOSSProperties;
import com.org.hktshop.service.aliyun.AliyunOssService;
import com.org.hktshop.service.hotking.BomOrderService;
import com.org.hktshop.utils.DateUtil;
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.*;
import java.util.stream.Collectors;

/**
 * @author owen
 */
@Service
public class PortalBomServiceImpl extends BaseService<HktGoodItem> implements IPortalBomService {

    @Autowired
    private MongoHelper<HktGoodItem> mongoHelper;

    @Autowired
    private IHktGoodsService hktGoodsService;

    @Autowired
    private IHktLanguageService languageService;

    @Autowired
    private IHktPriceRegulationService hktPriceRegulationService;

    @Autowired
    private GoodsUtils goodsUtils;

    @Autowired
    private BomOrderService bomOrderService;

    @Autowired
    private IHktSearchReplacementService hktSearchReplacementService;

    @Autowired
    private PortalProductServiceImpl portalProductService;

    @Autowired
    private AliyunOssService aliyunOssService;

    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    @Override
    public BomOrder selectBomList(List<BomOrderDetail> bomOrderDetails, HktUser hktUser){
        BomOrder bo;
        if(hktUser != null && !StringUtils.isNull(hktUser.getHeadImg())){
            BomOrder bomOrder = new BomOrder();
            bomOrder.setList(bomOrderDetails);
            bomOrder.setUserId(hktUser.getId());
            bomOrder.setName("物料清单-" + DateUtil.getDateSecond());
            bomOrder.setCreateTime(DateUtil.getDateTime());
            bomOrder.setImage(hktUser.getHeadImg());
            bomOrder.setDistribution(1);
            bo = bomOrderService.saveBomOrder(bomOrder);
        }else {
            bo = bomOrderService.findBomOrderByUUid(bomOrderDetails.get(0).getBomId());
        }
        List<BomOrderDetail> detailList = bo.getList();
        List<BomOrderDetail> allList = new ArrayList<>();
        List<BomOrderDetail> unList = new ArrayList<>();
        List<BomOrderDetail> list = new ArrayList<>();
        for (BomOrderDetail bomOrderDetail : detailList) {
            HktGoodItem hg = new HktGoodItem();
            hg.setPageNum(1);
            hg.setPageSize(1);
            hg.setLanguage("1");
            hg.setQueryValue(bomOrderDetail.getMaterialSn());
            Page<HktGoodItem> hktGoodItemPage = portalProductService.selectProductLike(hg);
            HktGoodItem hktGoodItem = null;
            if(hktGoodItemPage.getRecords().size() > 0){
                hktGoodItem = hktGoodItemPage.getRecords().get(0);
            }
            long count = hktGoodItemPage.getTotal();
            if (hktGoodItem != null) {
                bomOrderDetail.setGoodsId(hktGoodItem.getId());
                if(StringUtils.isNull(bomOrderDetail.getNum())){
                    bomOrderDetail.setMatchNum(hktGoodItem.getPackCount()+"");
                }else {
                    int i = bomOrderDetail.getNum() % hktGoodItem.getPackCount() == 0 ? bomOrderDetail.getNum() / hktGoodItem.getPackCount() : bomOrderDetail.getNum() / hktGoodItem.getPackCount() + 1;
                    bomOrderDetail.setMatchNum(hktGoodItem.getPackCount() * i + "");
                }

                //匹配型号
                bomOrderDetail.setMatchMaterialSn(hktGoodItem.getMaterialSn());
                //参数
                bomOrderDetail.setMatchParam(hktGoodItem.getCategoryName() + " " + hktGoodItem.getName());
                //品牌
                bomOrderDetail.setMatchBrandName(hktGoodItem.getBrandName());
                //手册
                bomOrderDetail.setMatchPdf(hktGoodItem.getGoodsManual());
                bomOrderDetail.setPackageCount(hktGoodItem.getPackCount());

                HktGoodItem hi = new HktGoodItem();
                hi.setNum(Integer.parseInt(bomOrderDetail.getMatchNum()));
                hi.setId(hktGoodItem.getId());
                hi.setLanguage("1");
                Map<String, Object> priceRegulationInfo = hktPriceRegulationService.getPriceRegulationInfo(hi);

                Double dealPrice = Double.valueOf(priceRegulationInfo.get("realPrice") + "");
                //成交价格
                bomOrderDetail.setDealPrice(dealPrice + "");
                //合计
                bomOrderDetail.setTotalMoney(String.format("%.2f", dealPrice * Integer.parseInt(bomOrderDetail.getMatchNum())));
                bomOrderDetail.setCount(count);
                allList.add(bomOrderDetail);
                list.add(bomOrderDetail);
            } else {
                //询价型号
                bomOrderDetail.setTotalMoney("0");
                bomOrderDetail.setCount(0L);
                allList.add(bomOrderDetail);
                unList.add(bomOrderDetail);
            }

        }
        List<BomOrderDetail> collect = allList.stream().sorted(Comparator.comparingDouble(x -> Double.parseDouble(x.getTotalMoney()))).collect(Collectors.toList());
        Collections.reverse(collect);
        bo.setAllList(allList);
        bo.setUnList(unList);
        bo.setList(list);
        return bo;
    }

    @Override
    public Object importBomExcel(MultipartFile file, String language, HktUser hktUser) throws Exception {
        InputStream is = null;
        List<BomOrderDetail> list = new ArrayList<>();
        is = file.getInputStream();
        Workbook workBook = WorkbookFactory.create(is);
        Sheet sheet = workBook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum() + 1;
        if (lastRowNum > 200) {
            return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(), "上传数据不能超过200条");
        }
        Row titleRow = sheet.getRow(0);
        short lastCellNum = titleRow.getLastCellNum();
        Set<String> set = new TreeSet<>();
        for(int i = 0;i<lastCellNum;i++){
            set.add(ExcelUtil.getCellValue(titleRow.getCell(i)));
        }

        String folderName = aliyunOssService.getFolderName(file.getOriginalFilename());
        OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
        String url = aliyunOssService.uploadByFile(ossClient, file, folderName);
        hktUser.setHeadImg(url);
        if(set.size() < 4 ||!set.contains("料号") || !set.contains("商品参数") || !set.contains("品牌") || !set.contains("数量")){
            BomOrder bomOrder = new BomOrder();
            bomOrder.setImage(url);
            bomOrder.setName(file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")));
            bomOrder.setUserId(hktUser.getId());
            bomOrder.setType(2);
            bomOrder.setUserId(hktUser.getId());
            bomOrder.setCreateTime(DateUtil.getDateTime());
            bomOrderService.saveBomOrder(bomOrder);
            return BaseResult.success();
        }

        for (int i = 1; i < lastRowNum; i++) {
//            Map<String, Object> map = new HashMap<>();
            BomOrderDetail bd = new BomOrderDetail();
            Row row = sheet.getRow(i);
            for (int j = 0; j < lastCellNum; j++) {
                Cell cell = row.getCell(j);
                String cellValue = ExcelUtil.getCellValue(cell);
                switch (ExcelUtil.getCellValue(titleRow.getCell(j))) {
                    //料号,商品参数,品牌,数量
                    case "料号":
                        bd.setMaterialSn(cellValue);
                        break;
                    case "商品参数":
                        bd.setParam(cellValue);
                        break;
                    case "品牌":
                        bd.setBrandName(cellValue);
                        break;
                    case "数量":
                        try {
                            bd.setNum(Integer.parseInt(cellValue));
                        } catch (Exception e) {
                            bd.setNum(1);
                        }
                }
                bd.setLanguage(language);
            }
            if(StringUtils.isNull(bd.getMaterialSn()) && StringUtils.isNull(bd.getParam()) && StringUtils.isNull(bd.getBrandName())){
                return BaseResult.fail("第"+i+"行主要匹配参数不能全为空");
            }
            list.add(bd);
        }
        BomOrder bomOrder = selectBomList(list, hktUser);
        return BaseResult.successWithData(bomOrder);
    }

    @Override
    public BomOrderDetail findByBomOrderDetail(BomOrderDetail bomOrderDetail, String language) {
        String collectionName = goodsUtils.getCollectionName(language);
        Criteria criteriaAll = new Criteria();
        List<Criteria> criteriaList = new ArrayList<>();
        String queryValue = "";
        if (!StringUtils.isNull(bomOrderDetail.getMaterialSn())) {
            queryValue += " " + bomOrderDetail.getMaterialSn();
        }

        if (!StringUtils.isNull(bomOrderDetail.getParam())) {
            queryValue += " " + bomOrderDetail.getParam();
        }

        if (!StringUtils.isNull(bomOrderDetail.getBrandName())) {
            queryValue += " " + bomOrderDetail.getBrandName();
        }

        if (!StringUtils.isNull(queryValue)) {
//            List<String> stringList = IKAnalyzerUtil.IKAnalysis(queryValue);
            List<String> stringList = Arrays.asList(queryValue.toUpperCase().split(" "));
            Criteria[] criteria = new Criteria[stringList.size()];
            for (int i = 0; i < stringList.size(); i++) {
                if (!StringUtils.isNull(stringList.get(i))) {
                    String replaceForMatching = hktSearchReplacementService.findReplaceForMatching(stringList.get(i)).trim();
                    criteria[i] = Criteria.where("queryValue").regex(replaceForMatching, "i");
                    criteriaList.add(criteria[i]);
                }
            }
        }

        Criteria[] criterialist = new Criteria[criteriaList.size()];
        for (int i = 0; i < criteriaList.size(); i++) {
            criterialist[i] = criteriaList.get(i);
        }
        if (criterialist.length > 0) {
            criteriaAll.andOperator(criterialist);
        }
        Query query = new Query(criteriaAll);
        long count = mongoHelper.count(query, HktGoodItem.class, collectionName);
        HktGoodItem hktGoodItem = mongoHelper.findOne(query, HktGoodItem.class, collectionName);

        if (hktGoodItem != null) {
            bomOrderDetail.setGoodsId(hktGoodItem.getId());
            int dealNum = bomOrderDetail.getNum();
            if (dealNum == 0 || dealNum < hktGoodItem.getPackCount()) {
                dealNum = hktGoodItem.getPackCount();
            } else {
                int num = dealNum % hktGoodItem.getPackCount() == 0 ? dealNum % hktGoodItem.getPackCount() : dealNum % hktGoodItem.getPackCount() + 1;
                dealNum = num * hktGoodItem.getPackCount();
            }

            //匹配型号
            bomOrderDetail.setMatchMaterialSn(hktGoodItem.getMaterialSn());
            //参数
            bomOrderDetail.setMatchParam(hktGoodItem.getCategoryName() + " " + hktGoodItem.getName());
            //品牌
            bomOrderDetail.setMatchBrandName(hktGoodItem.getBrandName());
            //手册
            bomOrderDetail.setMatchPdf(hktGoodItem.getGoodsManual());

            bomOrderDetail.setMatchNum(dealNum + "");

            HktGoodItem hi = new HktGoodItem();
            hi.setNum(dealNum);
            hi.setId(hktGoodItem.getId());
            hi.setLanguage("1");
            Map<String, Object> priceRegulationInfo = hktPriceRegulationService.getPriceRegulationInfo(hi);

//                     String dealPrice = priceRegulationInfo.get("realPrice");
            Double dealPrice = Double.valueOf(priceRegulationInfo.get("realPrice") + "");
            //成交价格
            bomOrderDetail.setDealPrice(dealPrice + "");
            //合计
            bomOrderDetail.setTotalMoney(String.format("%.2f", dealPrice * Integer.parseInt(bomOrderDetail.getMatchNum())));
            bomOrderDetail.setCount(count);
        } else {
            //询价型号
//                hashMap.put("enquiryType", map.get("materialSn"));
            bomOrderDetail.setTotalMoney("0");
            bomOrderDetail.setCount(0L);
        }
        return bomOrderDetail;
    }
}
