package com.emergency.avenue.storage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.emergency.avenue.admin.api.entity.SysDept;
import com.emergency.avenue.admin.api.entity.SysDeptRelation;
import com.emergency.avenue.admin.api.entity.SysTreeDict;
import com.emergency.avenue.admin.api.vo.MaterialFailureVO;
import com.emergency.avenue.admin.api.vo.MaterialOutboundVO;
import com.emergency.avenue.admin.service.SysDeptRelationService;
import com.emergency.avenue.admin.service.SysDeptService;
import com.emergency.avenue.admin.service.SysTreeDictService;
import com.emergency.avenue.common.core.util.R;
import com.emergency.avenue.common.log.annotation.SysLog;
import com.emergency.avenue.common.security.util.SecurityUtils;
import com.emergency.avenue.storage.api.entity.*;
import com.emergency.avenue.storage.api.request.MaterialMaintenanceRequest;
import com.emergency.avenue.storage.service.MaterialMaintenanceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
@RequestMapping("/maintenance")
@Tag(description = "maintenance", name = "物资维护信息管理")
public class MaterialMaintenanceController {

	private final MaterialMaintenanceService materialMaintenanceService;

	private final SysDeptRelationService relationService;

	private final SysTreeDictService sysTreeDictService;

	private final SysDeptService sysDeptService;

