package com.yeejoin.amos.boot.module.jcs.biz.controller;

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

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.Menu;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersDto;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersInfoDto;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersZhDto;
import com.yeejoin.amos.boot.module.common.api.entity.Firefighters;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersContacts;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersContract;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersEducation;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersJacket;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersPost;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersThought;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersContactsServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersContractServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersEducationServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersPostServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersThoughtServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.FirefightersJacketServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 消防队员
 *
 * @author tb
 * @date 2021-06-07
 */
@RestController
@Api(tags = "消防队员Api")
@RequestMapping(value = "/firefighters")
public class FirefightersController extends BaseController {

	@Autowired
	FirefightersServiceImpl iFirefightersService;
	@Autowired
	FirefightersPostServiceImpl iFirefightersPostService;
	@Autowired
	FirefightersContactsServiceImpl ifirefightersContactsService;
	@Autowired
	FirefightersEducationServiceImpl ifirefightersEducationService;
	@Autowired
	FirefightersThoughtServiceImpl iFirefightersThoughtService;
	@Autowired
	FirefightersContractServiceImpl iFirefightersContractService;
	@Autowired
	FirefightersJacketServiceImpl iFirefightersJacketService;
	@Autowired
	RedisUtils redisUtils;
	@Value("${redis.cache.failure.time}")
	private long time;

	/**
	 * 新增消防队员
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增消防队员", notes = "新增消防队员")
	@Transactional
	public ResponseModel<FirefightersInfoDto> saveFirefighters(@RequestBody FirefightersInfoDto firefighters) {
		try {
			iFirefightersService.saveFirefighters(firefighters);
			return ResponseHelper.buildResponse(firefighters);
		} catch (Exception e) {

			throw new RuntimeException("系统异常");
		}

	}

	/**
	 * 根据id删除
	 *
	 * @param id
	 * @return
	 */
	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	@Transactional
	public ResponseModel<Object> deleteById(HttpServletRequest request, @PathVariable Long id) {
		QueryWrapper<FirefightersJacket> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("firefighters_id", id);
		queryWrapper.eq("is_delete", 0);
		List<FirefightersJacket> firefightersJacket = iFirefightersJacketService.list(queryWrapper);
		if (firefightersJacket != null && firefightersJacket.size() > 0) {
			throw new RuntimeException("该消防还有在装装备！");
		}
		try {
			iFirefightersService.update(new UpdateWrapper<Firefighters>().eq("sequence_nbr", id).set("is_delete", 1));
			iFirefightersPostService
					.update(new UpdateWrapper<FirefightersPost>().eq("firefighters_id", id).set("is_delete", 1));
			ifirefightersContactsService
					.update(new UpdateWrapper<FirefightersContacts>().eq("firefighters_id", id).set("is_delete", 1));
			ifirefightersEducationService
					.update(new UpdateWrapper<FirefightersEducation>().eq("firefighters_id", id).set("is_delete", 1));
			iFirefightersThoughtService
					.update(new UpdateWrapper<FirefightersThought>().eq("firefighters_id", id).set("is_delete", 1));
			iFirefightersContractService
					.update(new UpdateWrapper<FirefightersContract>().eq("firefighters_id", id).set("is_delete", 1));
			iFirefightersJacketService
					.update(new UpdateWrapper<FirefightersJacket>().eq("firefighters_id", id).set("is_delete", 1));
			// 删除缓存
			redisUtils.del(RedisKey.FIREFIGHTERS_ID + id, RedisKey.FIREFIGHTERS_LIST_ID + id);
			return ResponseHelper.buildResponse(null);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("删除失败！");
		}
	}

