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

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

import javax.servlet.http.HttpServletRequest;

import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.module.common.api.dto.FirefightersDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
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.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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.Menu;
import com.yeejoin.amos.boot.biz.common.utils.MenuFrom;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
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.entity.FireTeam;
import com.yeejoin.amos.boot.module.jcs.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) {
        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);
    }
}