package com.ywt.service;

import com.ywt.core.*;
import com.ywt.core.utils.Checker;
import com.ywt.core.utils.CollectionUtil;
import com.ywt.core.utils.ExcelHelper;
import com.ywt.core.utils.FormatUtil;
import com.ywt.domain.entity.glasses.DictType;
import com.ywt.domain.entity.glasses.DictTypeRepository;
import com.ywt.domain.entity.glasses.Goods;
import com.ywt.domain.entity.glasses.GoodsRepository;

import com.ywt.params.mg.goods.QueryGoodsListRequest;
import jxl.Workbook;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@DubboService
@Service
public class GoodsService extends ServiceBase {

    private static final Logger logger = LoggerFactory.getLogger(GoodsService.class);

    @Autowired
    @Qualifier("sqlHelperGlasses")
    private SqlHelper sqlHelper;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private DictTypeRepository dictTypeRepository;

    @Autowired
    private UserService userService;


    public PagedList<Goods> queryPageGoodsList(QueryGoodsListRequest request) {
        List<Object> paramList = new ArrayList<>();
        String whereSql = " ( 1=1 )";

        whereSql += "and deleted = 0";

        String name = request.getName();
        if (!Checker.isNull(name)) {
            whereSql += " and (name like ?)";
            paramList.add("%" + name.trim() + "%");
        }

        String brandName = request.getBrandName();
        if (!Checker.isNull(brandName)) {
            whereSql += " and (brand_name like ?)";
            paramList.add("%" + brandName.trim() + "%");
        }

        Integer typeId = request.getTypeId();
        if (!Checker.isNone(typeId)) {
            whereSql += " and (type_id =?)";
            paramList.add(typeId);
        }

        String status = request.getStatus();
        if (!Checker.isNull(status)) {
            int status2 = Integer.parseInt(status);
            whereSql += " and (status = ?)";
            paramList.add(status2);
        }

        int shopId = userService.getShopId();
        whereSql += " and (shop_id =?)";
        paramList.add(shopId);

        String formatDate = "yyyy-MM-dd";
        SimpleDateFormat format = new SimpleDateFormat(formatDate);

        try {
            String createTime = request.getCreateTime();
            if (!Checker.isNull(createTime.trim())) {
                whereSql += " and (create_time >= ?)";
                Date date = format.parse(createTime);
                paramList.add(date);
            }
            String createEndTime = request.getCreateEndTime();
            if (!Checker.isNull(createEndTime.trim())) {
                whereSql += " and ( create_time < ? )";
                Date date = format.parse(createEndTime);

                //把日期往后增加一天.整数往后推,负数往前移动
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, 1);
                //这个时间就是日期往后推一天的结果
                date = calendar.getTime();
                paramList.add(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sqlHelper.getPagedList(request.getPageIndex(), request.getPageSize(), "*", whereSql, "weight desc", Goods.class, paramList.toArray());
    }


    public List<Goods> queryList(QueryGoodsListRequest request) {
        List<Object> paramList = new ArrayList<>();
        String whereSql = " ( 1=1 )";

        whereSql += " and deleted = 0";

        String name = request.getName();
        if (!Checker.isNull(name)) {
            whereSql += " and (name like ?)";
            paramList.add("%" + name.trim() + "%");
        }

        String brandName = request.getBrandName();
        if (!Checker.isNull(brandName)) {
            whereSql += " and (brand_name like ?)";
            paramList.add("%" + brandName.trim() + "%");
        }

        Integer typeId = request.getTypeId();
        if (!Checker.isNone(typeId)) {
            whereSql += " and (type_id =?)";
            paramList.add(typeId);
        }

        String status = request.getStatus();
        if (!Checker.isNull(status)) {
            int status2 = Integer.parseInt(status);
            whereSql += " and (status = ?)";
            paramList.add(status2);
        }

        if (request.getShopId() > 0) {
            whereSql += " and (shop_id =?)";
            paramList.add(request.getShopId());
        } else {
            int shopId = userService.getShopId();
            whereSql += " and (shop_id =?)";
            paramList.add(shopId);
        }

        String formatDate = "yyyy-MM-dd";
        SimpleDateFormat format = new SimpleDateFormat(formatDate);

        try {
            String createTime = request.getCreateTime();
            if (!Checker.isNull(createTime)) {
                whereSql += " and (create_time >= ?)";
                Date date = format.parse(createTime);
                paramList.add(date);
            }
            String createEndTime = request.getCreateEndTime();
            if (!Checker.isNull(createEndTime)) {
                whereSql += " and ( create_time < ? )";
                Date date = format.parse(createEndTime);

                //把日期往后增加一天.整数往后推,负数往前移动
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, 1);
                //这个时间就是日期往后推一天的结果
                date = calendar.getTime();
                paramList.add(date);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlHelper.getDownLoadList("*", whereSql, "weight desc", Goods.class, paramList.toArray());
    }


    //展示商品列表, 弃用
    public BaseResponse queryGoodsList(QueryGoodsListRequest request) throws Exception {
        PageDataResponse<Object> pageDataResponse = new PageDataResponse<>();
        pageDataResponse.setData(new ArrayList<>());

        PagedList<Goods> pagedList = queryPageGoodsList(request);
        if (!Checker.isNone(pagedList.getItems())) {
            List<Map<String, Object>> datas = CollectionUtil.toList(pagedList.getItems(), p -> {
                Map<String, Object> item = new HashMap<>();

                item.put("name", p.getName());
                item.put("brandName", p.getBrandName());
                item.put("typeName", p.getTypeName());
                item.put("spec", p.getSpec());
                item.put("unitName", p.getUnitName());
                int amount = Checker.getIntegerValue(p.getUnitPrice());
                String amountStr = FormatUtil.decimalFormat(amount / 100.0);
                item.put("unitPrice", amountStr);
                item.put("inventory", p.getInventory());
                item.put("weight", p.getWeight());
                item.put("status", p.getStatus());
                item.put("createTime", p.getCreateTime());
                return item;
            });
            pageDataResponse.setData(datas);
        }
        pageDataResponse.setPageIndex(request.getPageIndex());
        pageDataResponse.setPageSize(request.getPageSize());
        pageDataResponse.setTotalCount(pagedList.getTotal());

        return pageDataResponse.succeed("处理成功");
    }


    private void detailExcel(QueryGoodsListRequest request, int n, WritableCellFormat cellFormat2, WritableSheet sheet) throws Exception {
        List<Goods> goodsList = queryList(request);
        for (Goods p : goodsList) {
            if (!Checker.isNone(p)) {
                String nameValue = p.getName();
                String brandNameValue = p.getBrandName();
                String typeNameValue = p.getTypeName();
                String specValue = p.getSpec();
                String unitNameValue = p.getUnitName();
                String unitPriceValue = FormatUtil.intShrink100ToStr(p.getUnitPrice());
                String inventoryValue = p.getInventory().toString();
                String weightValue = p.getWeight().toString();
                String statusValue = p.getStatus() == 1 ? "正常" : "禁用";
                String createTimeValue = FormatUtil.createTimeFormatDetail(p.getCreateTime());
                String[] bodyStr = new String[]{nameValue, brandNameValue, typeNameValue, specValue, unitNameValue, unitPriceValue, inventoryValue,
                        weightValue, statusValue, createTimeValue};
                ExcelHelper.settingMainBodyLabelCell(sheet, cellFormat2, n, bodyStr);
                n++;
            }
        }
    }


    public void downloadGoods(QueryGoodsListRequest request, HttpServletResponse httpServletResponse) {
        String createDate = request.getCreateTime();
        String createEndDate = request.getCreateEndTime();
        String filename = "";
        if (!Checker.isNull(createDate) && !Checker.isNull(createEndDate)) {
            filename = "眼镜目录" + createDate + "-" + createEndDate + ".xls";
        } else if (!Checker.isNull(createDate) && Checker.isNull(createEndDate)) {

            filename = "眼镜目录" + createDate + ".xls";
        } else if (Checker.isNull(createDate) && !Checker.isNull(createEndDate)) {
            filename = "眼镜目录" + createEndDate + ".xls";
        } else {

            filename = "眼镜目录.xls";
        }
        OutputStream out = null;
        WritableWorkbook workbook = null;
        try {
            ExcelHelper.setHttpServletResponse(httpServletResponse, filename);
            out = httpServletResponse.getOutputStream();
            // 创建写工作簿对象
            workbook = Workbook.createWorkbook(out);
            // 工作表（设置第一个sheet）
            WritableSheet sheet = workbook.createSheet(filename, 0);
            // 设置第一行格式
            WritableCellFormat cellFormat = ExcelHelper.getWritableCellFormat();
            // 设置列的不同宽度;
            Map<Integer, Integer> widthSet = new HashMap<>(16);
            widthSet.put(0, 35);
            widthSet.put(1, 35);
            widthSet.put(7, 30);
            ExcelHelper.settingColumnWidth(sheet, widthSet);
            // 设置第一行所在的标题
            String[] title = new String[]{"名称", "品牌", "类型", "规格", "单位", "单价", "库存", "权重", "状态", "创建时间"};
            ExcelHelper.settingTitleLabelCell(sheet, cellFormat, title);
            int n = 1;
            // 第二行格式
            WritableCellFormat cellFormat2 = ExcelHelper.getWritableCellFormat();

            detailExcel(request, n, cellFormat2, sheet);

            workbook.write();

        } catch (Exception e) {
            if (out != null)
                e.printStackTrace();
            logger.error("/goods/downloadGoodsList(): {}", e.getMessage(), e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }


    public void downloadGoodsT(QueryGoodsListRequest request, HttpServletResponse httpServletResponse) {
        String createDate = request.getCreateTime();
        String createEndDate = request.getCreateEndTime();
        String filename = "";
        if (!Checker.isNull(createDate) && !Checker.isNull(createEndDate)) {
            filename = "眼镜目录" + createDate + "-" + createEndDate + ".xls";
        } else if (!Checker.isNull(createDate) && Checker.isNull(createEndDate)) {

            filename = "眼镜目录" + createDate + ".xls";
        } else if (Checker.isNull(createDate) && !Checker.isNull(createEndDate)) {
            filename = "眼镜目录" + createEndDate + ".xls";
        } else {

            filename = "眼镜目录.xls";
        }

        FileInputStream fin = null;
        InputStreamReader re = null;
        FileOutputStream fout = null;
        OutputStream fileOut = null;
        OutputStream out = null;
        File fi = new File("C:\\Users\\Admin\\3.xls");

        WritableWorkbook workbook = null;
        try {
            ExcelHelper.setHttpServletResponse(httpServletResponse, filename);
           // out = httpServletResponse.getOutputStream();
            // 创建写工作簿对象
          //  workbook = Workbook.createWorkbook(out);
            String folderPath = "C:\\Users\\Admin\\excel";
            File folder = new File(folderPath);
            String savePath = folderPath + File.separator + filename;
            fileOut = new FileOutputStream(savePath);
            workbook = Workbook.createWorkbook(fileOut);
            // 工作表（设置第一个sheet）
            WritableSheet sheet = workbook.createSheet(filename, 0);
            // 设置第一行格式
            WritableCellFormat cellFormat = ExcelHelper.getWritableCellFormat();
            // 设置列的不同宽度;
            Map<Integer, Integer> widthSet = new HashMap<>(16);
            widthSet.put(0, 35);
            widthSet.put(1, 35);
            widthSet.put(7, 30);
            ExcelHelper.settingColumnWidth(sheet, widthSet);
            // 设置第一行所在的标题
            String[] title = new String[]{"名称", "品牌", "类型", "规格", "单位", "单价", "存库", "权重", "状态", "创建时间"};
            ExcelHelper.settingTitleLabelCell(sheet, cellFormat, title);
            int n = 1;
            // 第二行格式
            WritableCellFormat cellFormat2 = ExcelHelper.getWritableCellFormat();

            detailExcel(request, n, cellFormat2, sheet);


            workbook.write();
            //fileOut.close();
        } catch (Exception e) {
            if (fileOut != null)
                e.printStackTrace();
            logger.error("/goods/downloadGoodsList(): {}", e.getMessage(), e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }






    //增加或修改商品

    public BaseResponse addOrUpdateGoods(int id, String name, String brandName, int typeId, String spec, int unitId, int unitPrice, int inventory, int weight,
                                         String pic, int status) {
        BaseResponse response = new BaseResponse();
        weight = Checker.getIntegerValue(weight);
        Goods goods = null;
        if (id != 0) {

            if (id < 0) {
                return response.failed(BaseResponse.PARAMETER_ERROR, "传过来的商品ID有错");
            }
            int shopId = userService.getShopId();
            goods = goodsRepository.checkGoodsById(shopId, id);
            if (Checker.isNone(goods)) {
                return response.failed(BaseResponse.PARAMETER_ERROR, "参数错误，找不到对象");
            }
            //  int count = goodsRepository.checkGoodsSpecById(spec.trim(), id, shopId);

            //   if (count > 0) {
            //     return response.failed(BaseResponse.PARAMETER_ERROR, "商品规格出现重复");
            //   }

            goods.setName(name);
            goods.setBrandName(brandName);
            goods.setTypeId(typeId);
            DictType dictType = dictTypeRepository.findById(typeId).orElse(null);
            if (Checker.isNone(dictType)) {
                return response.failed(BaseResponse.PARAMETER_ERROR, "参数错误，找不到对象");
            }
            goods.setTypeName(dictType.getItemName());
            goods.setSpec(spec);
            goods.setUnitId(unitId);
            DictType dictType2 = dictTypeRepository.findById(unitId).orElse(null);
            if (Checker.isNone(dictType2)) {
                return response.failed(BaseResponse.PARAMETER_ERROR, "参数错误，找不到对象");
            }
            goods.setUnitName(dictType2.getItemName());
            goods.setUnitPrice(unitPrice);
            goods.setInventory(inventory);
            goods.setWeight(weight);
            goods.setPic(pic);
            goods.setStatus(status);

            goods.setShopId(shopId);
            goods.setUpdateTime(new Date());
            goodsRepository.save(goods);

        } else {
            int shopId = userService.getShopId();
            //  int count = goodsRepository.checkGoodsBySpec(spec, shopId);
            //   if (count > 0) {
            //     return response.failed(BaseResponse.PARAMETER_ERROR, "商品规格出现重复");
            // }
            goods = new Goods();
            goods.setName(name);
            goods.setBrandName(brandName);

            goods.setShopId(shopId);
            goods.setTypeId(typeId);
            DictType dictType = dictTypeRepository.findById(typeId).orElse(null);
            if (Checker.isNone(dictType)) {
                return response.failed(BaseResponse.PARAMETER_ERROR, "参数错误，找不到对象");
            }
            goods.setTypeName(dictType.getItemName());
            goods.setSpec(spec);
            goods.setUnitId(unitId);
            DictType unitType = dictTypeRepository.findById(unitId).orElse(null);
            if (Checker.isNone(unitType)) {
                return response.failed(BaseResponse.PARAMETER_ERROR, "参数错误，找不到对象");
            }
            goods.setUnitName(unitType.getItemName());
            goods.setUnitPrice(unitPrice);
            goods.setInventory(inventory);
            goods.setWeight(weight);
            goods.setPic(pic);
            goods.setStatus(status);
            goods.setCreateTime(new Date());
            goods.setUpdateTime(new Date());
            goodsRepository.save(goods);
        }
        return response.succeed("处理成功");
    }


    public BaseResponse deletedGoods(int id) {
        BaseResponse response = new BaseResponse();
        int shopId = userService.getShopId();
        Goods goods = goodsRepository.checkGoodsById(shopId, id);

        if (Checker.isNone(goods)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "参数错误，找不到对象");
        }
        goods.setDeleted(1);
        goods.setUpdateTime(new Date());
        goodsRepository.save(goods);
        return response.succeed("处理成功");
    }

    public BaseResponse gooodsList(String name) {
        DataResponse response = new DataResponse();
        try {
            int shopId = userService.getShopId();
            List<DictType> dictTypeList = dictTypeRepository.showDictTypeList(shopId);
            HashMap<String, Object> map = new HashMap<>();

            if (!Checker.isNone(dictTypeList)) {
                List<Map<String, Object>> datas = new LinkedList<>();
                for (DictType p : dictTypeList) {

                    int id = p.getId();
                    List<Goods> showGoodsList = new ArrayList<>();
                    showGoodsList = goodsRepository.goodList(shopId, id);
                   if(!Checker.isNone(name)){
                       showGoodsList =  queryListByNameAndType(shopId, id, name);
                   }
                    if (!Checker.isNone(showGoodsList)) {
                        Map<String, Object> item = new HashMap<>();
                        item.put("itemName", p.getItemName());
                        item.put("id", p.getId());
                        List<Map<String, Object>> datas_goods = new LinkedList<>();
                        for (Goods g : showGoodsList) {
                            Map<String, Object> item2 = new HashMap<>();
                            item2.put("name", g.getName());
                            item2.put("spec", g.getSpec());
                            item2.put("unitName", g.getUnitName());
                            item2.put("brandName", g.getBrandName());
                            item2.put("unitPriceInt", Checker.getIntegerValue(g.getUnitPrice()));
                            item2.put("unitPrice", FormatUtil.intShrink100ToStr(g.getUnitPrice()));
                            item2.put("inventory", g.getInventory());
                            item2.put("pic", g.getPic());
                            item2.put("id", g.getId());
                            datas_goods.add(item2);
                        }

                        item.put("children", datas_goods);
                        datas.add(item);
                    }
                }
                map.put("list", datas);
                response.setData(map);
            }
        } catch (Exception e) {
            logger.error("goodsList(): {}", e.getMessage(), e);
            response.setCode(response.APP_EXCEPTION);

        }
        return response.succeed("处理成功");
    }

    public List<Goods> queryListByNameAndType(int shopId, int typeId, String name){
        List<Object> paramList = new ArrayList<>();
        String whereSql = " ( 1=1 )";

        whereSql += " and deleted = 0";

        if (!Checker.isNull(name)) {
            whereSql += " and (name like ?)";
            paramList.add("%" + name.trim() + "%");
        }
        whereSql += " and (shop_id =?)";
        paramList.add(shopId);

        if (!Checker.isNone(typeId)) {
            whereSql += " and (type_id =?)";
            paramList.add(typeId);
        }
        return sqlHelper.getDownLoadList("*", whereSql, "weight desc", Goods.class, paramList.toArray());
    }

}
