/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.po.FreightStatisticsPo;
import com.yami.shop.bean.po.SkuStatisticsPo;
import com.yami.shop.bean.vo.FreightStatisticsVo;
import com.yami.shop.bean.vo.SkuBuyTogetherOftenVo;
import com.yami.shop.bean.vo.SkuStatisticsVo;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.SkuMapper;
import com.yami.shop.service.SkuService;
import com.yami.shop.service.UserService;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lgh on 2018/09/29.
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private UserService userService;

    @Override
    public List<Sku> listByProdId(Long prodId) {
        return skuMapper.listByProdId(prodId);
    }

    @Override
    public List<Sku> listByProdId(Long prodId, Long channelId, Long shopId) {
        return skuMapper.listByProdIdAndPlatform(prodId, channelId, shopId);
    }

    @Override
    public Sku getSkuBySkuId(Long skuId) {
        return skuMapper.selectById(skuId);
    }

    @Override
    public Sku getSkuBySkuId(Long skuId, Long channelId, Long shopId) {
        return skuMapper.listBySukIdAndPlatformShop(skuId, channelId, shopId);
    }

    @Override
    public Sku getSkuBySkuId(Long skuId, Long channelId) {
        return skuMapper.listBySukIdAndPlatform(skuId, channelId);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(cacheNames = "sku", key = "#skuId"),
            @CacheEvict(cacheNames = "skuList", key = "#prodId")
    })
    public void removeSkuCacheBySkuId(Long skuId, Long prodId) {

    }

    @Override
    public IPage<SkuBuyTogetherOftenVo> buyTogetherOften(PageParam<SkuBuyTogetherOftenVo> page, Long prodId,Long shopId,Long channelId,String userId) {
        return skuMapper.buyTogetherOften(page, prodId,shopId,channelId,userId);
    }

    @Override
    public IPage<SkuStatisticsVo> skuStatisticsList(PageParam<SkuStatisticsPo> page, SkuStatisticsPo po) {
        return skuMapper.skuStatisticsList(page, po);
    }

    @Override
    @SneakyThrows
    public void skuStatisticsExcel(HttpServletResponse response, SkuStatisticsPo po) {
        List<SkuStatisticsVo> skuStatisticsVoList = skuMapper.skuStatisticsList2(po);
        Double goodsTotalPrice = skuMapper.goodsTotalPrice(po);
        Double totalPoints = skuMapper.totalPoints(po);
        Double totalCash = skuMapper.totalCash(po);
        Double totalFreight = skuMapper.totalFreight(po);

        String head = "对账汇总表";
        List<String> heads = Arrays.asList(
                "商品ID", "商品名称", "规格", "单价（元）", "商品总数量", "小计（元）",
                "商品总额（元）", "总积分抵扣（元）", "总现金抵扣（元）", "总运费（元）"
        );
        List<List<String>> hs = heads.stream()
                .map(h -> Arrays.asList(head, h))
                .collect(Collectors.toList());

        List<List<Object>> data = new ArrayList<>();
        for (int i = 0; i < skuStatisticsVoList.size(); i++) {
            SkuStatisticsVo sku = skuStatisticsVoList.get(i);
            List<Object> row = new ArrayList<>();
            row.add(sku.getSkuId());
            row.add(sku.getSkuName());
            row.add(sku.getSpec());
            row.add(sku.getPrice());
            row.add(sku.getProdCount());
            row.add(sku.getTotal());

            if (i == 0) {   // 第一行放值
                row.add(goodsTotalPrice);
                row.add(totalPoints);
                row.add(totalCash);
                row.add(totalFreight);
            } else {        // 其余行留空
                row.add(null);
                row.add(null);
                row.add(null);
                row.add(null);
            }
            data.add(row);
        }

        /* 4. 样式 */
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 15);
        headWriteFont.setBold(true);
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        /* 5. 合并策略：数据区域第 1 行到最后一行，列 6~9 纵向合并 */
        OnceAbsoluteMergeStrategy mergeStrategy = null;
        if (data.size() > 1) {          // 至少两行才需要合并
            mergeStrategy = new OnceAbsoluteMergeStrategy(2, data.size()+1, 6, 6);
        }

        OnceAbsoluteMergeStrategy mergeStrategy2 = null;
        if (data.size() > 1) {          // 至少两行才需要合并
            mergeStrategy2 = new OnceAbsoluteMergeStrategy(2, data.size()+1, 7, 7);
        }

        OnceAbsoluteMergeStrategy mergeStrategy3 = null;
        if (data.size() > 1) {          // 至少两行才需要合并
            mergeStrategy3 = new OnceAbsoluteMergeStrategy(2, data.size()+1, 8, 8);
        }

        OnceAbsoluteMergeStrategy mergeStrategy4 = null;
        if (data.size() > 1) {          // 至少两行才需要合并
            mergeStrategy4 = new OnceAbsoluteMergeStrategy(2, data.size()+1, 9, 9);
        }

        /* 6. 写出 */
        String fileName = URLEncoder.encode("对账汇总表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        ExcelWriterSheetBuilder writerBuilder = EasyExcel.write(response.getOutputStream())
                .head(hs)
                .sheet(head)
                .registerWriteHandler(horizontalCellStyleStrategy);
        if (mergeStrategy != null) {
            writerBuilder.registerWriteHandler(mergeStrategy);
        }
        if (mergeStrategy2 != null) {
            writerBuilder.registerWriteHandler(mergeStrategy2);
        }
        if (mergeStrategy3 != null) {
            writerBuilder.registerWriteHandler(mergeStrategy3);
        }
        if (mergeStrategy4 != null) {
            writerBuilder.registerWriteHandler(mergeStrategy4);
        }
        writerBuilder.doWrite(data);
    }

    @Override
    public void freightStatisticsExcel(HttpServletResponse response,FreightStatisticsPo po) {
        try {
            List<FreightStatisticsVo> list = skuMapper.freightStatisticsList2(po);
            if (!list.isEmpty()){
                list.forEach(c->{
                    LocalDateTime dateTime = LocalDateTime.parse(c.getPayTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    String result = dateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
                    c.setPayTime(result);
                });
            }
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("运费汇总表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), FreightStatisticsVo.class)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("列表").doWrite(list);
        } catch (IOException e) {
            throw new GlobalException("文件下载异常");
        }
    }

    @Override
    public IPage<FreightStatisticsVo> freightStatisticsList(PageParam<FreightStatisticsPo> page, FreightStatisticsPo po) {
        return skuMapper.freightStatisticsList(page,po);
    }

    @Override
    @SneakyThrows
    public void test(HttpServletResponse response) {
        String head = "用户信息表";
        List<String> heads = Lists.newArrayList();
        heads.add("手机号");
        heads.add("积分");

        //deal_num=分销的 deal_money=自己买的 remark=分销的商品 sales_nick_name=自己买的商品 sales_status=总计

        List<List<String>> hs = Lists.newArrayList();
        heads.forEach(c -> hs.add(Arrays.asList(head, c)));
        List<List<Object>> data = Lists.newArrayList();
        List<User> userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getChannelId,1L));

        for (User user : userList) {
            List<Object> list = Lists.newArrayList();
            list.add(user.getUserMobile());
            list.add(userService.test(user.getUserId()));
            data.add(list);
        }

        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置背景颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        //设置头字体
        WriteFont headWriteFont = new WriteFont();
        //字体大小
        headWriteFont.setFontHeightInPoints((short) 15);
        //使用微软粗体
        headWriteFont.setBold(true);
        //塞入条件
        headWriteCellStyle.setWriteFont(headWriteFont);
        //设置头居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        //内容策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        String fileName = URLEncoder.encode("用户信息表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream())
                .head(hs)
                .useDefaultStyle(true)
                .sheet(head)
                .registerWriteHandler(horizontalCellStyleStrategy)
                //自适应宽度
                //.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(data);
    }

}
