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

import java.util.Arrays;

import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import org.apache.commons.lang3.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.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.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.FirefightersDataDto;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersEducation;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersPost;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersWorkexperience;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FirefightersContactsServiceImpl;
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.FirefightersWorkexperienceServiceImpl;

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

/**
 * 岗位信息
 *
 * @author tb
 * @date 2021-06-07
 */
@RestController
@Api(tags = "岗位信息Api")
@RequestMapping(value = "/firefighters-post")
public class FirefightersPostController extends BaseController {

	@Autowired
	FirefightersPostServiceImpl iFirefightersPostService;
	@Autowired
	FirefightersContactsServiceImpl ifirefightersContactsService;
	@Autowired
	FirefightersEducationServiceImpl ifirefightersEducationService;
	@Autowired
	FirefightersWorkexperienceServiceImpl ifirefightersWorkexperienceService;
	@Autowired
	DataDictionaryServiceImpl dataDictionaryService;

	@Autowired
	RedisUtils redisUtils;
	@Value("${redis.cache.failure.time}")
	private long time;

	/**
	 * 新增岗位信息
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增岗位信息", notes = "新增岗位信息")
	@Transactional
	public ResponseModel<Object> saveFirefightersPost(@RequestBody FirefightersDataDto firefightersDataDto) {
		try {
			/*---------修改bug:2179   解決崗位与学历可以重复添加导致的列表页展示消防人员信息呈现多条的情况  on 2021-08-21 陈浩---start*/
			//LambdaQueryWrapper<FirefightersPost> queryWrapper = new LambdaQueryWrapper<FirefightersPost>();
			//.eq(FirefightersPost::getFirefightersId, firefightersDataDto.getFirefightersPost().getFirefightersId());
			@SuppressWarnings("rawtypes")
			QueryWrapper queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("firefighters_id", firefightersDataDto.getFirefightersPost().getFirefightersId());
			FirefightersPost firefightersPost = iFirefightersPostService.getOne(queryWrapper);

			/*bug3071 消防人员，专家领域选择子分类时概要信息中专家领域未显示 2021-10-09 chenzhao */
			if (firefightersDataDto.getFirefightersPost().getAreasExpertiseCode() != null){
				String areasExpertiseCode = firefightersDataDto.getFirefightersPost().getAreasExpertiseCode();
				DataDictionary zjly = dataDictionaryService.getByCode(areasExpertiseCode, "ZJLY");
				firefightersDataDto.getFirefightersPost().setAreasExpertise(zjly.getName());
			}
			/*bug3071 消防人员，专家领域选择子分类时概要信息中专家领域未显示 2021-10-09 chenzhao */
			if (firefightersPost == null) {
				iFirefightersPostService.save(firefightersDataDto.getFirefightersPost());
			} else {
				iFirefightersPostService.update(firefightersDataDto.getFirefightersPost(), queryWrapper);
			}
			
			FirefightersEducation firefightersEducation=	ifirefightersEducationService.getOne(queryWrapper);
			if(firefightersEducation==null) {
				ifirefightersEducationService.save(firefightersDataDto.getFirefightersEducation());
			}else {
				ifirefightersEducationService.update(firefightersDataDto.getFirefightersEducation(),queryWrapper);
			}
			