	/**
	 * 修改消防队员
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/updateById", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "修改消防队员", notes = "修改消防队员")
	@Transactional
	public ResponseModel<Object> updateByIdFirefighters(HttpServletRequest request,
			@RequestBody FirefightersInfoDto firefighters) {
		try {
			Firefighters firefighter = firefighters.getFirefighters();
			iFirefightersService.updateById(firefighter);
			ifirefightersContactsService.updateById(firefighters.getFirefightersContacts());
			// 删除缓存
			redisUtils.del(RedisKey.FIREFIGHTERS_ID + firefighter.getSequenceNbr(),
					RedisKey.FIREFIGHTERS_LIST_ID + firefighter.getSequenceNbr());
			return ResponseHelper.buildResponse(null);
		} catch (Exception e) {

			throw new RuntimeException("系统异常");
		}
	}

	/**
	 * 根据id查询
	 *
	 * @param id
	 * @return
	 */
	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	public ResponseModel<Object> selectById(HttpServletRequest request, @PathVariable Long id) {

		if (redisUtils.hasKey(RedisKey.FIREFIGHTERS_ID + id)) {
			Object obj = redisUtils.get(RedisKey.FIREFIGHTERS_ID + id);
			return ResponseHelper.buildResponse(obj);
		} else {
			Firefighters firefighters = iFirefightersService.getById(id);
			QueryWrapper<FirefightersContacts> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("firefighters_id", id);
			FirefightersContacts firefightersContacts = ifirefightersContactsService.getOne(queryWrapper);
			FirefightersInfoDto firefightersInfoDto = new FirefightersInfoDto(firefighters, firefightersContacts);
			redisUtils.set(RedisKey.FIREFIGHTERS_ID + id, JSON.toJSON(firefightersInfoDto), time);
			return ResponseHelper.buildResponse(firefightersInfoDto);
		}
	}

	/**
	 * 列表详情展示
	 */

	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/list/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "列表详情根据id查询", notes = "列表详情根据id查询")
	public ResponseModel<Object> listToSelectById(HttpServletRequest request, @PathVariable Long id) {
		if (redisUtils.hasKey(RedisKey.FIREFIGHTERS_LIST_ID + id)) {
			Object obj = redisUtils.get(RedisKey.FIREFIGHTERS_LIST_ID + id);
			return ResponseHelper.buildResponse(obj);
		} else {
			Map<String, Object> firefighters = iFirefightersService.listToSelectById(id);
			redisUtils.set(RedisKey.FIREFIGHTERS_LIST_ID + id, JSON.toJSON(firefighters), time);
			return ResponseHelper.buildResponse(firefighters);
		}
	}

	/**
	 * 列表分页查询
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public IPage<Firefighters> listPage(String pageNum, String pageSize, Firefighters firefighters) {
		Page<Firefighters> pageBean;
		QueryWrapper<Firefighters> firefightersQueryWrapper = new QueryWrapper<>();
		Class<? extends Firefighters> aClass = firefighters.getClass();
		Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
			try {
				field.setAccessible(true);
				Object o = field.get(firefighters);
				if (o != null) {
					Class<?> type = field.getType();
					String name = NameUtils.camel2Underline(field.getName());
					if (type.equals(Integer.class)) {
						Integer fileValue = (Integer) field.get(firefighters);
						firefightersQueryWrapper.eq(name, fileValue);
					} else if (type.equals(Long.class)) {
						Long fileValue = (Long) field.get(firefighters);
						firefightersQueryWrapper.eq(name, fileValue);
					} else if (type.equals(String.class)) {
						String fileValue = (String) field.get(firefighters);
						firefightersQueryWrapper.eq(name, fileValue);
					} else {
						if (!name.equals(NameUtils.camel2Underline("serialVersionUID"))) {
							String fileValue = (String) field.get(firefighters);
							firefightersQueryWrapper.eq(name, fileValue);
						}
					}
				}
			} catch (Exception e) {
				throw new RuntimeException("系统异常");
			}
		});
		IPage<Firefighters> page;
		if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		page = iFirefightersService.page(pageBean, firefightersQueryWrapper);
		return page;
	}

	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/getFirefighters", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "新列表分页查询", notes = "新表分页查询")
	public ResponseModel<Page<FirefightersZhDto>> getFirefighters(Integer pageNum, Integer pageSize,
			FirefightersDto firefighters) {
		// 条件分页
		if (null == pageNum || null == pageSize) {
			pageNum = 1;
			pageSize = Integer.MAX_VALUE;
		}
		List<FirefightersZhDto> list = iFirefightersService.getFirefighters((pageNum - 1) * pageSize, pageSize,
				firefighters);
		Map<String, Long> num = iFirefightersService.getFirefightersCount((pageNum - 1) * pageSize, pageSize,
				firefighters);
		Page<FirefightersZhDto> pageBean = new Page<>(pageNum, pageSize, num.get("num"));
		pageBean.setRecords(list);
		return ResponseHelper.buildResponse(pageBean);
	}

	/**
	 * 岗位树，带统计
	 *
	 * @param
	 * @return
	 * @throws Exception
	 */
	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/getFirefightersJobTitleCount", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	public ResponseModel<Object> getFirefightersJobTitleCount() throws Exception {
		List<Menu> menus = iFirefightersService.getFirefightersJobTitleCount();
		return ResponseHelper.buildResponse(menus);
	}

}
