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

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

import javax.servlet.http.HttpServletRequest;

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ReflectionUtils;
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.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
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.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.module.common.api.entity.FirefightersJacket;
import com.yeejoin.amos.boot.module.jcs.api.dto.EquipSpecificDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.EquipmentOnCarDto;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.FirefightersJacketServiceImpl;

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

/**
 * 消防人员配装记录
 *
 * @author tb
 * @date 2021-06-07
 */
@RestController
@Api(tags = "消防人员配装记录Api")
@RequestMapping(value = "/firefighters-jacket")
public class FirefightersJacketController extends BaseController {

	@Autowired
	FirefightersJacketServiceImpl iFirefightersJacketService;

    /**
     * 新增消防人员配装记录
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save/{firefightersId}", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增消防人员配装记录", notes = "新增消防人员配装记录")
    @Transactional
    public ResponseModel<Object> saveFirefightersJacket(@ApiParam(value = "消防队员ID", required = true) @PathVariable Long firefightersId, @RequestBody List<EquipmentOnCarDto> equipmentOnCarDtos) {
        boolean flag = iFirefightersJacketService.saveOrUpdateBatch(firefightersId, equipmentOnCarDtos);
        if (!flag) {
            throw new BadRequest("保存失败.");
        }
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 删除数据(退装|回库)
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{type}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "删除数据", notes = "删除数据")
    public ResponseModel<Object> deleteById(@PathVariable String type, @RequestBody FirefightersJacket firefightersJacket) {
        boolean flag = iFirefightersJacketService.update(type, firefightersJacket);
        if (!flag) {
            throw new BadRequest("删除失败.");
        }
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 修改消防人员配装记录
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改消防人员配装记录", notes = "修改消防人员配装记录")
    public ResponseModel<FirefightersJacket> updateByIdFirefightersJacket(HttpServletRequest request,
                                                                          @RequestBody FirefightersJacket firefightersJacket) {
        iFirefightersJacketService.updateById(firefightersJacket);
        return ResponseHelper.buildResponse(firefightersJacket);
    }

    /**
     * 根据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<FirefightersJacket> selectById(HttpServletRequest request, @PathVariable Long id) {
        QueryWrapper<FirefightersJacket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("firefighters_id", id);
        FirefightersJacket firefightersJacket = iFirefightersJacketService.getOne(queryWrapper);
        return ResponseHelper.buildResponse(firefightersJacket);
    }

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

        Page<FirefightersJacket> pageBean;
        QueryWrapper<FirefightersJacket> firefightersJacketQueryWrapper = new QueryWrapper<>();
        firefightersJacketQueryWrapper.eq("is_delete", 0);
        Class<? extends FirefightersJacket> aClass = firefightersJacket.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                ReflectionUtils.makeAccessible(field);
                Object o = field.get(firefightersJacket);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(firefightersJacket);
                        firefightersJacketQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(firefightersJacket);
                        firefightersJacketQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        if("EQUIPMENT_DETAIL_NAME".equals(name)){
                            String fileValue = (String) field.get(firefightersJacket);
                            firefightersJacketQueryWrapper.like(name, fileValue);
                        }else {
                            String fileValue = (String) field.get(firefightersJacket);
                            firefightersJacketQueryWrapper.eq(name, fileValue);
                        }
                    } else if (type.equals(Date.class)) {
                        Date fileValue = (Date) field.get(firefightersJacket);
                        firefightersJacketQueryWrapper.eq(name, fileValue);
                    } else {
                    	if(!name.equals(NameUtils.camel2Underline("serialVersionUID"))) {
                        String fileValue = (String) field.get(firefightersJacket);
                        firefightersJacketQueryWrapper.eq(name, fileValue);
                    }
                    	}
                }
            } catch (Exception e) {
                throw new BadRequest("系统异常");
            }
        });
        IPage<FirefightersJacket> 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 = iFirefightersJacketService.page(pageBean, firefightersJacketQueryWrapper);

        return ResponseHelper.buildResponse(page);
    }

    /**
     * 分页查询设备数量（调用装备接口）
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "人员装备数量")
    @RequestMapping(value = "/person-equip-count", method = RequestMethod.GET)
    public ResponseModel<List<Map<String, Object>>> getPersonEquipCount() {
        return ResponseHelper.buildResponse(iFirefightersJacketService.getPersonEquipCount());
    }

    /**
     * 分页查询设备列表（调用装备接口）
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "人员装备列表")
    @RequestMapping(value = "/airEquipSpecificPage", method = RequestMethod.GET)
    public ResponseModel<Page<Object>> getAirEquipSpecificPage(int current, int size,
                                                                          EquipSpecificDto equipSpecificDto) throws Exception {
        return iFirefightersJacketService.getAirEquipSpecificPage(equipSpecificDto, current, size);
    }

    /**
     * 查询设备详情（调用装备接口）
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "人员装备详情")
    @RequestMapping(value = "/getEquipByStockDetailId/{stockDetailId}", method = RequestMethod.GET)
    public ResponseModel<Object> getEquipByStockDetailId(@PathVariable Long stockDetailId) throws Exception {
        return iFirefightersJacketService.getEquipByStockDetailId(stockDetailId);
    }
}
