package com.yeejoin.amos.boot.module.common.biz.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.google.common.collect.Lists;
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.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.boot.biz.common.utils.Menu;
import com.yeejoin.amos.boot.biz.common.utils.MenuFrom;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.module.common.api.core.framework.PersonIdentify;
import com.yeejoin.amos.boot.module.common.api.dto.FireTeamCardDto;
import com.yeejoin.amos.boot.module.common.api.dto.FireTeamListDto;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgMenuDto;
import com.yeejoin.amos.boot.module.common.api.entity.FireTeam;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireTeamServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
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.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消防队伍
 *
 * @author tb
 * @date 2021-06-07
 */
@RestController
@Api(tags = "消防队伍Api")
@RequestMapping(value = "/fire-team")
public class FireTeamController extends BaseController {

    @Autowired
    FireTeamServiceImpl iFireTeamService;

    @Autowired
    OrgUsrServiceImpl iOrgUsrService;
    @Autowired
    OrgUsrMapper orgUsrMapper;
    @Value("${auth-key-fire-team:fire_team_info}")
    private String authKey;


    /**
     * 新增消防队伍
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增消防队伍", notes = "新增消防队伍")
    public ResponseModel<Object> saveFireTeam(HttpServletRequest request, @RequestBody FireTeam fireTeam) {
        return ResponseHelper.buildResponse(iFireTeamService.saveFireTeam(fireTeam));
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public ResponseModel<Object> deleteById(HttpServletRequest request, @PathVariable Long id) throws Exception {
        iFireTeamService.deleteById(id);
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 修改消防队伍
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改消防队伍", notes = "修改消防队伍")
    public ResponseModel<Object> updateByIdFireTeam(HttpServletRequest request, @RequestBody FireTeam fireTeam) {
        if (ValidationUtil.isEmpty(fireTeam.getSequenceNbr())) {
            throw new BadRequest("更新消防队伍必须传入主键");
        }
        // BUG 2842  由 BUG2217 2684 新增业务 需要统计消防队伍旗下所有消防队伍信息导致数据逻辑错误 返回错误提示 2021-09-10 by kongfm
        if (fireTeam.getSequenceNbr().equals(fireTeam.getParent())) {
            throw new BadRequest("消防队伍上级不可选为自己");
        }
        return ResponseHelper.buildResponse(iFireTeamService.saveFireTeam(fireTeam));
    }

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

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "新列表分页查询", notes = "新列表分页查询")
    public ResponseModel<IPage<FireTeamCardDto>> getFireTeamByPage(@RequestParam Integer pageNum,
                                                                   @RequestParam Integer pageSize,
                                                                   FireTeamListDto fireTeamList) {
        //条件分页
        if (pageNum == null || pageSize == null) {
            pageNum = 1;
            pageSize = 10;
        }
        if (pageSize == -1) {
            pageSize = Integer.MAX_VALUE;
        }
        Page<FireTeamCardDto> pageBean = new Page<>(pageNum, pageSize);
        IPage<FireTeamCardDto> page = iFireTeamService.listFireTeamByPage(pageBean, fireTeamList);
        return ResponseHelper.buildResponse(page);
    }


    /**
     * 消防队伍树查询
     *
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/listTree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "队伍树", notes = "队伍树")
    public ResponseModel<List<Menu>> listTree() throws Exception {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("is_delete", 0);
        List<Menu> menus = iFireTeamService.getTeamTree(columnMap);
        return ResponseHelper.buildResponse(menus);
    }

    /**
     * 查询所属单位下消防队伍树
     *
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{companyId}/listTree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "查询所属单位下消防队伍树", notes = "查询所属单位下消防队伍树")
    public ResponseModel<List<Menu>> listTreeByCompanyId(@PathVariable(value = "companyId") String companyId) throws Exception {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("is_delete", 0);
        columnMap.put("company", companyId);
        List<Menu> menus = iFireTeamService.getTeamTree(columnMap);
        return ResponseHelper.buildResponse(menus);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{companyId}/listTreetype", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "查询所属单位下消防队伍树", notes = "查询所属单位下消防队伍树")
    public ResponseModel<List<Menu>> getlistTreeByCompanyId(
        @PathVariable(value = "companyId") String companyId) throws Exception {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("is_delete", 0);
        OrgUsr our=iOrgUsrService.getById(companyId);
        if(our.getParentId()!=null){
          //判断是不是部门

            if(our.getBizOrgType().equals("COMPANY")){
                columnMap.put("company", companyId);
            }else{
               String id= orgUsrMapper.getParentList(companyId);
               columnMap.put("company", id);
            }
        }
        List<Menu> menus = iFireTeamService.getTeamTree(columnMap);
        return ResponseHelper.buildResponse(menus);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{companyId}/listTreetypeLikeCode", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "查询所属单位下消防队伍树", notes = "查询所属单位下消防队伍树")
    public ResponseModel<List<Menu>> getlistTreeByCompanyIdLike(
            @PathVariable(value = "companyId") String companyId) throws Exception {
        QueryWrapper<FireTeam> fireTeamQueryWrapper = new QueryWrapper<>();
        fireTeamQueryWrapper.eq("is_delete",0);
        OrgUsr our=iOrgUsrService.getById(companyId);
        //车辆装备需要判断
        if(our.getParentId()!=null){
            //判断是不是部门

            if(our.getBizOrgType().equals("COMPANY")){
                fireTeamQueryWrapper.likeRight("biz_org_code",our.getBizOrgCode());
            }else{
                String id= orgUsrMapper.getParentList(companyId);
                OrgUsr ourf=iOrgUsrService.getById(id);
                fireTeamQueryWrapper.likeRight("biz_org_code",ourf.getBizOrgCode());
            }
        }
        List<Menu> menus = iFireTeamService.getTeamTreeLikeCode(fireTeamQueryWrapper);
        return ResponseHelper.buildResponse(menus);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{companyId}/getBizCode", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取bizcode", notes = "获取bizcode")
    public ResponseModel<String> getBizCode(
            @PathVariable(value = "companyId") String companyId) throws Exception {

        OrgUsr our=iOrgUsrService.getById(companyId);
        if(our.getParentId()!=null){
            //判断是不是部门
            if(our.getBizOrgType().equals("COMPANY")){
                return ResponseHelper.buildResponse(our.getBizOrgCode());
            }else{
                String id= orgUsrMapper.getParentList(companyId);
                OrgUsr ourf=iOrgUsrService.getById(id);
                return ResponseHelper.buildResponse(ourf.getBizOrgCode());
            }
        }
        return ResponseHelper.buildResponse(our.getBizOrgCode());

    }


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

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

    /**
     * 查询机场单位-消防队伍树
     *
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/company/listTree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "查询机场单位-消防队伍树", notes = "查询机场单位-消防队伍树")
    public ResponseModel<List<MenuFrom>> listCompanyTree() throws Exception {
        List<MenuFrom> menus = iFireTeamService.getCompanyTeamTree();
        return ResponseHelper.buildResponse(menus);
    }

    /**
     * 查询消防队伍下的人员
     *
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/fighter", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "查询消防队伍下的人员", notes = "查询消防队伍下的人员")
    public ResponseModel<List<FirefightersDto>> listFighterByTeamId(@RequestParam("teamIds") String teamIds) {
        List<String> teamIdList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(teamIds)) {
            teamIdList = Lists.newArrayList(teamIds.split(","));
        }
        List<FirefightersDto> fighters = iFireTeamService.getFighterByTeamId(teamIdList);
        return ResponseHelper.buildResponse(fighters);
    }

    /**
     * 查询消防队伍下的人员
     *
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{teamIds}/company", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "查询消防队伍所属单位", notes = "查询消防队伍所属单位")
    public ResponseModel<FireTeam> listFighterCompany(@PathVariable(value = "teamIds") String teamIds) {
        FireTeam fireTeamBySequenceNbr = iFireTeamService.getFireTeamBySequenceNbr(Long.valueOf(teamIds));
        return ResponseHelper.buildResponse(fireTeamBySequenceNbr);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/firstAid", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "急救站", notes = "急救站")
    public Object getFirstAidForTypeCodeAndCompanyId(String code, String typeCode, Long companyId) {
        return ResponseHelper.buildResponse(iFireTeamService.getFirstAidForTypeCodeAndCompanyId(code, typeCode, companyId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/find/fireTeam/designated/department", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "消防队伍 中的 类型为【企（事）业单位专职消防救援队】队伍", notes = "消防队伍 中的 类型为【企（事）业单位专职消防救援队】队伍")
    public ResponseModel<List<Menu>> getFirstTeamToDesignatedDepartment() throws Exception {
        return ResponseHelper.buildResponse(iFireTeamService.getFirstTeamToDesignatedDepartment());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/find/departmentTree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = " 消防队伍中 消救部 下的  类型为【企（事）业单位专职消防救援队】的队伍", notes = " 消防队伍中 消救部下的  类型为【企（事）业单位专职消防救援队】的队伍")
    public ResponseModel<List<Menu>> getFirstTeamToDesignatedDepartment(@RequestParam String dicCode, @RequestParam String typeCode) throws Exception {
        return ResponseHelper.buildResponse(iFireTeamService.getFirstTeamToDesignatedDepartment(dicCode, typeCode));
    }

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

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/typeTree/XFJGLX", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据bizOrgCode的值获取对应的消防队伍树信息，含有队伍下统计数据", notes = "根据bizOrgCode的值获取对应的消防队伍树信息，含有队伍下统计数据")
    public ResponseModel<List<Menu>> getFireTeamType(@RequestParam(required = false) String bizOrgCode) throws Exception {
        List<Menu> list = iFireTeamService.getFireTeamTypeTree(bizOrgCode);
        return ResponseHelper.buildResponse(list);
    }


}