			FirefightersWorkexperience  firefightersWorkexperience =	ifirefightersWorkexperienceService.getOne(queryWrapper);
			if(firefightersWorkexperience==null) {
				ifirefightersWorkexperienceService.save(firefightersDataDto.getFirefightersWorkexperience());
			}else {
				ifirefightersWorkexperienceService.update(firefightersDataDto.getFirefightersWorkexperience(),queryWrapper);
			}
			/*---------修改bug:2179   解決崗位与学历可以重复添加导致的列表页展示消防人员信息呈现多条的情况  on 2021-08-21 陈浩---end*/
			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.DELETE)
	@ApiOperation(httpMethod = "DELETE", value = "根据消防人员id删除岗位和学历信息", notes = "根据 id删除")
	@Transactional
	public ResponseModel<Object> deleteById(@PathVariable Long id) {
		try {
			iFirefightersPostService
					.update(new UpdateWrapper<FirefightersPost>().eq("firefighters_id", id).set("is_delete", 1));
			ifirefightersWorkexperienceService.update(
					new UpdateWrapper<FirefightersWorkexperience>().eq("firefighters_id", id).set("is_delete", 1));
			ifirefightersEducationService
					.update(new UpdateWrapper<FirefightersEducation>().eq("firefighters_id", id).set("is_delete", 1));
			// 删除缓存
			redisUtils.del(RedisKey.EDUCATION_POST_EXPERIENCE_FIREFIGHTERS_ID + id);
			return ResponseHelper.buildResponse(null);
		} catch (Exception e) {

			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> updateByIdFirefightersPost(@RequestBody FirefightersDataDto firefightersDataDto) {
		try {
			FirefightersPost firefightersPost = firefightersDataDto.getFirefightersPost();
			/*bug3101 编辑页面专家领域选择子分类保存成功后，领域未修改 2021-10-15 chenzhao */
			if (firefightersDataDto.getFirefightersPost().getAreasExpertiseCode() != null){
				String areasExpertiseCode = firefightersDataDto.getFirefightersPost().getAreasExpertiseCode();
				DataDictionary zjly = dataDictionaryService.getByCode(areasExpertiseCode, "ZJLY");
				firefightersDataDto.getFirefightersPost().setAreasExpertise(zjly.getName());
			}
			/*bug3101 编辑页面专家领域选择子分类保存成功后，领域未修改 2021-10-15	 chenzhao */
			iFirefightersPostService.updateById(firefightersPost);
			ifirefightersWorkexperienceService.updateById(firefightersDataDto.getFirefightersWorkexperience());
			ifirefightersEducationService.updateById(firefightersDataDto.getFirefightersEducation());
			// 删除缓存
			redisUtils.del(RedisKey.EDUCATION_POST_EXPERIENCE_FIREFIGHTERS_ID + firefightersPost.getSequenceNbr());
			return ResponseHelper.buildResponse(null);
		} catch (Exception e) {

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

	/**
	 * 根据id查询
	 * 
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据消防员id查询", notes = "根据消防员id查询")
	public ResponseModel<Object> selectById(@PathVariable Long id) {
		@SuppressWarnings("rawtypes")
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("firefighters_id", id);
		FirefightersDataDto firefightersDataDto = new FirefightersDataDto(
				ifirefightersWorkexperienceService.getOne(queryWrapper),
				ifirefightersEducationService.getOne(queryWrapper), iFirefightersPostService.getOne(queryWrapper));
		return ResponseHelper.buildResponse(firefightersDataDto);
	}

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

		Page<FirefightersPost> pageBean;
		QueryWrapper<FirefightersPost> firefightersPostQueryWrapper = new QueryWrapper<>();
		Class<? extends FirefightersPost> aClass = firefightersPost.getClass();
		Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
			try {
				field.setAccessible(true);
				Object o = field.get(firefightersPost);
				if (o != null) {
					Class<?> type = field.getType();
					String name = NameUtils.camel2Underline(field.getName());
					if (type.equals(Integer.class)) {
						Integer fileValue = (Integer) field.get(firefightersPost);
						firefightersPostQueryWrapper.eq(name, fileValue);
					} else if (type.equals(Long.class)) {
						Long fileValue = (Long) field.get(firefightersPost);
						firefightersPostQueryWrapper.eq(name, fileValue);
					} else if (type.equals(String.class)) {
						String fileValue = (String) field.get(firefightersPost);
						firefightersPostQueryWrapper.eq(name, fileValue);
					} else {
						if (!name.equals(NameUtils.camel2Underline("serialVersionUID"))) {
							String fileValue = (String) field.get(firefightersPost);
							firefightersPostQueryWrapper.eq(name, fileValue);
						}
					}
				}
			} catch (Exception e) {
				throw new RuntimeException("系统异常");
			}
		});
		IPage<FirefightersPost> 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 = iFirefightersPostService.page(pageBean, firefightersPostQueryWrapper);
		return page;
	}
}
