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

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferCompanyDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.UserCar;
import com.yeejoin.amos.boot.module.jcs.api.mapper.UserCarMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireTeamServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferSimpleDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.PowerTransfer;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.PowerTransferServiceImpl;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;

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

/**
 * 力量调派
 *
 * @author tb
 * @date 2021-06-17
 */
@RestController
@Api(tags = "力量调派Api")
@RequestMapping(value = "/power-transfer")
public class PowerTransferController extends BaseController {

    @Autowired
    PowerTransferServiceImpl powerTransferService;
    @Autowired
    FireTeamServiceImpl fireTeamService;
    @Autowired
    EquipFeignClient docequipFeignClient;
    @Autowired
    UserCarMapper userCarMapper;

    /**
     * 新增力量调派
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增力量调派", notes = "新增力量调派")
    public boolean savePowerTransfer(@RequestBody PowerTransfer powerTransfer) {
        return powerTransferService.save(powerTransfer);
    }

    /**
     * 根据id删除
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean deleteById(@PathVariable Long id) {
        return powerTransferService.removeById(id);
    }


    /**
     * 修改力量调派
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改力量调派", notes = "修改力量调派")
    public boolean updateByIdPowerTransfer(@RequestBody PowerTransfer powerTransfer) {
        return powerTransferService.updateById(powerTransfer);
    }


    /**
     * 根据id查询
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public PowerTransfer selectById(@PathVariable Long id) {
        return powerTransferService.getById(id);
    }

    /**
     * 列表分页查询
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public IPage<PowerTransfer> listPage(String pageNum, String pageSize, PowerTransfer powerTransfer) {

        Page<PowerTransfer> pageBean;
        QueryWrapper<PowerTransfer> powerTransferQueryWrapper = new QueryWrapper<>();
        Class<? extends PowerTransfer> aClass = powerTransfer.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(powerTransfer);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(powerTransfer);
                        powerTransferQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(powerTransfer);
                        powerTransferQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(powerTransfer);
                        powerTransferQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(powerTransfer);
                        powerTransferQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        IPage<PowerTransfer> 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 = powerTransferService.page(pageBean, powerTransferQueryWrapper);
        return page;
    }

    /**
     * 根据警情id获取力量调派列表
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list/{alert_called_id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据警情id获取力量调派列表", notes = "根据警情id获取力量调派列表")
    public ResponseModel<PowerTransferSimpleDto> list(@PathVariable String alert_called_id) {
        PowerTransferSimpleDto powerTransferSimpleDto =
                powerTransferService.getPowerTransferList(Long.parseLong(alert_called_id));
        return ResponseHelper.buildResponse(powerTransferSimpleDto);
    }

    /**
     * 力量调派-任务派发
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "力量调派-任务派发", notes = "力量调派-任务派发")
    public ResponseModel<Boolean> createPowerTransfer(@RequestBody PowerTransferDto powerTransferDto) {

        List<PowerTransferCompanyDto> powerTransferCompanyDotList = powerTransferDto.getPowerTransferCompanyDotList();
        StringBuilder content = new StringBuilder();
        powerTransferCompanyDotList.forEach(e->{
            if (e.getPowerTransferCompanyResourcesDtoList()!=null){
                e.getPowerTransferCompanyResourcesDtoList().forEach(
                        c->
                        {
                            LambdaQueryWrapper<UserCar> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(UserCar::getCarId,c.getResourcesId());
                            wrapper.eq(BaseEntity::getIsDelete, false);
                            Integer count = userCarMapper.selectCount(wrapper);
                            if (count < 1){
                                content.append(c.getResourcesName()+":"+c.getResourcesNum()+" ");
                            }
                        }
                );
            }
        });
        if (!ValidationUtil.isEmpty(content) && content.length()>0){
            throw new BadRequest("车辆："+content+"未绑定人员,无法调派");
        }

        AgencyUserModel userInfo = getUserInfo();
        powerTransferDto.setTaskSenderId(Long.parseLong(userInfo.getUserId()));
        powerTransferDto.setTaskSenderName(userInfo.getRealName());
        String companyName = getSelectedOrgInfo().getCompany().getCompanyName();
        powerTransferDto.setCompanyName(companyName);
        boolean save = powerTransferService.createPowerTransfer(powerTransferDto);
        return ResponseHelper.buildResponse(save);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/power/tree")
    @ApiOperation(value = "力量调派资源树", notes = "力量调派资源树")
    public ResponseModel<Object> getPowerTree( @RequestParam String type) {
        return ResponseHelper.buildResponse(powerTransferService.getPowerTree(type));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/power/list")
    @ApiOperation(value = "力量出动列表", notes = "力量调派资源树")
    public ResponseModel<Object> getPowerTransferList(@ApiParam(value = "开始日期") @RequestParam(defaultValue = "") String beginDate,
                                                      @ApiParam(value = "结束日期") @RequestParam(defaultValue = "") String endDate) {
        return ResponseHelper.buildResponse(powerTransferService.getPowerTransferList(beginDate, endDate));
    }

}

