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

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.common.api.entity.*;
import com.yeejoin.amos.boot.module.common.api.enums.ExceptionEnum;
import com.yeejoin.amos.boot.module.common.api.mapper.DynamicFormInstanceMapper;
import com.yeejoin.amos.boot.module.common.api.service.IDynamicFormInstanceService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
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.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
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.core.framework.PersonIdentify;
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.dto.OrgMenuDto;
import com.yeejoin.amos.boot.module.common.api.dto.PeopleBasicInfoDto;
import com.yeejoin.amos.boot.module.common.api.dto.PeopleInfoDto;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireTeamServiceImpl;
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.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.entity.UserCar;
import com.yeejoin.amos.boot.module.jcs.api.service.IUserCarService;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.FirefightersJacketServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;

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
    FireTeamServiceImpl iFireTeamService;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    DataDictionaryServiceImpl dataDictionaryService;
    @Autowired
    DynamicFormInstanceMapper dynamicFormInstanceMapper;

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

    @Value("${auth-key-fire-fighters:fire_fighters_info}")
    private String authKey;
    @Value("${logic}")
    private Boolean logic;
    @Autowired
    IUserCarService userCarService;

    /**
     * 新增消防队员
     *
     * @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 {
            /*3184 消防人员，编辑页面岗位选择子分类保存成功后，概要中岗位未修改 chenzhao start 2021-10-19*/
            if (firefighters.getFirefighters().getJobTitleCode() != null && !firefighters.getFirefighters().getJobTitleCode().equals("")) {
                DataDictionary gwmc = dataDictionaryService.getByCode(firefighters.getFirefighters().getJobTitleCode(), "GWMC");
                firefighters.getFirefighters().setJobTitle(gwmc.getName());
            }
            /*3184 消防人员，编辑页面岗位选择子分类保存成功后，概要中岗位未修改 chenzhao end 2021-10-19*/
            iFirefightersService.saveFirefighters(firefighters);
            return ResponseHelper.buildResponse(firefighters);
        } catch (Exception e) {
            throw new BadRequest(ExceptionEnum.PARAMETER_TYPE_ERR.getEmsg());
        }

    }

    /**
     * 根据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) {
        //BUG 2761 判断人员删除时的逻辑 如果被选为队伍联系人则无法被删除 bykongfm
        List<FireTeam> fireTeam = iFireTeamService.list(new LambdaQueryWrapper<FireTeam>().eq(FireTeam::getIsDelete, false).eq(FireTeam::getContactUserId, id));
        if (fireTeam.size() > 0) {
            return ResponseHelper.buildResponse("-1");
        }
        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) {
            // BUG 2222 by litw start 2021年9月10日
            return ResponseHelper.buildResponse("-2");
        }
        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("0");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BadRequest("删除失败！");
        }
    }


    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/companyTreeByUserAndType", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据登录人及类型获取公司树", notes = "根据登录人及类型获取公司树")
    public ResponseModel<List<OrgMenuDto>> companyTreeByUserAndType() {
        // 获取登陆人角色
        ReginParams reginParams = getSelectedOrgInfo();
        // 权限赋值
        PermissionInterceptorContext.setDataAuthRule(authKey);
        List<OrgMenuDto> menus = iOrgUsrService.companyTreeByUserAndType(reginParams, OrgPersonEnum.公司.getKey(), null);
        return ResponseHelper.buildResponse(menus);
    }





    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getUserCar/{carId}/{teamId}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "POST", value = "获取绑定车辆", notes = "获取绑定车辆")
    @Transactional
    public void getUserCar(@PathVariable Long carId,@PathVariable String teamId) {
        try {
            UserCar userCar =userCarService.selectByCarId(carId);
            if(userCar!=null&&!userCar.getTeamId().equals(teamId)){
                userCarService.delete(userCar);
            }
        } catch (Exception e) {
            throw new BadRequest(ExceptionEnum.PARAMETER_TYPE_ERR.getEmsg());
        }

    }



    /**
     * 修改消防队员
     *
     * @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 {

            //判断此消防人员所属队伍是否变换，
            //获取用户已绑定车辆id、
            UserCar userCar = userCarService.selectByAmosUserId(Long.valueOf(firefighters.getFirefighters().getAmosUserId()));
            if(userCar!=null&&!userCar.getTeamId().equals(firefighters.getFirefighters().getFireTeamId()+"")){
                userCarService.delete(userCar);
            }

            Firefighters firefighter = firefighters.getFirefighters();
            // BUG2168 居住地户籍所在地为空判断 bykongfm
            if (firefighter.getResidenceDetails() != null) {
                FeignClientResult<RegionModel> region = Systemctl.regionClient.getRegion(Long.parseLong(firefighter.getResidenceDetails()));
                firefighter.setResidence(region.getResult().getRegionName());
            }
            /*3184 消防人员，编辑页面岗位选择子分类保存成功后，概要中岗位未修改 chenzhao start 2021-10-19*/
            if (firefighter.getJobTitleCode() != null) {
                DataDictionary gwmc = dataDictionaryService.getByCode(firefighter.getJobTitleCode(), "GWMC");
                firefighter.setJobTitle(gwmc.getName());
            }
            /*3184 消防人员，编辑页面岗位选择子分类保存成功后，概要中岗位未修改 chenzhao end 2021-10-19*/
            if (firefighter.getNativePlace() != null) {
                FeignClientResult<RegionModel> nativePlace = Systemctl.regionClient.getRegion(Long.parseLong(firefighter.getNativePlace()));
                firefighter.setNativePlaceValue(nativePlace.getResult().getRegionName());
            }
            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 BadRequest(ExceptionEnum.PARAMETER_TYPE_ERR.getEmsg());
        }
    }

    /**
     * 根据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);
        }
    }

    /**
     * 根据amos ID查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getFirefighterByAmosUserId", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据AmosId查询", notes = "根据AmosId查询")
    public ResponseModel<Object> selectByAmosId() {
        Firefighters firefighters = iFirefightersService.selectByAmosOrgId(Long.valueOf(getUserId()));
        return ResponseHelper.buildResponse(firefighters);
    }

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

    @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 {
                ReflectionUtils.makeAccessible(field);
                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 BadRequest(ExceptionEnum.PARAMETER_TYPE_ERR.getEmsg());
            }
        });
        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;
        }
        if(!ValidationUtil.isEmpty(firefighters.getJobTitle())) {
            firefighters.setJobTitles(Arrays.asList(firefighters.getJobTitle().split(",")));
        }

        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(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/job/getFirefightersJobTitleCount", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<Object> getFirefightersJobTitleCount(String bizOrgCode) throws Exception {
        List<Menu> menus = iFirefightersService.getFirefightersJobTitleCount(bizOrgCode);
        return ResponseHelper.buildResponse(menus);
    }
    /**
     * 岗位树，带统计
     *
     * @param
     * @return
     * @throws Exception
     */
    @PersonIdentify
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/all/fire/person", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "所有的消防人员", notes = "所有的消防人员")
    public ResponseModel<Object> getAllFirefightersPerson(String jobCode)throws Exception {
        String bizOrgCode = null;
        if(!logic){
            // 获取登陆人角色firefighters/all/fire/person
            ReginParams reginParams = getSelectedOrgInfo();
            bizOrgCode = reginParams.getPersonIdentity().getCompanyBizOrgCode();
        }
        return ResponseHelper.buildResponse(iFirefightersService.getAllFirefightersPerson(jobCode,bizOrgCode));
    }

    /**
     * 根据id查询人员
     * @param id
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/people/{id}", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "获取人员详情", notes = "获取人员详情")
    public ResponseModel<PeopleInfoDto> updatePeopleById(@RequestBody PeopleInfoDto firefighters, @PathVariable Long id) {
        try {
            if ("1601".equals(firefighters.getFirefighters().getPeopleType())){
                QueryWrapper<DynamicFormInstance> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("group_code", OrgPersonEnum.人员.getCode());
                queryWrapper.eq("field_code", "peopleType");
                queryWrapper.eq("instance_id", id);
                DynamicFormInstance instance = dynamicFormInstanceMapper.selectOne(queryWrapper);
                instance.setFieldValue(firefighters.getFirefighters().getPeopleType());
                instance.setFieldValueLabel("驻站消防员");
                dynamicFormInstanceMapper.updateById(instance);

                PeopleBasicInfoDto peopleBasicInfoDto = firefighters.getFirefighters();
                Firefighters firefighter = new Firefighters();
                BeanUtils.copyProperties(peopleBasicInfoDto, firefighter);
                Firefighters fire = iFirefightersService.getFirefightersByUserId(peopleBasicInfoDto.getSequenceNbr());
                if (!ObjectUtils.isEmpty(fire)) {
                    //判断此消防人员所属队伍是否变换，
                    //获取用户已绑定车辆id、
                    if(!ValidationUtil.isEmpty(firefighters.getFirefighters().getAmosUserId())) {
                        UserCar userCar = userCarService.selectByAmosUserId(Long.valueOf(firefighters.getFirefighters().getAmosUserId()));
                        if(userCar!=null&&!userCar.getTeamId().equals(firefighters.getFirefighters().getFireTeamId()+"")){
                            userCarService.delete(userCar);
                        }
                    }

                    firefighter.setSequenceNbr(fire.getSequenceNbr());
                    firefighter.setOrgUsrId(peopleBasicInfoDto.getSequenceNbr());
                    firefighter.setEmployeeNumber(peopleBasicInfoDto.getPersonNumber());
                    firefighter.setMobilePhone(peopleBasicInfoDto.getTelephone());
                    firefighter.setCertificateNumber(peopleBasicInfoDto.getCertificatesNumber());
                    // BUG2168 居住地户籍所在地为空判断 bykongfm
                    if (!ObjectUtils.isEmpty(firefighter.getResidenceDetailsCode())) {
                        FeignClientResult<RegionModel> region = Systemctl.regionClient.getRegion(Long.parseLong(firefighter.getResidenceDetailsCode()));
                        firefighter.setResidence(region.getResult().getRegionName());
                    }

                    /*3184 消防人员，编辑页面岗位选择子分类保存成功后，概要中岗位未修改 chenzhao end 2021-10-19*/
                    if (!ObjectUtils.isEmpty(firefighter.getNativePlaceCode())) {
                        FeignClientResult<RegionModel> nativePlace = Systemctl.regionClient.getRegion(Long.parseLong(firefighter.getNativePlaceCode()));
                        firefighter.setNativePlaceValue(nativePlace.getResult().getRegionName());
                    }
                    if (ObjectUtils.isEmpty(firefighter.getCompany())) {
                        firefighter.setCompany(fire.getCompany());
                        firefighter.setCompanyCode(fire.getCompanyCode());
                        firefighter.setCompanyName(fire.getCompanyName());
                    }
                    if (ObjectUtils.isEmpty(firefighter.getBizOrgCode())) {
                        firefighter.setBizOrgCode(fire.getBizOrgCode());
                        firefighter.setBizOrgName(fire.getBizOrgName());
                    }
                    iFirefightersService.updateById(firefighter);
                    ifirefightersContactsService.updateById(firefighters.getFirefightersContacts());


                    // 删除缓存
                    redisUtils.del(RedisKey.FIREFIGHTERS_ID + firefighter.getSequenceNbr(),
                            RedisKey.FIREFIGHTERS_LIST_ID + firefighter.getSequenceNbr());
                } else {
                    // 修改时改为消防人员
                    firefighters.getFirefighters().setOrgUsrId(firefighters.getFirefighters().getSequenceNbr());
                    iFirefightersService.saveFirefightersByUser(firefighters);
                }
            }
            return ResponseHelper.buildResponse(iFirefightersService.updatePeopleById(firefighters, id));
        } catch (Exception e) {
            throw new BadRequest(ExceptionEnum.PARAMETER_TYPE_ERR.getEmsg());
        }
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/get/personByCodes")
    @ApiOperation(httpMethod = "GET", value = "根据code查性别", notes = "根据code查性别")
    public ResponseModel<Map<String, String>> getPersonByCodes(@RequestParam(value = "list", required = true) List<String> list) {
        return ResponseHelper.buildResponse(iFirefightersService.getPersonByCodes(list));
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/get/persons")
    @ApiOperation(httpMethod = "GET", value = "根据当前登陆用户获取换流站驻站消防队专职消防队消防人员", notes = "根据当前登陆用户获取换流站驻站消防队专职消防队消防人员")
    public ResponseModel<JSONObject> getPersons() {
        ReginParams reginParam = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if(null != reginParam) {
            String bizOrgCode = reginParam.getPersonIdentity().getBizOrgCode();
            List<Map<String,Object>> list = new ArrayList<>();
            Map<String,Object> bizOrgCodeAndBizOrgName = iFirefightersService.getCompanyName(bizOrgCode);

            QueryWrapper<Firefighters> firefightersQueryWrapper1 = new QueryWrapper<>();
            firefightersQueryWrapper1.like("biz_org_code", bizOrgCodeAndBizOrgName.get("bizOrgCode"));
            firefightersQueryWrapper1.eq("people_type", "1601");
            firefightersQueryWrapper1.eq("is_delete", "0");
            List<Firefighters> firefighters = iFirefightersService.getBaseMapper().selectList(firefightersQueryWrapper1);
            firefighters.stream().forEach(e -> {
                Map<String, Object> map = new HashMap<>();
                map.put("name", e.getName());
                map.put("jobTitle", e.getJobTitle());
                map.put("bizOrgName", bizOrgCodeAndBizOrgName.get("bizOrgName"));
                map.put("bizOrgCode", bizOrgCodeAndBizOrgName.get("bizOrgCode"));
                map.put("amosUserId", e.getOrgUsrId());
                map.put("personnelPhotos", e.getPersonnelPhotos());
                list.add(map);
            });

            JSONObject object = new JSONObject();
            object.put("persons",list);
            return ResponseHelper.buildResponse(object);
        }
        return ResponseHelper.buildResponse(null);
    }

}
