package com.dk.mdm.service.mst;

import com.dk.common.exception.BaseBusinessException;
import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.common.util.ExcelUtils;
import com.dk.mdm.infrastructure.convert.mst.GoodsSkuConvert;
import com.dk.mdm.infrastructure.util.AuthUtils;
import com.dk.mdm.mapper.mst.*;
import com.dk.mdm.model.pojo.mst.GoodsBrand;
import com.dk.mdm.model.pojo.mst.GoodsCategory;
import com.dk.mdm.model.pojo.mst.GoodsSku;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.pojo.mst.Role;
import com.dk.mdm.model.query.mac.OtherReceivableItemQuery;
import com.dk.mdm.model.query.mst.*;
import com.dk.mdm.model.response.mac.OtherReceivableItemResponse;
import com.dk.mdm.model.response.mst.*;
import com.dk.mdm.model.vo.ivt.InOutRecordVO;
import com.dk.mdm.model.vo.ivt.InboundItemVO;
import com.dk.mdm.model.vo.ivt.InboundVO;
import com.dk.mdm.model.vo.mst.GoodsSkuVO;
import com.dk.mdm.model.vo.mst.RoleVo;
import com.dk.mdm.service.common.CommonService;
import com.dk.mdm.service.ivt.inbound.InboundCheckService;
import com.dk.mdm.service.ivt.inventory.InventoryService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Transactional
public class GoodsSkuService extends BaseService<GoodsSku> {

	@Override
	public BaseMapper<GoodsSku> getRepository() {
		return goodsSkuMapper;
	}

	@Autowired
	private GoodsSkuMapper goodsSkuMapper;


	@Autowired
	private GoodsSkuConvert goodsSkuConvert;

	@Autowired
	private InboundCheckService inboundCheckService;

	@Autowired
	InventoryService inventoryService;

	@Autowired
	private GoodsBrandMapper goodsBrandMapper;

	@Autowired
	private GoodsCategoryMapper	goodsCategoryMapper;

	@Autowired
	private UnitMapper unitMapper;

	@Autowired
	private GoodsSeriesMapper goodsSeriesMapper;

 /**
     * @desc   : 重写组件
     * @author : 王英杰
     * @date   : 2024/3/4 14:51
     */
	@Override
	public String getPrimaryKey() {
		return "sku_id";
	}
	@Autowired
	private CommonService commonService;
	@Autowired
	private AuthUtils authUtils;
	/**
	 * @desc : 查询
	 * @author : 王英杰
	 * @date : 2023/1/5 9:39
	 */
	@Pagination
	public ResponseResultVO<PageList<GoodsSkuResponse>> selectByCond(GoodsSkuQuery goodsSkuQuery) {
		return super.mergeListWithCount(goodsSkuQuery, goodsSkuMapper.selectByCond(goodsSkuQuery),
				goodsSkuMapper.countByCond(goodsSkuQuery));
	}



	/**
	 * @desc : 新建
	 * @author : 王英杰
	 * @date : 2023/1/5 9:39
	 */
	@Transactional(
			rollbackFor = {Exception.class}
	)
	public ResponseResultVO<?> insert(GoodsSkuVO goodsSkuVO) {
		GoodsSku goodsSku = goodsSkuConvert.convertToPo(goodsSkuVO);
		// 获取编码和主键UuId
		Map<String, Object> codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.GOODSSKU.getName(), true);

		// 如果辅助单位标识前端传值为空则赋值false
		if(goodsSku.getFlgSubUnit() == null || goodsSku.getFlgSubUnit().equals("null")){
			goodsSku.setFlgSubUnit(false);
		}

		goodsSku.setSkuId(codeMap.get("outId").toString());
		goodsSku.setSkuCode(codeMap.get("outNote").toString());
		super.insert(goodsSku);