	@GetMapping("/page")
	@Operation(description = "物资维护信息分页查询", summary = "物资维护信息分页查询")
	public R<Page<MaterialMaintenance>> getMaterialMaintenancePage(Page page, MaterialMaintenance materialMaintenance) {
		List<String> deptIds = relationService.list(Wrappers.<SysDeptRelation>lambdaQuery().eq(SysDeptRelation::getAncestor, SecurityUtils.getUser().getDeptId()))
				.stream()
				.map(SysDeptRelation::getDescendant).collect(Collectors.toList());
		QueryWrapper<MaterialMaintenance> query = Wrappers.query(materialMaintenance);
		query.lambda().in(MaterialMaintenance::getDeptId, deptIds);
		String deptType = SecurityUtils.getUser().getDeptType();
		if (deptType.equals("2")) {
			query.lambda().ne(MaterialMaintenance::getStatus, "1");
			query.orderByAsc("FIELD(status,'2','6','3','4','5')");
		} else if (deptType.equals("1")) {
			query.lambda().notIn(MaterialMaintenance::getStatus, Arrays.asList("1", "2", "4"));
			query.lambda().orderByAsc(MaterialMaintenance::getStatus);
		} else if (deptType.equals("3")) {
			query.orderByAsc("FIELD(status,'4','1','2','3','5','6')");
		}
		if (StringUtils.isNotEmpty(materialMaintenance.getMaterialNameVo())) {
			QueryWrapper<SysTreeDict> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(SysTreeDict::getType, "1");
			queryWrapper.lambda().like(SysTreeDict::getName, materialMaintenance.getMaterialNameVo());
			List<SysTreeDict> list1 = sysTreeDictService.list(queryWrapper);
			if(list1.size()<1){
				return R.ok(new Page<MaterialMaintenance>());
			}
			List<String> collect = list1.stream().map(SysTreeDict::getId).collect(Collectors.toList());
			query.lambda().in(MaterialMaintenance::getMaterialName, collect);
		}
		query.lambda().orderByDesc(MaterialMaintenance::getSubmitTime);
		if (ObjectUtils.isNotEmpty(materialMaintenance.getStartEntryDate()) && ObjectUtils.isNotEmpty(materialMaintenance.getEndEntryDate())) {
			query.lambda().between(MaterialMaintenance::getEntryDate, materialMaintenance.getStartEntryDate(), materialMaintenance.getEndEntryDate());
		}
		Page<MaterialMaintenance> page1 = materialMaintenanceService.page(page, query);
		List<SysTreeDict> list = sysTreeDictService.getList(1);
		Map<String, String> collect = list.stream().collect(Collectors.toMap(SysTreeDict::getId, SysTreeDict::getName));
		List<SysDept> list1 = sysDeptService.list();
		Map<String, String> collect1 = list1.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getAbbreviationName));
		List<MaterialMaintenance> records = page1.getRecords();
		for (MaterialMaintenance materialMaintenance1 : records) {
			materialMaintenance1.setMaterialGroupVo(collect.get(materialMaintenance1.getMaterialGroup()));
			materialMaintenance1.setMaterialTypeVo(collect.get(materialMaintenance1.getMaterialType()));
			materialMaintenance1.setMaterialNameVo(collect.get(materialMaintenance1.getMaterialName()));
			materialMaintenance1.setMaterialUnitVo(collect.get(materialMaintenance1.getMaterialUnit()));
			materialMaintenance1.setWarehouse(collect1.get(materialMaintenance1.getDeptId()));
		}
		return R.ok(page1);
	}

	/**
	 * 通过ID查询物资维护信息
	 *
	 * @param id ID
	 * @return 物资维护信息
	 */
	@GetMapping("/{id}")
	@Operation(description = "通过ID查询物资维护信息", summary = "通过ID查询物资维护信息")
	public R<MaterialMaintenance> getById(@PathVariable Integer id) {
		return R.ok(materialMaintenanceService.getMaterialMaintenanceById(id));
	}

	@SysLog("添加物资维护信息")
	@PostMapping
	@Operation(description = "添加物资维护信息及维护信息", summary = "添加物资维护信息及维护信息")
	public R save(@RequestBody MaterialMaintenance materialMaintenance) {
		return materialMaintenanceService.saveMaterialMaintenance(materialMaintenance);
	}

	@PutMapping
	@SysLog("修改物资维护信息")
	@Operation(description = "修改物资维护信息", summary = "修改物资维护信息")
	public R updateById(@RequestBody MaterialMaintenance materialMaintenance) {
		return R.ok(materialMaintenanceService.updateMaterialMaintenance(materialMaintenance));
	}

	@SysLog("删除物资维护信息")
	@DeleteMapping("/{id}")
	@Operation(description = "删除物资维护信息", summary = "删除物资维护信息")
	public R removeById(@PathVariable Long id) {
		return R.ok(materialMaintenanceService.removeByIdAndDetail(id));
	}

	@PutMapping("/auditing")
	@Operation(description = "审核物资维护信息", summary = "审核物资维护信息")
	public R auditing(@RequestBody MaterialMaintenanceStatus materialMaintenanceStatus) {
		return materialMaintenanceService.saveInboundStatus(materialMaintenanceStatus);
	}
	@PostMapping("/getTimeAndUnitPrice")
	@Operation(description = "获取库存物资信息", summary = "获取库存物资信息")
	public R getTimeAndUnitPrice(@RequestBody MaterialView materialView){
		return materialMaintenanceService.getTimeAndUnitPrice(materialView);

	}
	@PostMapping("/getTimeAndUnitPriceForFailure")
	@Operation(description = "设备故障获取库存物资信息", summary = "设备故障获取库存物资信息")
	public R getTimeAndUnitPriceForFailure(@RequestBody MaterialFailureVO materialFailureVO){
		return R.ok(materialMaintenanceService.getTimeAndUnitPriceForFailure(materialFailureVO));
	}
	@PostMapping("/getTimeAndUnitPriceForOutbound")
	@Operation(description = "出库下发获取库存物资信息", summary = "出库下发获取库存物资信息")
	public R getTimeAndUnitPriceForOutbound(@RequestBody MaterialOutboundVO materialOutboundOV){
		return R.ok(materialMaintenanceService.getTimeAndUnitPriceForOutbound(materialOutboundOV));
	}
	@PostMapping("/getStatistics")
	@Operation(description = "获取库存物资统计信息", summary = "获取库存物资统计信息")
	public R getStatistics(@RequestBody MaterialMaintenanceRequest materialMaintenanceRequest){
		return R.ok(materialMaintenanceService.getStatistics(materialMaintenanceRequest));
	}
	@GetMapping("/getStatistics/{id}")
	@Operation(description = "获取库存物资统计信息详细(id)", summary = "获取库存物资统计信息详细(id)")
	public R getStatisticsbyId(@PathVariable Integer id){
		return R.ok(materialMaintenanceService.getStatisticsbyId(id));
	}
}