package cn.wise.sc.cement.business.service.impl;

import cn.wise.sc.cement.business.entity.*;
import cn.wise.sc.cement.business.mapper.ConsumablesEnterMapper;
import cn.wise.sc.cement.business.mapper.ConsumablesMapper;
import cn.wise.sc.cement.business.mapper.ConsumablesOutMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.ChangeValidDateQuery;
import cn.wise.sc.cement.business.model.query.ChangeStockQuery;
import cn.wise.sc.cement.business.service.IConsumablesService;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Builder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-09-03
 */
@Service
public class ConsumablesServiceImpl extends ServiceImpl<ConsumablesMapper, Consumables> implements IConsumablesService {

	@Resource
	private ConsumablesMapper consumablesMapper;
	@Autowired
	private ISysUserService userService;
	@Resource
	private ConsumablesEnterMapper consumablesEnterMapper;
	@Resource
	private ConsumablesOutMapper consumablesOutMapper;

	/**
	 * 分页查询
	 *
	 * @param pageQuery
	 * @param name
	 * @param supplierName
	 * @return
	 */
	@Override
	public BaseResponse<IPage<Consumables>> getPage(PageQuery pageQuery, String name, String supplierName) {
		QueryWrapper<Consumables> qw = new QueryWrapper<>();
		if (StringUtils.isNotEmpty(name)) {
			qw.like("name", name);
		}
		if (StringUtils.isNotEmpty(supplierName)) {
			qw.like("supplier_name", supplierName);
		}
		qw.orderByDesc("create_time");
		IPage<Consumables> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		page = consumablesMapper.selectPage(page, qw);
		return BaseResponse.okData(page);
	}

	/**
	 * 消耗品导出
	 *
	 * @param name
	 * @param supplierName
	 * @param fileName
	 * @param response
	 */
	@Override
	public void export(String name, String supplierName, String fileName, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
		params.put("supplierName", supplierName);
		params.put("name", name);
		List<Map<String, Object>> list = consumablesMapper.exportList(params);

		if (!CollectionUtils.isEmpty(list)) {
			Map<String, Object> map = list.get(0);
			String[] headers = new String[map.size()];
			headers[0] = "序号";
			headers[1] = "易耗品名称";
			headers[2] = "'易耗品代号'";
			headers[3] = "供应商";
			headers[4] = "位置";
			headers[5] = "购买日期";
			headers[6] = "库存数量";
			List<Object[]> datas = new ArrayList<>(list.size());
			for (Map<String, Object> m : list) {
				Object[] objects = new Object[headers.length];
				for (int j = 0; j < headers.length; j++) {
					String obj = m.get(headers[j]).toString();
					if (j == 0) {
						obj = obj.split("\\.")[0];
					}
					objects[j] = obj;
				}
				datas.add(objects);
			}
			ExcelUtil.excelExport(
					fileName == null || fileName.trim().length() <= 0 ? "消耗品" : fileName, headers,
					datas, response);
		}
	}

	/**
	 * 新增消耗品
	 *
	 * @param query
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<Consumables> create(Consumables query) {
		if (StringUtils.isEmpty(query.getName())) {
			return BaseResponse.errorMsg("消耗品名称不能为空!");
		}
		QueryWrapper<Consumables> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		int count = consumablesMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg(query.getName() + "已存在");
		}
		if(query.getEnterNum() != null && query.getUnitStock() != null){
			BigDecimal stockNum = new BigDecimal(query.getEnterNum()).multiply(query.getUnitStock());
			query.setStockNum(stockNum);
		}else{
			query.setStockNum(new BigDecimal(0));
		}
		query.setCreateTime(LocalDateTime.now())
				.setStatus(1);
		consumablesMapper.insert(query);
		//消耗品入库记录添加
		LoginUser loginUser = userService.getLoginUser();
		ConsumablesEnter enter = new ConsumablesEnter();
		enter.setConsumablesId(query.getId())
				.setUserId(loginUser.getId())
				.setEnterNum(query.getEnterNum())
				.setCreateTime(LocalDateTime.now())
				.setRemark("新增消耗品");
		consumablesEnterMapper.insert(enter);
		return BaseResponse.okData(query);
	}

	/**
	 * 修改消耗品
	 *
	 * @param query
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<Consumables> update(Consumables query) {
		if (StringUtils.isEmpty(query.getName())) {
			return BaseResponse.errorMsg("消耗品名称不能为空!");
		}
		QueryWrapper<Consumables> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		qw.ne("id", query.getId());
		int count = consumablesMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg(query.getName() + "已存在");
		}
		consumablesMapper.updateById(query);
		return BaseResponse.okData(query);
	}

	/**
	 * 新增入库
	 *
	 * @param query
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<String> enter(ChangeStockQuery query) {
		if (query == null || query.getId() == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		Consumables consumables = consumablesMapper.selectById(query.getId());
		if (consumables == null) {
			return BaseResponse.errorMsg("数据错误!");
		}
		ConsumablesEnter enter = new ConsumablesEnter();
		enter.setConsumablesId(consumables.getId())
				.setUserId(userService.getLoginUser().getId())
				.setEnterNum(query.getEnterNum())
				.setCreateTime(LocalDateTime.now())
				.setRemark(query.getRemark());
		consumablesEnterMapper.insert(enter);
		consumables.setStockNum(consumables.getStockNum().add( consumables.getUnitStock().multiply(new BigDecimal(enter.getEnterNum()))));
		consumablesMapper.updateById(consumables);
		return BaseResponse.okData("新增入库完成");
	}

	/**
	 * 领用出库
	 *
	 * @param query
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<String> out(ChangeStockQuery query) {
		if (query == null || query.getId() == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		Consumables consumables = consumablesMapper.selectById(query.getId());
		if (consumables == null) {
			return BaseResponse.errorMsg("数据错误!");
		}
		ConsumablesOut out = new ConsumablesOut();
		out.setConsumablesId(consumables.getId())
				.setUserId(userService.getLoginUser().getId())
				.setCollectNum(query.getOutNum())
				.setCreateTime(LocalDateTime.now())
				.setRemark(query.getRemark());
		consumablesOutMapper.insert(out);
		consumables.setStockNum(consumables.getStockNum().subtract(out.getCollectNum()));
		consumablesMapper.updateById(consumables);
		return BaseResponse.okData("领用出库完成");
	}

	/**
	 * 变更有效期
	 *
	 * @param query
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<String> changeValidDate(ChangeValidDateQuery query) {
		if (query == null || query.getId() == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		Consumables consumables = consumablesMapper.selectById(query.getId());
		if (consumables == null) {
			return BaseResponse.errorMsg("数据错误!");
		}

		consumables.setValidDate(query.getValidDate());
		consumablesMapper.updateById(consumables);
		return BaseResponse.okData("变更有效期完成");
	}

	/**
	 * 过期处置
	 *
	 * @param id
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<String> overdue(Integer id) {
		if (id == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		Consumables consumables = consumablesMapper.selectById(id);
		if (consumables == null) {
			return BaseResponse.errorMsg("数据错误!");
		}
		consumables.setStatus(0);
		consumablesMapper.updateById(consumables);
		return BaseResponse.okData("过期处置完成");
	}

}
