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

import com.org.hktshop.Interface.product.IHktPriceRegulationService;
import com.org.hktshop.base.BaseResult;
import com.org.hktshop.base.BaseService;
import com.org.hktshop.base.MongoHelper;
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.user.HktUser;
import com.org.hktshop.service.hotking.BomOrderService;
import com.org.hktshop.service.portal.product.PortalBomServiceImpl;
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.*;

/**
 * @author owen
 */
@Service
public class BomOrderServiceImpl extends BaseService<BomOrder> implements BomOrderService {

    @Autowired
    private MongoHelper<HktGoodItem> mongoHelper;

    @Autowired
    private BomOrderDetailServiceImpl bomOrderDetailServiceImpl;

    @Autowired
    private IHktPriceRegulationService hktPriceRegulationService;

    @Autowired
    private GoodsUtils goodsUtils;

    @Override
    public List<Map<String, Object>> selectBomList(List<Map> maps) {
        String collectionName = goodsUtils.getCollectionName((String) maps.get(0).get("language"));
        List<Map<String, Object>> 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) {
                for (HktGoodItem hktGoodItem : hktGoodItemList) {
                    Map<String, Object> hashMap = new HashMap<>();
                    hashMap.put("id", hktGoodItem.getId());
                    //单价
                    hashMap.put("price", hktGoodItem.getPrice());
                    //起订量/库存量
                    hashMap.put("ration", hktGoodItem.getSetUp() + "/" + hktGoodItem.getStoreCount());
                    //品牌
                    hashMap.put("brandName", hktGoodItem.getBrandName());
                    //购买数量 store 0:库存不够  1:库存够
                    int dealNum = Integer.parseInt(map.get("num") + "");
                    /*int storeCount = hktGoodItem.getStoreCount() * 2 / 3;
                    if ( dealNum > storeCount) {
                        hashMap.put("num", storeCount);
                    }else if(dealNum < hktGoodItem.getSetUp()){
                        hashMap.put("num", hktGoodItem.getSetUp());
                    } else {
                        hashMap.put("num", map.get("num"));
                    }*/
                    hashMap.put("num",dealNum);
                    //询价型号
                    hashMap.put("enquiryType", map.get("materialSn"));
                    //匹配型号
                    hashMap.put("matchType", hktGoodItem.getMaterialSn());
                    hktGoodItem.setNum(dealNum);
                    Map<String, Object> priceRegulationInfo = hktPriceRegulationService.getPriceRegulationInfo(hktGoodItem);

//                     String dealPrice = priceRegulationInfo.get("realPrice");
                    Double dealPrice = Double.valueOf(priceRegulationInfo.get("realPrice")+"");
                    //成交价格
                    hashMap.put("dealPrice", dealPrice);
                    //合计
                    hashMap.put("totalMoney", String.format("%.2f", dealPrice * Integer.parseInt(map.get("num")+"")));
                    list.add(hashMap);
                }
            } else {
                //没有匹配到的
                Map<String, Object> hashMap = new HashMap<>();
                //询价型号
                hashMap.put("enquiryType", map.get("materialSn"));
                hashMap.put("totalMoney",0);
                list.add(hashMap);
            }
        }
        return list;
    }

    @Override
    public Object importBomExcel(MultipartFile file,String language) 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+"行数量不正确");
                    }
                }
                map.put("language", language);
            }
            list.add(map);
        }
        return BaseResult.successWithData(selectBomList(list));
    }

    @Override
    public BomOrder saveBomOrder(BomOrder bomOrder){
        String uuid = bomOrder.getUuid();
        if(StringUtils.isNull(bomOrder.getUuid())){
            uuid = UUID.randomUUID().toString().replace("-","");
        }
        List<String> sqls = new ArrayList<>();
        bomOrder.setUuid(uuid);
        String bomOrderSql = ExecSqlLib.GetInsertSql(bomOrder);
        sqls.add(bomOrderSql);
        List<BomOrderDetail> list = bomOrder.getList();
        if(list != null && list.size() > 0){
            for(BomOrderDetail bd : list){
                bd.setBomId(uuid);
                sqls.add(ExecSqlLib.GetInsertSql(bd));
            }
        }
        boolean b = this.baseJdbcDao.executeTransaction(sqls);
        if(b){
            BomOrder bo = new BomOrder();
            bo.setUuid(uuid);
            BomOrder query = this.baseJdbcDao.query(ExecSqlLib.GetQuerySql(bo), bo);
            BomOrderDetail bomOrderDetail = new BomOrderDetail();
            bomOrderDetail.setBomId(uuid);
            List<BomOrderDetail> bomOrderDetails = bomOrderDetailServiceImpl.queryList(bomOrderDetail);
            query.setList(bomOrderDetails);
            return query;
        }else {
            return new BomOrder();
        }
    }

    @Override
    public Object queryBomOrderPage(BomOrder bomOrder) {
        String sql = ExecSqlLib.GetQuerySql(bomOrder).replace(" order by id"," order by create_time desc");
        return this.baseJdbcDao.queryPage(sql,bomOrder);
    }

    @Override
    public void delBomOrder(BomOrder bomOrder) {
        String sql = ExecSqlLib.GetQuerySql(bomOrder);
        BomOrder query = this.baseJdbcDao.query(sql, bomOrder);
        if(query != null){
            bomOrder.setStatus(1);
            bomOrder.setId(query.getId());
            sql= ExecSqlLib.GetUpdateSql(bomOrder);
            this.baseJdbcDao.execute(sql);
        }
    }


    @Autowired
    private PortalBomServiceImpl portalBomService;
    @Override
    public Object findBomOrder(BomOrder bomOrder) {
        String sql = "select bo.id,bo.`name`,bo.`status`,bo.create_time as createTime,bo.uuid,bo.image,bo.type,bo.remark,bo.distribution,bo.distribution_user as distributionUser,bo.update_time as updateTime,hu.nickname as userId from bom_order bo LEFT JOIN hkt_users hu ON bo.user_id = hu.id where bo.id ="+bomOrder.getId();
        BomOrder query = this.baseJdbcDao.query(sql, bomOrder);
        BomOrderDetail bomOrderDetail = new BomOrderDetail();
        bomOrderDetail.setBomId(query.getUuid());
        List<BomOrderDetail> detailList = bomOrderDetailServiceImpl.queryList(bomOrderDetail);
        if(detailList .size() == 0){
            return query;
        }
        BomOrder bomOrder1 = portalBomService.selectBomList(detailList, null);
        bomOrder1.setUuid(query.getUuid());
        return bomOrder1;
    }

    @Override
    public Object getDealPriceByCount(Map<String, String> map) {
        String id = map.get("id");
        HktGoodItem hktGoodItem = new HktGoodItem();
        hktGoodItem.setId(id);
        hktGoodItem.setNum(Integer.parseInt(map.get("num")));
        hktGoodItem.setLanguage(map.get("language"));
        Map<String, Object> priceRegulationInfo = hktPriceRegulationService.getPriceRegulationInfo(hktGoodItem);
        return Double.valueOf(priceRegulationInfo.get("realPrice")+"");
    }

    @Override
    public Object selectBomOrderPage(BomOrder bomOrder) {
        String sql = "select bo.id,bo.type as type,bo.distribution_user as distributionUser,bo.image,bo.distribution,bo.update_time as updateTime,bo.name,hu.name as userName,hu.nickName,hu.mobile,bo.create_time AS createTime from bom_order bo LEFT JOIN hkt_users hu ON bo.user_id = hu.id  where 1 =1 ";
        StringBuilder sb = new StringBuilder(sql);
        if(!StringUtils.isNull(bomOrder.getType())){
            sb.append(" and bo.type=").append(bomOrder.getType());
        }
        if(!StringUtils.isNull(bomOrder.getDistribution())){
            sb.append(" and bo.distribution=").append(bomOrder.getDistribution());
        }

        if(!StringUtils.isNull(bomOrder.getName())){
            sb.append(" and bo.name like '%").append(bomOrder.getName()).append("%'");
        }

        if(!StringUtils.isNull(bomOrder.getStartTime())){
            sb.append(" and bo.create_time >='").append(bomOrder.getStartTime()).append("'");
        }

        if(!StringUtils.isNull(bomOrder.getEndTime())){
            sb.append(" and bo.create_time <='").append(bomOrder.getEndTime()).append("'");
        }

        sb.append(" ORDER BY bo.update_time,bo.create_time DESC");
        return this.baseJdbcDao.queryPage(sb.toString(),bomOrder);
    }

    @Override
    public BomOrder findBomOrderByUUid(String bomId) {
        BomOrder bomOrder = new BomOrder();
        bomOrder.setUuid(bomId);
        String sql = ExecSqlLib.GetQuerySql(bomOrder);
        BomOrder query = this.baseJdbcDao.query(sql, bomOrder);

        BomOrderDetail bd = new BomOrderDetail();
        bd.setBomId(bomId);
        List<BomOrderDetail> detailList = bomOrderDetailServiceImpl.queryList(bd);
        query.setList(detailList);
        return query;
    }

    @Override
    public void updateBomOrder(BomOrder bomOrder) {
        String sql = ExecSqlLib.GetUpdateSql(bomOrder);
        this.baseJdbcDao.execute(sql);
    }

    @Override
    public void distribution(BomOrder bi) {
        String sql = ExecSqlLib.GetUpdateSql(bi);
        List<String> stringList = ExecSqlLib.GetInsertSqlCount(bi.getList());
        stringList.add(sql);
        this.baseJdbcDao.execute(stringList);
    }

    @Override
    public BomOrder findBomOrderById(String id) {
        BomOrder bomOrder = new BomOrder();
        bomOrder.setId(id);
        return this.baseJdbcDao.query(ExecSqlLib.GetQuerySql(bomOrder),bomOrder);
    }
}
