package org.springblade.imports.controller;


import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springblade.capcancel.vo.CapNoKcYesVO;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.imports.dto.FctStandingBookDTO;
import org.springblade.imports.entity.FctStandingBook;
import org.springblade.imports.entity.ImpUnicomArpuDou;
import org.springblade.imports.listener.EasyExcelListener;
import org.springblade.imports.listener.FctStandingBookExcelListener;
import org.springblade.imports.query.FctStandingBookQuery;
import org.springblade.imports.service.IFctStandingBookService;
import org.springblade.imports.service.IImpUnicomArpuDouService;
import org.springblade.imports.util.RandomUtil;
import org.springblade.imports.vo.FctStandingBookVO;
import org.springblade.system.client.UserClient;
import org.springblade.system.client.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zbc
 * @since 2021-03-22
 */
@RestController
@Slf4j
@RequestMapping("imports/impUnicomArpuDou")
@Api(value = "报表导入", tags = "报表导入接口")
public class ImpUnicomArpuDouController extends BladeController {

	@Autowired
	private IImpUnicomArpuDouService impUnicomArpuDouService;

	@Autowired
	private IFctStandingBookService fctStandingBookService;

	@Autowired
	private UserClient userService;

	/**
	 * excel导入
	 */
	@PostMapping("/import")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "excel导入", notes = "file")
	public R<ImpUnicomArpuDou> imports(@RequestParam(required = false,name = "file") MultipartFile file) {
		if (file.isEmpty()) {
			return R.fail("导入文件不能为空");
		}
		EasyExcelListener easyExcelListener = new EasyExcelListener();
		List<ImpUnicomArpuDou> excelList = easyExcelListener.list;
		try {
			InputStream inputStream = file.getInputStream();
			EasyExcel.read(inputStream, ImpUnicomArpuDou.class, easyExcelListener).sheet().doRead();
			log.info("导入条数" + excelList.size());
			impUnicomArpuDouService.insertBatch(excelList);
		}catch (Exception e){
			e.printStackTrace();
			return R.fail("导入失败");
		}
		return R.success("导入成功");
	}


	/**
	 * 进销存excel导入
	 */
	@PostMapping("/importFctStandingBook")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "进销存excel导入", notes = "file")
	public R<FctStandingBook> importFctStandingBook(@RequestParam(required = false,name = "file") MultipartFile file) {
		if (file.isEmpty()) {
			return R.fail("导入文件不能为空");
		}
		FctStandingBookExcelListener fctStandingBookExcelListener = new FctStandingBookExcelListener();
		List<FctStandingBookDTO> excelList = fctStandingBookExcelListener.list;
		try {
			InputStream inputStream = file.getInputStream();
			EasyExcel.read(inputStream, FctStandingBookDTO.class, fctStandingBookExcelListener).sheet().doRead();
			log.info("导入条数" + excelList.size());
			BladeUser bladeUser = AuthUtil.getUser();
			UserModel user = userService.getById(bladeUser.getUserId());
			List<FctStandingBook> list = excelList.stream()
				.map(obj -> {
					FctStandingBook bean = new FctStandingBook();
					bean.setAccountId(user.getAccount());
					bean.setAccountName(user.getName());
					bean.setImportTime(new Date());
					BeanUtils.copyProperties(obj,bean);
					//结算日期处理
					if(StringUtils.isNotBlank(obj.getThemonth())){
						String replace = obj.getThemonth().replace("年", "-").replace("月", "");
						SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm");
						Date parse = null;
						try {
							parse = simpleDateFormat.parse(replace);
						} catch (ParseException e) {
							e.printStackTrace();
						}
						String format = simpleDateFormat.format(parse);
						bean.setThemonth(format);
					}
					//采购金额
					if(StringUtils.isNotBlank(obj.getInMoney())){
						bean.setInMoney(new BigDecimal(obj.getInMoney().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//采购数量
					if(StringUtils.isNotBlank(obj.getInNum())){
						bean.setInNum(Double.parseDouble(obj.getInNum()));
					}
					//采购赠卡数量
					if(StringUtils.isNotBlank(obj.getInGiftcardNum())){
						bean.setInGiftcardNum(Double.parseDouble(obj.getInGiftcardNum()));
					}
					//采购单价
					if(StringUtils.isNotBlank(obj.getInPrice())){
						bean.setInPrice(new BigDecimal(obj.getInPrice().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//出库单价
					if(StringUtils.isNotBlank(obj.getOutPrice())){
						bean.setOutPrice(new BigDecimal(obj.getOutPrice().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//销售单价
					if(StringUtils.isNotBlank(obj.getSalePrice())){
						bean.setSalePrice(new BigDecimal(obj.getSalePrice().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//实际结算数量
					if(StringUtils.isNotBlank(obj.getAccountNum())){
						bean.setAccountNum(Double.parseDouble(obj.getAccountNum()));
					}
					//销售赠卡数量
					if(StringUtils.isNotBlank(obj.getSaleGiftcardNum())){
						bean.setSaleGiftcardNum(Double.parseDouble(obj.getSaleGiftcardNum()));
					}
					//实际结算金额
					if(StringUtils.isNotBlank(obj.getAccountMoney())){
						bean.setAccountMoney(new BigDecimal(obj.getAccountMoney().replaceAll("\\(","").replaceAll("\\)","").replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//系统出库数量
					if(StringUtils.isNotBlank(obj.getSystemNum())){
						bean.setSystemNum(Double.parseDouble(obj.getSystemNum()));
					}
					//结余金额
					if(StringUtils.isNotBlank(obj.getBalanceMoney())){
						bean.setBalanceMoney(new BigDecimal(obj.getBalanceMoney().replaceAll(",", "")).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					//结余正价卡数量
					if(StringUtils.isNotBlank(obj.getBalanceNormalCard())){
						bean.setBalanceNormalCard(Double.parseDouble(obj.getBalanceNormalCard()));
					}
					//结余赠卡数量
					if(StringUtils.isNotBlank(obj.getBalanceGiftcard())){
						bean.setBalanceGiftcard(Double.parseDouble(obj.getBalanceGiftcard()));
					}
					return bean;
				}).collect(Collectors.toList());
			fctStandingBookService.insertBatch(list);
		}catch (Exception e){
			e.printStackTrace();
			return R.fail("导入失败");
		}
		return R.success("导入成功");
	}



	@Value("${blade.file.uploadPath}")
	private String picDir;

	/**
	 * 进销存excel导出
	 */
	@PostMapping("/exportFctStandingBook")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "进销存excel导出", notes = "query")
	public R<ImpUnicomArpuDou> exportFctStandingBook(HttpServletResponse response, FctStandingBookQuery query) {
		List<FctStandingBook> list = fctStandingBookService.getListByQuery(query);
		String tempFileName = UUID.randomUUID().toString() + RandomUtil.randomString(4) + ".xls";
		List<FctStandingBookVO> voList = new ArrayList<FctStandingBookVO>();
		if(list != null && !list.isEmpty()) {
			list.forEach(item -> voList.add(BeanUtil.copyProperties(item, FctStandingBookVO.class)));
		}
		try {
			String filePath = picDir + tempFileName;
			//String filePath = "D:/boyuan/work2/excel/" + tempFileName;
			EasyExcel.write(filePath, FctStandingBookVO.class).sheet().doWrite(voList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.success("uploads/" + tempFileName);
	}


}

