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

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.entity.DataDictionary;
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.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.*;
import com.yeejoin.amos.boot.module.common.biz.service.impl.*;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.FireTeamServiceImpl;
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;
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.*;
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 javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 消防队员
 *
 * @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;
    @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 {
            /*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 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) {
        //BUG 2761 判断人员删除时的逻辑 如果被选为队伍联系人则无法被删除 bykongfm
        List 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 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();
            // 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 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);
        }
    }

    /**
     * 根据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 {
                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);
    }
    /**
     * 岗位树，带统计
     *
     * @param
     * @return
     * @throws Exception
     */
    @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 {
        return ResponseHelper.buildResponse(iFirefightersService.getAllFirefightersPerson(jobCode));
    }
}