		if(goodsSkuVO.getWhId()!=null){ //生成入库单数据  插入存货表
			  String StaffId = authUtils.getStaff().getStaffId();
			//总单
			InboundVO inboundVO = new InboundVO();
			inboundVO.setIntoType(Constant.IntoType.BEGIN.getName());
			inboundVO.setIntoingQty(goodsSkuVO.getIntoQty());
			inboundVO.setIntoingAmt(goodsSkuVO.getIntoQty().multiply(goodsSkuVO.getPriceInto()));
			inboundVO.setStaffId(StaffId);
			inboundVO.setMakeStaff(StaffId);
			inboundVO.setOrgId(goodsSkuVO.getOrgId());
			inboundVO.setMakeTime(LocalDateTime.now());
			inboundVO.setIntoDate(LocalDate.now());
			inboundVO.setWhId(goodsSkuVO.getWhId());
			inboundVO.setFlgAutoHandle(true);

            //明细
			List<InboundItemVO> inboundItemVOList = new ArrayList<>();
			InboundItemVO inboundItemVO = new InboundItemVO();
			inboundItemVO.setIntoingQty(goodsSkuVO.getIntoQty());
			inboundItemVO.setIntoingAmt(goodsSkuVO.getIntoQty().multiply(goodsSkuVO.getPriceInto()));
			inboundItemVO.setPriceInto(goodsSkuVO.getPriceInto());
			inboundItemVO.setCostPrice(goodsSkuVO.getPriceInto());
			inboundItemVO.setCostAmt(inboundItemVO.getIntoingAmt());
			inboundItemVO.setIntoAmt(goodsSkuVO.getIntoQty().multiply(goodsSkuVO.getPriceInto()));
			inboundItemVO.setIntoQty(goodsSkuVO.getIntoQty());
			inboundItemVO.setItemIndex(0);
			inboundItemVO.setSkuId(goodsSku.getSkuId());
			inboundItemVO.setWhId(goodsSkuVO.getWhId());
			inboundItemVO.setNonStdCode(goodsSkuVO.getNonStdCode());
			inboundItemVO.setIntoingBox(goodsSkuVO.getBox());
			inboundItemVO.setIntoingPiece(goodsSkuVO.getPiece());
			inboundItemVO.setSkuModel(goodsSkuVO.getSkuModel());
			inboundItemVO.setSkuName(goodsSkuVO.getSkuName());
			inboundItemVOList.add(inboundItemVO);

			Map<String, Object> map = new HashMap<>();
			map.put("total",inboundVO);
			map.put("detail",inboundItemVOList);
			inboundCheckService.checkInboundInsert(map);
		}
		return ResponseResultUtil.success();
	}
	/**
	 * @desc : 新建
	 * @author : 王英杰
	 * @date : 2023/1/5 9:39
	 */
	@Transactional(
			rollbackFor = {Exception.class}
	)
	public ResponseResultVO<?> update(GoodsSkuVO goodsSkuVO) {
		GoodsSku goodsSku = goodsSkuConvert.convertToPo(goodsSkuVO);
		// 获取编码和主键UuId
		super.updateByUuid(goodsSku);
		return ResponseResultUtil.success();
	}

	/**
	 * @desc   : 导入
	 * @author : 常皓宁
	 * @date   : 2024/6/7 11:41
	 */
	@Transactional(rollbackFor = {Exception.class})
	public ResponseResultVO<String> importSKU(List<GoodsSku> list, HttpServletResponse response,@PathVariable Integer cpId) {
		List<GoodsSku> messageList = new ArrayList<>();
		Workbook workbook = null;
		Boolean importMessage = false;
		//规则校验
		for (GoodsSku goodsSku : list) {
			goodsSku.setCpId(cpId);
			goodsSku.setErrorMessage("");
			//TODO 校验规则
			//商品编号不能为空
			if(goodsSku.getSkuCode()==null){
				goodsSku.setErrorMessage(goodsSku.getErrorMessage() + "商品编号不能为空,");
				importMessage = true;
			}
			//商品型号不能为空
			if(goodsSku.getSkuModel()==null){
				goodsSku.setErrorMessage(goodsSku.getErrorMessage() + "商品型号不能为空,");
				importMessage = true;
			}
			//品牌
			if (goodsSku.getBrandName()!=null) {
				String brandName = goodsSku.getBrandName();
				GoodsBrandResponse goodsBrandResponse = goodsBrandMapper.selectByUuId(new GoodsBrandQuery().setBrandName(brandName).setCpId(goodsSku.getCpId()));
				if(goodsBrandResponse == null){
					goodsSku.setErrorMessage(goodsSku.getErrorMessage() + "商品品牌填写错误,");
					importMessage = true;
				}else{
					goodsSku.setBrandId(goodsBrandResponse.getBrandId());
				}
			}else{
				goodsSku.setErrorMessage(goodsSku.getErrorMessage() + "商品品牌不能为空,");
				importMessage = true;
			}
			//种类
			if (goodsSku.getCategoryName()!=null) {
				String CatagoryName = goodsSku.getCategoryName();
				GoodsCategoryResponse goodsCategoryResponse = goodsCategoryMapper.selectByUuId(new GoodsCategoryQuery().setCatName(CatagoryName).setCpId(goodsSku.getCpId()));
				if(goodsCategoryResponse == null){
					goodsSku.setErrorMessage(goodsSku.getErrorMessage() + "商品种类填写错误,");
					importMessage = true;
				}else{
					goodsSku.setCategoryId(goodsCategoryResponse.getCatId());
				}
			}else{
				goodsSku.setErrorMessage(goodsSku.getErrorMessage() + "商品种类不能为空,");
				importMessage = true;
			}
			//计量单位
			if (goodsSku.getUnitName()!=null) {
				String unintName = goodsSku.getUnitName();
				UnitResponse unitResponse = unitMapper.selectByUuId(new UnitQuery().setUnitName(unintName).setCpId(goodsSku.getCpId()));
				if(unitResponse == null){
					goodsSku.setErrorMessage(goodsSku.getErrorMessage() + "计量单位填写错误,");
					importMessage = true;
				}else{
					goodsSku.setUnitId(unitResponse.getUnitId());
				}
			}else{
				goodsSku.setErrorMessage(goodsSku.getErrorMessage() + "计量单位不能为空,");
				importMessage = true;
			}
			//辅助单位
			if (goodsSku.getSubUnitName()!=null) {
				String subUnintName = goodsSku.getSubUnitName();
				UnitResponse unitResponse = unitMapper.selectByUuId(new UnitQuery().setUnitName(subUnintName).setCpId(goodsSku.getCpId()));
				if(unitResponse == null){
					goodsSku.setErrorMessage(goodsSku.getErrorMessage()  + "辅助单位填写错误,");
					importMessage = true;
				}else{
					goodsSku.setSubUnitId(unitResponse.getUnitId());
				}
			}
			//商品系列
			if (goodsSku.getSeriesName()!=null) {
				String seriesName = goodsSku.getSeriesName();
				GoodsSeriesResponse goodsSeriesResponse = goodsSeriesMapper.selectByUuId(new GoodsSeriesQuery().setSeriesName(seriesName).setCpId(goodsSku.getCpId()));
				if(goodsSeriesResponse == null){
					goodsSku.setErrorMessage(goodsSku.getErrorMessage() + "商品系列填写错误,");
					importMessage = true;
				}else{
					goodsSku.setSubUnitId(goodsSeriesResponse.getSeriesId());
				}
			}
			messageList.add(goodsSku);
		}


		//导出错误提示
		if (importMessage) {
			workbook = ExcelUtils.exportExcelUrl(messageList, "错误数据反馈", "错误数据反馈", GoodsSku.class, "商品档案错误数据反馈.xls", response);
			UUID uuid = UUID.randomUUID();
			String randomUUIDString = uuid.toString();
			//TODO 导出文件位置
			String fileName = "D:/练习/" + randomUUIDString;
			File outputFile = new File(fileName);
			//创建文件夹
			if (!outputFile.exists()) {
				outputFile.mkdir();
			}
			File uploadFile = new File(fileName, "商品档案错误数据反馈.xls");
			try (FileOutputStream fos = new FileOutputStream(uploadFile)) {
				workbook.write(fos);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return ResponseResultUtil.error(-300,"D:/练习/" + randomUUIDString + "/商品档案错误数据反馈.xls");
		}
		else{
			//插入数据
			for (GoodsSku goodsSku : messageList) {
				super.insert(goodsSku);
			}
			return ResponseResultUtil.success();
		}
	}

    public ResponseResultVO<?> saveUpdateList(List<GoodsSkuVO> goodsSkuVOS) {
		Boolean saveBoolean = goodsSkuMapper.saveWarningList(goodsSkuVOS);
		return ResponseResultUtil.success();
    }
}
