/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.ship.cable.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.log.model.LogUsual;
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.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.excel.CableExcel;
import org.springblade.modules.system.excel.CableImporter;
import org.springblade.modules.system.excel.UserExcel;
import org.springblade.modules.system.excel.UserImporter;
import org.springblade.modules.system.service.IDictService;
import org.springblade.modules.system.service.ILogUsualService;
import org.springblade.ship.cable.vo.Modify;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.ship.cable.entity.Cable;
import org.springblade.ship.cable.vo.CableVO;
import org.springblade.ship.cable.wrapper.CableWrapper;
import org.springblade.ship.cable.service.ICableService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-11-15
 */
@RestController
@AllArgsConstructor
@RequestMapping("ship/cable")
@Api(value = "", tags = "接口")
public class CableController extends BladeController {

	private final ICableService cableService;
	private final ILogUsualService logUsualService;
	private final IDictService dictService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入cable")
	public R<CableVO> detail(Cable cable) {
		Cable detail = cableService.getOne(Condition.getQueryWrapper(cable));
		return R.data(CableWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入cable")
	public R<IPage<CableVO>> list(CableVO cable, Query query) {
		QueryWrapper<Cable> queryWrapper = Condition.getQueryWrapper(cable);
		queryWrapper.lambda().orderByDesc(Cable::getCreateTime);
		if (cable.getCreateTimeBegin() != null && cable.getCreateTimeEnd() != null){
			queryWrapper.lambda().between(Cable::getCreateTime, cable.getCreateTimeBegin(), cable.getCreateTimeEnd());
		}
		IPage<Cable> pages = cableService.page(Condition.getPage(query), queryWrapper);
		return R.data(CableWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入cable")
	public R<IPage<CableVO>> page(CableVO cable, Query query) {
		IPage<CableVO> pages = cableService.selectCablePage(Condition.getPage(query), cable);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入cable")
	public R save(@Valid @RequestBody Cable cable) {
//		Cable one = cableService.getByAlias(cable.getAlias());
//		Assert.isNull(one, "代号为（" + cable.getAlias() + "）的记录已存在！");
		return R.status(cableService.save(cable));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入cable")
	public R update(@Valid @RequestBody Cable cable) {

		Cable old = cableService.getById(cable.getId());
		List<Map<String, Object>> becompare = becompare(cable, old);
		if (becompare.size() > 0){
			String compareStr = JSONUtil.toJsonStr(becompare);
			LogUsual logUsual = new LogUsual();
			logUsual.setLogData(compareStr);
			logUsual.setLogId(old.getId()+"");
			logUsual.setRequestUri("/cable/update");
			logUsual.setMethodName("update");
			logUsual.setCreateBy(AuthUtil.getUser().getAccount());
			logUsualService.save(logUsual);
			cable.setIsModify(1);
		}

		return R.status(cableService.updateById(cable));
	}


	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入cable")
	public R submit(@Valid @RequestBody Cable cable) {
		return R.status(cableService.saveOrUpdate(cable));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(cableService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 导入用户
	 */
	@PostMapping("/import-cable")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "导入用户", notes = "传入excel")
	public R importCable(MultipartFile file, Integer isCovered) {
		CableImporter cableImporter = new CableImporter(cableService, new Integer(1).equals(isCovered));
		ExcelUtil.save(file, cableImporter, CableExcel.class);
		return R.success("操作成功");
	}

	/**
	 * 导出用户
	 */
	@GetMapping("export-cable")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "导出用户", notes = "传入user")
	public void exportCable(CableVO cable, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<Cable> queryWrapper = Condition.getQueryWrapper(cable);
		if (cable.getCreateTimeBegin() != null && cable.getCreateTimeEnd() != null){
			queryWrapper.lambda().between(Cable::getCreateTime, cable.getCreateTimeBegin(), cable.getCreateTimeEnd());
		}
		List<CableExcel> list = cableService.exportCable(queryWrapper);
		ExcelUtil.export(response, "电缆数据" + DateUtil.time(), "电缆数据表", list, CableExcel.class);
	}

	/**
	 * 导出模板
	 */
	@GetMapping("export-template")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<CableExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "电缆数据模板", "电缆数据表", list, CableExcel.class);
	}

	/**
	 * 详情
	 */
	@GetMapping("/getCableList")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入cable")
	public R getList() {
		List<Cable> list = cableService.list();
		return R.data(list);
	}

	/**
	 * 修改历史
	 */
	@GetMapping("/getCableEditHistory")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入cable")
	public R getCableEditHistory(String cableId) {
		List<LogUsual> list = logUsualService.list(new QueryWrapper<>(new LogUsual()).lambda().eq(LogUsual::getRequestUri, "/cable/update").eq(LogUsual::getLogId, cableId));
		List<Modify> resList = new ArrayList<>();
		String account = AuthUtil.getUser().getAccount();
		list.forEach(item -> {
			Modify modify = new Modify();
			BeanUtil.copy(item, modify);
			modify.setModifyUserName(account);
			resList.add(modify);
		});

		return R.data(resList);
	}






	public List<Map<String, Object>> becompare(Cable newData, Cable oldData){
		List list = new ArrayList();

		if (!newData.getShipNo().equals(oldData.getShipNo())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getShipNo());
			item.put("newValue", newData.getShipNo());
			item.put("text", "产品编号");
			list.add(item);
		}
		if (!newData.getLabel().equals(oldData.getLabel())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getLabel());
			item.put("newValue", newData.getLabel());
			item.put("text", "标签");
			list.add(item);
		}
		if (!newData.getAlias().equals(oldData.getAlias())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getAlias());
			item.put("newValue", newData.getAlias());
			item.put("text", "电缆代号");
			list.add(item);
		}
		if (!newData.getCategory().equals(oldData.getCategory())){
			Map<String, Object> item = new HashMap<>();

			String oldValue = dictService.getValue("cable_category", oldData.getCategory());
			String newValue = dictService.getValue("cable_category", newData.getCategory());

			item.put("oldValue", oldValue);
			item.put("newValue", newValue);
			item.put("text", "类别");
			list.add(item);
		}
		if (!newData.getModel().equals(oldData.getModel())){
			Map<String, Object> item = new HashMap<>();

			String oldValue = dictService.getValue("cable_model", oldData.getModel());
			String newValue = dictService.getValue("cable_model", newData.getModel());

			item.put("oldValue", oldValue);
			item.put("newValue", newValue);
			item.put("text", "型号");
			list.add(item);
		}
		if (!newData.getSpecs().equals(oldData.getSpecs())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getSpecs());
			item.put("newValue", newData.getSpecs());
			item.put("text", "规格");
			list.add(item);
		}
		if (!newData.getDiameter().equals(oldData.getDiameter())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getDiameter());
			item.put("newValue", newData.getDiameter());
			item.put("text", "直径");
			list.add(item);
		}
		if (!newData.getBeginCabin().equals(oldData.getBeginCabin())){
			Map<String, Object> item = new HashMap<>();

			String oldValue = dictService.getValue("ship_cabin", oldData.getBeginCabin());
			String newValue = dictService.getValue("ship_cabin", newData.getBeginCabin());

			item.put("oldValue", oldValue);
			item.put("newValue", newValue);
			item.put("text", "起点舱室");
			list.add(item);
		}
		if (!newData.getBeginName().equals(oldData.getBeginName())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getBeginName());
			item.put("newValue", newData.getBeginName());
			item.put("text", "起点终端");
			list.add(item);
		}
		if (!newData.getBeginDeck().equals(oldData.getBeginDeck())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getBeginDeck());
			item.put("newValue", newData.getBeginDeck());
			item.put("text", "起点甲板");
			list.add(item);
		}
		if (!newData.getBeginShipSide().equals(oldData.getBeginShipSide())){
			Map<String, Object> item = new HashMap<>();

			String oldValue = dictService.getValue("ship_side", oldData.getBeginShipSide());
			String newValue = dictService.getValue("ship_side", newData.getBeginShipSide());

			item.put("oldValue", oldValue);
			item.put("newValue", newValue);
			item.put("text", "起点船舷");
			list.add(item);
		}
		if (!newData.getBeginRibPosition().equals(oldData.getBeginRibPosition())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getBeginRibPosition());
			item.put("newValue", newData.getBeginRibPosition());
			item.put("text", "起点肋位");
			list.add(item);
		}
		if (!newData.getPassNode().equals(oldData.getPassNode())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getPassNode());
			item.put("newValue", newData.getPassNode());
			item.put("text", "经过节点");
			list.add(item);
		}

		if (!newData.getEndCabin().equals(oldData.getEndCabin())){
			Map<String, Object> item = new HashMap<>();

			String oldValue = dictService.getValue("ship_cabin", oldData.getEndCabin());
			String newValue = dictService.getValue("ship_cabin", newData.getEndCabin());

			item.put("oldValue", oldValue);
			item.put("newValue", newValue);
			item.put("text", "终点舱室");
			list.add(item);
		}
		if (!newData.getEndName().equals(oldData.getEndName())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getEndName());
			item.put("newValue", newData.getEndName());
			item.put("text", "终点终端");
			list.add(item);
		}
		if (!newData.getEndDeck().equals(oldData.getEndDeck())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getEndDeck());
			item.put("newValue", newData.getEndDeck());
			item.put("text", "终点甲板");
			list.add(item);
		}
		if (!newData.getEndShipSide().equals(oldData.getEndShipSide())){
			Map<String, Object> item = new HashMap<>();

			String oldValue = dictService.getValue("ship_side", oldData.getEndShipSide());
			String newValue = dictService.getValue("ship_side", newData.getEndShipSide());

			item.put("oldValue", oldValue);
			item.put("newValue", newValue);
			item.put("text", "终点船舷");
			list.add(item);
		}
		if (!newData.getEndRibPosition().equals(oldData.getEndRibPosition())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getEndRibPosition());
			item.put("newValue", newData.getEndRibPosition());
			item.put("text", "终点肋位");
			list.add(item);
		}

		if (!newData.getStopPoint().equals(oldData.getStopPoint())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getStopPoint());
			item.put("newValue", newData.getStopPoint());
			item.put("text", "电缆停止点");
			list.add(item);
		}
		if (!newData.getLen().equals(oldData.getLen())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getLen());
			item.put("newValue", newData.getLen());
			item.put("text", "电缆前长度");
			list.add(item);
		}
		if (!newData.getFrontLen().equals(oldData.getFrontLen())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getFrontLen());
			item.put("newValue", newData.getFrontLen());
			item.put("text", "电缆总长");
			list.add(item);
		}
		if (!newData.getDrawingNo().equals(oldData.getDrawingNo())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getDrawingNo());
			item.put("newValue", newData.getDrawingNo());
			item.put("text", "系统图号");
			list.add(item);
		}
		if (!newData.getRemark().equals(oldData.getRemark())){
			Map<String, Object> item = new HashMap<>();
			item.put("oldValue", oldData.getRemark());
			item.put("newValue", newData.getRemark());
			item.put("text", "备注");
			list.add(item);
		}


		return list;
	}


}
