package com.pj.tb_goods;

import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pj.api.dto.GoodsDto;
import com.pj.enummj.DeleteStatus;
import com.pj.enummj.Status;
import com.pj.tb_enterprise.TbEnterprise;
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.BeanUtils;
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 com.pj.utils.sg.*;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.filechooser.FileSystemView;

/**
 * Service: tb_goods -- 商品
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbGoodsService extends ServiceImpl<TbGoodsMapper, TbGoods> implements IService<TbGoods>{

	/** 底层 Mapper 对象 */
	@Autowired
	TbGoodsMapper tbGoodsMapper;

	@Autowired
	private MethodGoodsService methodGoodsService;

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

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

	/** 改 */
	void update(TbGoods t){
		updateById(t);
	}



	/** 查 */
	TbGoods getById(String id){
		return super.getById(id);
	}

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

	/** 查集合 - 根据互市区Id */
	List<TbGoods> getByTradeArea(SoMap so) {
		return tbGoodsMapper.getByTradeArea(so);
	}


	/** 远程调用: 同步航通海关监管商品信息 */
	public boolean goodsDto(GoodsDto goodsDto){
		TbGoods tbGoods = new TbGoods();
		List<TbGoods> tbGoodsList = tbGoodsMapper.selectList(new LambdaQueryWrapper<TbGoods>().eq(TbGoods::getHsCode, goodsDto.getHsCode()));
		//数据库没有就是新增
		if(tbGoodsList.size() == 0){
			BeanUtils.copyProperties(goodsDto,tbGoods);
			//设计基本信息
			tbGoods.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode()); // 默认未删除
			tbGoods.setStatus(Status.STATUS_ONE.getCode()); // 默认可用
			tbGoods.setCreateTime(new Date());
			tbGoods.setCreateName("航通");
			int insert = tbGoodsMapper.insert(tbGoods);
			return insert == 1;
		}
		//修改
		TbGoods goods = tbGoodsList.stream().sorted(Comparator.comparing(TbGoods::getId).reversed()).collect(Collectors.toList()).get(0);
		BeanUtils.copyProperties(goods,tbGoods);
		BeanUtils.copyProperties(goodsDto,tbGoods);
		int i = tbGoodsMapper.updateById(tbGoods);
		return i == 1;
	}

	/**
	 * 导入
	 * @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 = methodGoodsService.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<TbGoods> selectedList = tbGoodsMapper.selectList(new LambdaQueryWrapper<TbGoods>().eq(StringUtils.isNoneBlank(keyword), TbGoods::getGName, 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("主图");
		row.createCell(3).setCellValue("分类");
		row.createCell(4).setCellValue("分类名称");
		row.createCell(5).setCellValue("编号");
		row.createCell(6).setCellValue("备注");
		row.createCell(7).setCellValue("原产地");
		row.createCell(8).setCellValue("状态");
		row.createCell(9).setCellValue("unit");
		row.createCell(10).setCellValue("single_price");
		row.createCell(11).setCellValue("tax_no");
		row.createCell(12).setCellValue("创建时间");
		row.createCell(13).setCellValue("创建人编号");
		row.createCell(14).setCellValue("创建人名称");
		row.createCell(15).setCellValue("更新时间");
		row.createCell(16).setCellValue("更新人编号");
		row.createCell(17).setCellValue("更新人名称");
		row.createCell(18).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).getGName() + "").equals("null")? "": selectedList.get(i).getGName() + "");
			sheetRow.createCell(2).setCellValue((selectedList.get(i).getAvatar() + "").equals("null")? "": selectedList.get(i).getAvatar() + "");
			sheetRow.createCell(3).setCellValue((selectedList.get(i).getTypeIds() + "").equals("null")? "": selectedList.get(i).getTypeIds() + "");
			sheetRow.createCell(4).setCellValue((selectedList.get(i).getTypeNames() + "").equals("null")? "": selectedList.get(i).getTypeNames() + "");
			sheetRow.createCell(5).setCellValue((selectedList.get(i).getHsCode() + "").equals("null")? "": selectedList.get(i).getHsCode() + "");
			sheetRow.createCell(6).setCellValue((selectedList.get(i).getRemark() + "").equals("null")? "": selectedList.get(i).getRemark() + "");
			sheetRow.createCell(7).setCellValue((selectedList.get(i).getSource() + "").equals("null")? "": selectedList.get(i).getSource() + "");
			sheetRow.createCell(8).setCellValue((selectedList.get(i).getStatus() + "" ).equals("null")? "": selectedList.get(i).getStatus() + "");
			sheetRow.createCell(9).setCellValue((selectedList.get(i).getGUnit() + "").equals("null")? "": selectedList.get(i).getGUnit() + "");
			sheetRow.createCell(10).setCellValue((selectedList.get(i).getSinglePrice() + "").equals("null")? "": selectedList.get(i).getSinglePrice() + "");
			sheetRow.createCell(11).setCellValue((selectedList.get(i).getTaxNo() + "").equals("null")? "": selectedList.get(i).getTaxNo() + "");
			sheetRow.createCell(22).setCellValue((selectedList.get(i).getCreateTime() + "").equals("null")? "": selectedList.get(i).getCreateTime() + "");
			sheetRow.createCell(23).setCellValue((selectedList.get(i).getCreateBy() + "").equals("null")? "": selectedList.get(i).getCreateBy() + "");
			sheetRow.createCell(24).setCellValue((selectedList.get(i).getCreateName() + "").equals("null")? "": selectedList.get(i).getCreateName() + "");
			sheetRow.createCell(25).setCellValue((selectedList.get(i).getUpdateTime() + "").equals("null")? "": selectedList.get(i).getUpdateTime() + "");
			sheetRow.createCell(26).setCellValue((selectedList.get(i).getUpdateBy() + "").equals("null")? "": selectedList.get(i).getUpdateBy() + "");
			sheetRow.createCell(27).setCellValue((selectedList.get(i).getUpdateName() + "").equals("null")? "": selectedList.get(i).getUpdateName() + "");
			sheetRow.createCell(28).setCellValue((selectedList.get(i).getDeleteStatus() + "").equals("null")? "": selectedList.get(i).getDeleteStatus() + "");
			count += 1;
		}
		//建立输出流，输出文件
		FileOutputStream fos = new FileOutputStream(filepath);

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

	/** 远程调用 */
	GoodsDto selectById(Long id){
		TbGoods byId = super.getById(id);
		GoodsDto goodsDto = new GoodsDto();
		BeanUtils.copyProperties(byId,goodsDto);
		return goodsDto;

	}

	public TbGoods findByCode(String codeTs) {
		QueryWrapper<TbGoods>ew=new QueryWrapper<>();
		ew.lambda().eq(TbGoods::getHsCode,codeTs);
		List<TbGoods>list=list(ew);
		return list.isEmpty()?null:list.get(0);
	}
}
