package com.yeejoin.equipmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.equipmanage.common.entity.Warehouse;
import com.yeejoin.equipmanage.common.utils.NameUtils;
import com.yeejoin.equipmanage.mapper.WarehouseMapper;
import com.yeejoin.equipmanage.remote.RemoteSecurityService;
import com.yeejoin.equipmanage.service.IWarehouseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 仓库信息
 *
 * @author wujiang
 * @date 2020-07-07
 */
@RestController
@Api(tags = "仓库信息Api")
@RequestMapping(value = "/warehouse", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class WarehouseController extends AbstractBaseController {

	@Autowired
	IWarehouseService iWarehouseService;
	@Autowired
	WarehouseMapper warehouseMapper;
	@Autowired
	private RemoteSecurityService remoteSecurityService;

	/**
	 * 新增仓库信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST", value = "新增仓库信息", notes = "新增仓库信息")
	public Boolean saveWarehouse(HttpServletRequest request, @RequestBody Warehouse warehouse) {
		QueryWrapper<Warehouse> warehouseQueryWrapper = new QueryWrapper<>();
		warehouseQueryWrapper.eq("name", warehouse.getName());
		if (iWarehouseService.count(warehouseQueryWrapper) > 0) {
			throw new RuntimeException("仓库名称不能重复");
		}
		return iWarehouseService.save(warehouse);
	}

	/**
	 * 远程同步新增修改仓库货架信息
	 *
	 * @param request
	 * @param source
	 * @return Warehouse
	 * @throws <br>
	 * @author 张展弋
	 * @date 2020-9-8 11:19:42
	 */
//	@RequestMapping(value = "/saveAutoSysSyn", method = RequestMethod.POST)
//	    @TycloudOperation(ApiLevel = UserType.AGENCY)
//	@ApiOperation(httpMethod = "POST", value = "远程同步新增修改", notes = "远程同步新增修改仓库货架信息")
//	public CommonResponse saveAutoSysSyn(HttpServletRequest request, @RequestBody Warehouse source) {
//		String resMsg = iWarehouseService.saveAutoSysSyn(source);
//		CommonResponse cr = new CommonResponse();
//		if (resMsg != null) {
//			cr.setResult(FAILED);
//			cr.setMessage(resMsg);
//			return cr;
//		}
//		cr.setResult(SUCCESS);
//		return cr;
//	}

	/**
	 * 远程同步删除仓库货架信息
	 *
	 * @param request
	 * @param id
	 * @return CommonResponse
	 * @throws <br>
	 * @author 张展弋
	 * @date 2020-9-8 18:35:44
	 */
//	@RequestMapping(value = "/deleteAutoSysSyn", method = RequestMethod.POST)
//	    @TycloudOperation(ApiLevel = UserType.AGENCY)
//	@ApiOperation(httpMethod = "POST", value = "远程同步删除 ", notes = "远程同步删除仓库货架信息 ")
//	public CommonResponse deleteAutoSysSyn(HttpServletRequest request, @RequestBody Long id) {
//		String resMsg = iWarehouseService.deleteAutoSysSyn(id);
//		CommonResponse cr = new CommonResponse();
//		if (resMsg != null) {
//			cr.setResult(FAILED);
//			cr.setMessage(resMsg);
//			return cr;
//		}
//		cr.setResult(SUCCESS);
//		return cr;
//	}

	/**
	 * 根据id删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	public boolean deleteById(HttpServletRequest request, @PathVariable Long id) {
		return iWarehouseService.removeById(id);
	}

	/**
	 * 修改仓库信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.PUT)
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "PUT", value = "修改仓库信息", notes = "修改仓库信息")
	public Warehouse updateByIdWarehouse(HttpServletRequest request, @RequestBody Warehouse warehouse) {
		iWarehouseService.updateById(warehouse);
		return warehouse;
	}

	@RequestMapping(value = "/getWarehouse", method = RequestMethod.PUT)
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "仓库信息", notes = "仓库信息")
	public List<Warehouse> getWarehouse(HttpServletRequest request) {
		List<Warehouse> list = warehouseMapper.selectByMap(null);
		return list;
	}

	/**
	 * 根据id查询
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	public Warehouse selectById(HttpServletRequest request, @PathVariable Long id) {
		return iWarehouseService.getById(id);
	}

	/**
	 * 列表分页查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public IPage<Warehouse> listPage(String pageNumber, String pageSize, Warehouse warehouse) {

		Page<Warehouse> pageBean;
		QueryWrapper<Warehouse> warehouseQueryWrapper = new QueryWrapper<>();
		Class<? extends Warehouse> aClass = warehouse.getClass();
		Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
			try {
				ReflectionUtils.makeAccessible(field);
				Object o = field.get(warehouse);
				if (o != null) {
					Class<?> type = field.getType();
					String name = NameUtils.camel2Underline(field.getName());
					if (type.equals(Integer.class)) {
						Integer fileValue = (Integer) field.get(warehouse);
						warehouseQueryWrapper.eq(name, fileValue);
					} else if (type.equals(Long.class)) {
						Long fileValue = (Long) field.get(warehouse);
						warehouseQueryWrapper.eq(name, fileValue);
					} else if (type.equals(String.class)) {
						String fileValue = (String) field.get(warehouse);
						if ("name".equalsIgnoreCase(name)) {
							warehouseQueryWrapper.like("name", fileValue);
						} else {
							warehouseQueryWrapper.eq(name, fileValue);
						}

					} else {
						String fileValue = (String) field.get(warehouse);
						warehouseQueryWrapper.eq(name, fileValue);
					}
				}
			} catch (Exception e) {
			}
		});
		IPage<Warehouse> page;
		if (StringUtils.isBlank(pageNumber) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNumber), Integer.parseInt(pageSize));
		}
		page = iWarehouseService.page(pageBean, warehouseQueryWrapper);
		return page;
	}

	/**
	 * 根据orgcode查询
	 *
	 * @param orgcode
	 * @return
	 */
	@RequestMapping(value = "/orgcode/{orgcode}", method = RequestMethod.GET)
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	public Map<String, Object> selectByOrgcode(HttpServletRequest request, @PathVariable String orgcode) {
		if (orgcode.equals("amos")) {
			orgcode = getOrgCode();
		}
		List<Warehouse> list = iWarehouseService.list(new QueryWrapper<Warehouse>().eq("org_code", orgcode));
		if (list != null && !list.isEmpty()) {
			// 获取登录仓库后，返回系统业务字典（默认字典code值不能改变）
			List<DictionarieValueModel> listdate = remoteSecurityService
					.listDictionaryByDictCode("BUSINESS_DICTIONARY");
			Map<String, Object> map = new HashMap<String, Object>();
			if (listdate != null && listdate.size() > 0) {
				for (DictionarieValueModel dictionarieValueModel : listdate) {
					if ("EXTINGUISHING".equals(dictionarieValueModel.getDictDataKey())) {
						map.put("dictionaries", dictionarieValueModel.getDictDataValue());
					}
				}
			}
			map.put("warehouse", list.get(0));

			return map;
		} else {
			return null;
		}
	}

	/**
	 * 批量删除
	 *
	 * @param idList
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	public boolean delete(HttpServletRequest request, @RequestBody List<Long> idList) throws Exception {
		return iWarehouseService.removeBatchById(idList);
	}
}
