package com.emergency.avenue.storage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.emergency.avenue.admin.api.entity.SysDeptRelation;
import com.emergency.avenue.admin.api.entity.SysDictItem;
import com.emergency.avenue.admin.api.entity.SysTreeDict;
import com.emergency.avenue.admin.service.SysDeptRelationService;
import com.emergency.avenue.admin.service.SysDictItemService;
import com.emergency.avenue.admin.service.SysTreeDictService;
import com.emergency.avenue.common.core.util.R;
import com.emergency.avenue.common.security.util.SecurityUtils;
import com.emergency.avenue.storage.api.entity.*;
import com.emergency.avenue.storage.api.vo.TransferOrderVo;
import com.emergency.avenue.storage.mapper.OrderOutboundMapper;
import com.emergency.avenue.storage.mapper.TransferOrderMapper;
import com.emergency.avenue.storage.service.OutboundMaterialService;
import com.emergency.avenue.storage.service.OutboundService;
import com.emergency.avenue.storage.service.TransferOrderService;
import com.emergency.avenue.storage.util.MyFileUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class TransferOrderServiceImpl  extends ServiceImpl<TransferOrderMapper, TransferOrder>  implements TransferOrderService {


	private final  TransferOrderMapper transferOrderMapper;

	private final OutboundService outboundService;

	private final OutboundMaterialService outboundMaterialService;

	private final OrderOutboundMapper orderOutboundMapper;

	private final SysTreeDictService sysTreeDictService;

	private final SysDictItemService sysDictItemService;

	private final SysDeptRelationService relationService;
	@Override
	public R saveTransferOrderAndMaterial(TransferOrder transferOrder) {
		if (transferOrder.getOrderId()==null) {
			transferOrderMapper.insert(transferOrder);
		}else {
			transferOrderMapper.updateById(transferOrder);
			List<OrderOutbound> orderOutbounds = orderOutboundMapper.selectList(Wrappers.<OrderOutbound>lambdaQuery().eq(OrderOutbound::getOrderId, transferOrder.getOrderId()));
			for (OrderOutbound orderOutbound:orderOutbounds) {
				outboundMaterialService.remove(Wrappers.<OutboundMaterialInfo>query().lambda().eq(OutboundMaterialInfo::getOutboundId, orderOutbound.getOutboundId()));
				outboundService.removeById(orderOutbound.getOutboundId());
			}
			orderOutboundMapper.delete(Wrappers.<OrderOutbound>lambdaQuery().eq(OrderOutbound::getOrderId, transferOrder.getOrderId()));
		}
		List<OrderOutboundMaterialInfo> orderOutboundMaterialInfos = transferOrder.getOrderOutboundMaterialInfos();
		for (OrderOutboundMaterialInfo orderOutboundMaterialInfo : orderOutboundMaterialInfos) {
			OutboundInfo outboundInfo = new OutboundInfo();
			OutboundMaterialInfo outboundMaterialInfo = new OutboundMaterialInfo();
			BeanUtil.copyProperties(orderOutboundMaterialInfo, outboundInfo);
			BeanUtil.copyProperties(orderOutboundMaterialInfo, outboundMaterialInfo);
			LinkedList<OutboundMaterialInfo> outboundMaterialInfos = new LinkedList<>();
			outboundMaterialInfo.setMaterialId(null);
			outboundMaterialInfos.add(outboundMaterialInfo);
			outboundInfo.setStatus(transferOrder.getStatus());
			outboundInfo.setCalledProvince(orderOutboundMaterialInfo.getProvince());
			outboundInfo.setOutboundMaterialInfos(outboundMaterialInfos);
			outboundInfo.setOutboundId(null);
			outboundService.saveOutbountAndMaterial(outboundInfo);
			// 保存调令与下发信息中间表
			OrderOutbound orderOutbound = new OrderOutbound();
			orderOutbound.setOutboundId(outboundInfo.getOutboundId() + "");
			orderOutbound.setOrderId(transferOrder.getOrderId() + "");
			orderOutboundMapper.insert(orderOutbound);
		}
		return R.ok("成功");
	}

	@Override
	public Boolean removeByIdAndTransferOrder(Long id) {
		List<OrderOutbound> orderOutbounds = orderOutboundMapper.selectList(Wrappers.<OrderOutbound>lambdaQuery().eq(OrderOutbound::getOrderId, id));
		for (OrderOutbound orderOutbound:orderOutbounds) {
			outboundMaterialService.remove(Wrappers.<OutboundMaterialInfo>query().lambda().eq(OutboundMaterialInfo::getOutboundId, orderOutbound.getOutboundId()));
			outboundService.removeById(orderOutbound.getOutboundId());
		}
		orderOutboundMapper.delete(Wrappers.<OrderOutbound>lambdaQuery().eq(OrderOutbound::getOrderId,id));
		return SqlHelper.retBool(transferOrderMapper.deleteById(id));
	}

	@Override
	public R getTransferOrderPage(Page<TransferOrderVo> page, TransferOrderVo transferOrder) {
		List<String> deptIds = relationService.list(Wrappers.<SysDeptRelation>lambdaQuery().eq(SysDeptRelation::getAncestor, SecurityUtils.getUser().getDeptId()))
				.stream()
				.map(SysDeptRelation::getDescendant).collect(Collectors.toList());
		transferOrder.setDeptIds(deptIds);
		if (StringUtils.isNotEmpty(transferOrder.getMaterialName())) {
			QueryWrapper<SysTreeDict> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(SysTreeDict::getType,"1");
			queryWrapper.lambda().like(SysTreeDict::getName,transferOrder.getMaterialName());
			List<SysTreeDict> list1 = sysTreeDictService.list(queryWrapper);
			List<String> collect = list1.stream().map(SysTreeDict::getId).collect(Collectors.toList());
			if (collect.size()<1){
				return R.ok(page);
			}
			transferOrder.setMaterialNames(collect);
		}
		IPage<TransferOrderVo> transferOrderPage = transferOrderMapper.getTransferOrderPage(page, transferOrder);
		List<TransferOrderVo> records = transferOrderPage.getRecords();
		List<SysTreeDict> list = sysTreeDictService.getList(1);
		Map<String, String> collect = list.stream().collect(Collectors.toMap(SysTreeDict::getId, SysTreeDict::getName));
		Map<String, Map<String, String>> sysDictItemList = sysDictItemService.selectDictItem()
				.stream().collect(Collectors.groupingBy(SysDictItem::getDictType,
						Collectors.toMap(SysDictItem::getItemValue, SysDictItem::getLabel, (p1, p2) -> p2)));
		Map<String, String> province_ch = sysDictItemList.get("province_ch");
		for(TransferOrderVo transferOrderVo:records){
			if (StringUtils.isNotEmpty(transferOrderVo.getMaterialName())){
				String[] split = transferOrderVo.getMaterialName().split(",");
				StringBuilder namev=new StringBuilder();
				for (String name:split){
					namev.append(collect.get(name)+ " ");
				}
				transferOrderVo.setMaterialName(namev.toString());
			}
			if (StringUtils.isNotEmpty(transferOrderVo.getProvince())){
				StringBuilder provincev=new StringBuilder();
				String[] provinces = transferOrderVo.getProvince().split(",");
				for (String province:provinces){
					provincev.append(province_ch.get(province)+" ");
				}
				transferOrderVo.setProvince(provincev.toString());
			}
		}
		return R.ok(transferOrderPage);
	}

	@Override
	public TransferOrder getByIdAndTransferOrder(Integer id) {
		TransferOrder transferOrder = transferOrderMapper.selectById(id);
		List<OrderOutbound> orderOutbounds = orderOutboundMapper.selectList(Wrappers.<OrderOutbound>lambdaQuery().eq(OrderOutbound::getOrderId, transferOrder.getOrderId()));
		List<String> collect = orderOutbounds.stream().map(OrderOutbound::getOutboundId).collect(Collectors.toList());
		List<OrderOutboundMaterialInfo> orderOutboundMaterialInfo = transferOrderMapper.getOrderOutboundMaterialInfo(collect);
		orderOutboundMaterialInfo.forEach(orderOutboundMaterialInfo1 ->
				orderOutboundMaterialInfo1.setMaterialTree(Arrays.asList(orderOutboundMaterialInfo1.getMaterialGroup()
				,orderOutboundMaterialInfo1.getMaterialType(),orderOutboundMaterialInfo1.getMaterialName(),
						orderOutboundMaterialInfo1.getUnit())));
		transferOrder.setOrderOutboundMaterialInfos(orderOutboundMaterialInfo);
		return transferOrder;
	}

	@Override
	public void export(String fileName, String templateFile, List<TransferOrderVo> list0, HttpServletResponse response) {
		list0.forEach(transferOrderVo -> format(transferOrderVo));
		MyFileUtil.listToExcel(response,fileName, templateFile, -1,null, list0, null);
	}
	public void format(TransferOrderVo transferOrderVo){
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		transferOrderVo.setSubmitTimeVo(formatter.format(transferOrderVo.getSubmitTime()));
		Map<String, Map<String, String>> sysDictItemList = sysDictItemService.selectDictItem()
				.stream().collect(Collectors.groupingBy(SysDictItem::getDictType,
						Collectors.toMap(SysDictItem::getItemValue, SysDictItem::getLabel, (p1, p2) -> p2)));
		Map<String, String> outdound_type = sysDictItemList.get("outdound_type");
		transferOrderVo.setOutboundType(outdound_type.get(transferOrderVo.getOutboundType()));
	}
}
