package com.yeejoin.amos.boot.module.jcs.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.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.FirestationJacket;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireStationServiceImpl;
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.api.feign.CommonResponseUtil2;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.FirestationJacketServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.exception.instance.BadRequest;
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.Date;
import java.util.List;

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

	@Autowired
	FirestationJacketServiceImpl iFirestationJacketService;
    @Autowired
    FireStationServiceImpl fireStationServiceImpl;
    /**
     * 新增消防人员配装记录
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save/{firestationId}", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增消防人员配装记录", notes = "新增消防人员配装记录")
    @Transactional
    public ResponseModel<Object> saveFirestationJacket(@ApiParam(value = "消防队员ID", required = true) @PathVariable Long firestationId, @RequestBody List<EquipmentOnCarDto> equipmentOnCarDtos) {
        boolean flag = iFirestationJacketService.saveOrUpdateBatch(firestationId, 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 FirestationJacket firestationJacket) {
        boolean flag = iFirestationJacketService.update(type, firestationJacket);
        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<FirestationJacket> updateByIdFirestationJacket(HttpServletRequest request,
                                                                          @RequestBody FirestationJacket firestationJacket) {
        iFirestationJacketService.updateById(firestationJacket);
        return ResponseHelper.buildResponse(firestationJacket);
    }

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



    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/Firestation/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除微型消防站", notes = "根据sequenceNbr删除微型消防站")
    public ResponseModel deleteBySequenceNbr(HttpServletRequest request,
                                                      @PathVariable(value = "sequenceNbr") Long sequenceNbr) {

        QueryWrapper<FirestationJacket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("firefighters_id", sequenceNbr);
        queryWrapper.eq("is_delete", 0);
        FirestationJacket firestationJacket = iFirestationJacketService.getOne(queryWrapper);

        if(firestationJacket!=null){
            return CommonResponseUtil2.failure("微型消防站有配装装备，不能删除！");
        }

        return ResponseHelper.buildResponse(fireStationServiceImpl.updateisDelete(sequenceNbr));
    }




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

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

        return ResponseHelper.buildResponse(page);
    }

    /**
     * 分页查询设备列表（调用装备接口）
     */
    @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 iFirestationJacketService.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 iFirestationJacketService.getEquipByStockDetailId(stockDetailId);
    }
}
