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.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
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.listener.FctStandingBookExcelListener;
import org.springblade.imports.query.FctStandingBookQuery;
import org.springblade.imports.service.IFctStandingBookService;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
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.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

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

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zbc
 * @since 2021-03-22
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("imports/FctStandingBook")
@Api(value = "进销存台账", tags = "进销存台账接口")
public class FctStandingBookController extends BladeController {

	@Autowired
	private IFctStandingBookService fctStandingBookService;

	@Autowired
	private UserClient userService;


	@GetMapping("/page")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "分页", notes = "传入pageQuery")
	public R list(FctStandingBookQuery pageQuery, Query query) {
		IPage<FctStandingBook> pages = fctStandingBookService.getPageByQuery(Condition.getPage(query), pageQuery);
		return R.data(pages);
	}

	@GetMapping("/select/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "进销存下拉列表")
	public R selectList() {
		List<FctStandingBook> list = fctStandingBookService.list();
		List<Map<String, Object>> data = list.stream()
			.filter(obj -> StringUtils.isNotBlank(obj.getSpname()))
			.collect(
				Collectors.collectingAndThen(
					Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(FctStandingBook::getSpname))), ArrayList::new)
			).stream()
			.map(obj -> {
				Map<String, Object> map = new HashMap<>();
				map.put("label", obj.getSpname());
				map.put("value", obj.getSpname());
				return map;
			}).collect(Collectors.toList());
		List<Map<String, Object>> data2 = list.stream()
			.filter(obj -> StringUtils.isNotBlank(obj.getOutChannel()))
			.collect(
				Collectors.collectingAndThen(
					Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(FctStandingBook::getOutChannel))), ArrayList::new)
			).stream()
			.map(obj -> {
				Map<String, Object> map = new HashMap<>();
				map.put("label", obj.getOutChannel());
				map.put("value", obj.getOutChannel());
				return map;
			}).collect(Collectors.toList());
		Map<String, Object> maps = new HashMap<>();
		maps.put("list1",data);
		maps.put("list2",data2);
		return R.data(maps);
	}


	@PostMapping("/remove")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "删除", notes = "传入DID")
	public R remove(@ApiParam(value = "主键DID", required = true) @RequestParam Long dId) {
		return R.status(fctStandingBookService.remove(new LambdaQueryWrapper<FctStandingBook>()
			.eq(FctStandingBook::getDId, dId)
		));
	}


	@PostMapping("/update")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "修改", notes = "传入fctStandingBook")
	public R update(@Valid @RequestBody FctStandingBook fctStandingBook) {
		if (fctStandingBook == null || fctStandingBook.getDId() == null) {
			return R.fail("参数异常");
		}
		return R.status(fctStandingBookService.update(fctStandingBook, new LambdaQueryWrapper<FctStandingBook>()
			.eq(FctStandingBook::getDId, fctStandingBook.getDId()
			)
		));
	}



	@PostMapping("/jumpQueue")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "插入数据", notes = "传入file,onDid")
	public R saveOne(@RequestParam(required = true, name = "file") MultipartFile file,
					 @RequestParam(required = true, name = "onDid") Long onDid
	) {
		if (file == null) {
			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());
			if(excelList.isEmpty() || excelList.size() < 1){
				return R.fail("没有可导入的数据");
			}
			Long did = onDid;
			for (FctStandingBookDTO fctStandingBookDTO : excelList) {
				++did;
				fctStandingBookDTO.setDId(did);
			}
			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(",", "")).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());

			List<FctStandingBook> updateList = fctStandingBookService.list(new LambdaQueryWrapper<FctStandingBook>().gt(FctStandingBook::getDId, onDid));
			if(!updateList.isEmpty()&&updateList.size()>0){
				List<FctStandingBook> collect = updateList.stream().sorted((o1, o2) -> o2.getDId().intValue() - o1.getDId().intValue()).collect(Collectors.toList());
				for (FctStandingBook fctStandingBook : collect) {
					LambdaQueryWrapper<FctStandingBook> queryWrapper = new LambdaQueryWrapper<>();
					queryWrapper.eq(FctStandingBook::getDId,fctStandingBook.getDId());
					fctStandingBook.setDId(fctStandingBook.getDId() + excelList.size());
					fctStandingBookService.update(fctStandingBook,queryWrapper);
				}
			}
			fctStandingBookService.insertBatchHasDid(list);
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail("插入失败");
		}
		return R.success("插入成功");
	}

}

