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

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

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.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.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.controller.BaseController;
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.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.entity.FireTeam;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireTeamServiceImpl;

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

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

    @Autowired
    FireTeamServiceImpl iFireTeamService;

    /**
     * 新增消防队伍
     *
     * @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);
    }

    /**
     * 列表分页查询
     *
     * @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));
    }
}