package com.pj.tb_goods_units;

import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pj.tb_goods_type.TbGoodsType;
import com.pj.utils.so.SoMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.filechooser.FileSystemView;

/**
 * Service: tb_goods_units -- 商品单位
 *
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbGoodsUnitsService extends ServiceImpl<TbGoodsUnitsMapper, TbGoodsUnits> implements IService<TbGoodsUnits> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbGoodsUnitsMapper tbGoodsUnitsMapper;

    @Autowired
    private MethodGoodsUnitsService methodGoodsUnitsService;

    /**
     * 增
     */
    void add(TbGoodsUnits t) {
        save(t);
    }

    /**
     * 删
     */
    void delete(Long id) {
        removeById(id);
    }

    /**
     * 改
     */
    void update(TbGoodsUnits t) {
        updateById(t);

    }

    /**
     * 查
     */
    TbGoodsUnits getById(Long id) {
        return super.getById(id);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    List<TbGoodsUnits> getList(SoMap so) {
        return tbGoodsUnitsMapper.getList(so);
    }

    /**
     * 导入
     *
     * @param file excel文件
     * @return
     * @throws IOException
     */
    public String importData(MultipartFile file) throws IOException {
        System.out.println("\n开始执行文件上传....\n");

        //判空
        if (file.isEmpty()) return "文件为空,无法执行上传...";
        //获取文件上传数据
        HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
        //获取第一页sheet
        HSSFSheet sheet = wb.getSheetAt(0);
        //定义计数器
        int count = 0;
        //定义行对象
        HSSFRow row = null;
        //解析数据封装到集合
        count = methodGoodsUnitsService.importMethod(row, sheet, count);
        wb.close();
        System.out.println("\n文件上传完成,共上传 " + count + "条 " + "数据...\n");
        return "上传完成,共上传" + count + "条" + "数据。";
    }

    /**
     * 导出 excel文件
     *
     * @param keyword
     * @return
     */
    public String outportExcel(String keyword, String filepath) throws IOException {
        System.out.println("\n开始执行文件导出....\n");
        //导出的文件的路径
        if (filepath == null || filepath.trim().equals("")) {
            // 获取当前用户的桌面路径
            FileSystemView fileSystemView = FileSystemView.getFileSystemView();
            filepath = fileSystemView.getHomeDirectory().getPath();
        }
        filepath = filepath + "\\商品分类数据表_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".xlsx";
        //根据需求查询数据
        List<TbGoodsUnits> selectedList = tbGoodsUnitsMapper.selectList(new LambdaQueryWrapper<TbGoodsUnits>().eq(StringUtils.isNoneBlank(keyword), TbGoodsUnits::getUnits, keyword));
        if (selectedList.size() == 0) return "没有可导出的数据。";
        //建立excel对象封装数据
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建excel表格右下角的sheet页名称
        HSSFSheet sheet = workbook.createSheet("1");
        //创建表头
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("食品单位编号");
        row.createCell(2).setCellValue("管理商品的单位");

        //定义计数器
        int count = 0;
        //遍历集合
        for (int i = 0; i < selectedList.size(); i++) {
            HSSFRow sheetRow = sheet.createRow(sheet.getLastRowNum() + 1);
            sheetRow.createCell(0).setCellValue(i + 1);
            sheetRow.createCell(1).setCellValue((selectedList.get(i).getUnitsNo() + "").equals("null") ? "" : selectedList.get(i).getUnitsNo() + "");
            sheetRow.createCell(2).setCellValue((selectedList.get(i).getUnits() + "").equals("null") ? "" : selectedList.get(i).getUnits() + "");

            count += 1;
        }
        //建立输出流，输出文件
        FileOutputStream fos = new FileOutputStream(filepath);

        workbook.write(fos);
        fos.flush();
        //关闭输出流
        fos.close();
        workbook.close();
        System.out.println("\n数据导出完成!共导出 " + count + " 条数据。");
        return "数据导出完成!共导出 " + count + " 条数据。";
    }

    /**
     * 根据编号查询
     * @param code
     * @return
     */
    public TbGoodsUnits findByCode(String code) {
        List<TbGoodsUnits> list = tbGoodsUnitsMapper.selectList(new LambdaQueryWrapper<TbGoodsUnits>().eq(TbGoodsUnits::getUnitsNo, code));
        return list.isEmpty() ? null : list.get(0);
    }

}
