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

import com.alibaba.fastjson.JSONObject;
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.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.ESAlertCalledDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.ESAlertCalledRequestDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.AlertCalledServiceImpl;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.ESAlertCalledService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
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 java.lang.reflect.Field;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * 警情接警填报记录
 *
 * @author litw
 * @date 2021-08-03
 */
@RestController
@Api(tags = "警情接警填报记录Api")
@RequestMapping(value = "/tzs/alert-called")
public class AlertCalledController extends BaseController {

	@Autowired
	RedisUtils redisUtils;
	@Autowired
	AlertCalledServiceImpl iAlertCalledService;
	@Autowired
	private ESAlertCalledService eSAlertCalledService;

    /**
     * 新增警情接警填报记录
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增警情接警填报记录", notes = "新增警情接警填报记录")
	public ResponseModel<AlertCalled> save(@RequestBody AlertCalledObjsDto alertCalledObjsDto) {
		if (ValidationUtil.isEmpty(alertCalledObjsDto)
				|| ValidationUtil.isEmpty(alertCalledObjsDto.getAlertCalled())){
			throw new BadRequest("参数校验失败.");
		}
		ReginParams reginParams =
				JSONObject.parseObject(null != redisUtils.get(buildKey(getToken())) ?
						redisUtils.get(buildKey(getToken())).toString() : null, ReginParams.class);
		//获取当前登录人公司
		Integer code= reginParams.getCompany().getCompanyOrgCode();
		AlertCalled alertCalled =  alertCalledObjsDto.getAlertCalled();
		alertCalled.setOrgCode(String.valueOf(code));
		alertCalledObjsDto.setAlertCalled(alertCalled);
		alertCalledObjsDto =iAlertCalledService.createAlertCalled(alertCalledObjsDto);
		return ResponseHelper.buildResponse(alertCalledObjsDto.getAlertCalled());
	}


	/**
	 *
	 * <pre>
	 * 相似警情分页查询
	 * </pre>
	 *
	 * @param
	 * @param current
	 * @param size
	 * @return
	 * @throws Exception
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(value = "相似警情分页查询")
	@PostMapping(value = "/page/similar")
	public ResponseModel<Page<ESAlertCalledDto>> pageBySimilar(
			@RequestBody ESAlertCalledRequestDto alertCalledVo,
			@RequestParam(value = "current") int current,
			@RequestParam(value = "size") int size) throws Exception {
		return ResponseHelper.buildResponse(eSAlertCalledService.queryByKeys(alertCalledVo, current, size));
	}


    /**
     * 根据id查询
     *
	 * @param id  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{id}")
	@ApiOperation(httpMethod = "GET",value = "根据id查询单个警情接警填报记录",  notes = "根据id查询单个警情接警填报记录")
	public ResponseModel<Object> selectOne(@PathVariable Long id) {
		return ResponseHelper.buildResponse(iAlertCalledService.selectAlertCalledById(id));
	}

	/**
     * 列表分页查询
     *
     * @param pageNum 当前页
     * @param pageSize 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/list")
	@ApiOperation(httpMethod = "GET",value = "警情接警填报记录分页查询",  notes = "警情接警填报记录分页查询")
	public ResponseModel<IPage<AlertCalled>> queryForPage(String pageNum, String pageSize,String sort, AlertCalled alertCalled)  {
		Page<AlertCalled> pageBean;
		IPage<AlertCalled> page;
		QueryWrapper<AlertCalled> alertCalledQueryWrapper = new QueryWrapper<>();

		setQueryWrapper(alertCalledQueryWrapper, alertCalled,sort);

		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 = iAlertCalledService.page(pageBean, alertCalledQueryWrapper);
		return ResponseHelper.buildResponse(page);
	}

	private QueryWrapper<AlertCalled> setQueryWrapper(QueryWrapper<AlertCalled> queryWrapper, AlertCalled alertCalled,String sort){
		Class<? extends AlertCalled> aClass = alertCalled.getClass();
		queryWrapper.eq("is_delete", 0);

		if(sort!=null) {
//			String[] date=  sort.split(",");
//			if(date[1].equals("ascend")) {
//				queryWrapper.orderByAsc(RedisKey.humpToLine(date[0]));
//			}else {
//				queryWrapper.orderByDesc(RedisKey.humpToLine(date[0]));
//			}
		}else {
			queryWrapper.orderByDesc("call_time");
		}

		if (alertCalled.getCallTimeStart() != null && alertCalled.getCallTimeEnd() != null) {
			queryWrapper.between("call_time", alertCalled.getCallTimeStart(), alertCalled.getCallTimeEnd());
		}
		if (alertCalled.getIsFatherAlert()) { // 0：接警；1：处警
			queryWrapper.isNull("father_alert");
		}

		Stream<Field> fieldStream = Arrays.stream(aClass.getDeclaredFields()).filter(field -> {
			String name = NameUtils.camel2Underline(field.getName());
			return !("IS_FATHER_ALERT".equals(name));
		});
		fieldStream.forEach(field -> {
			try {
				field.setAccessible(true);
				Object o = field.get(alertCalled);
				if (o != null && !"serialVersionUID".equals(field.getName())) {
					Class<?> type = field.getType();
					String name = NameUtils.camel2Underline(field.getName());
					if (type.equals(Integer.class)) {
						Integer fileValue = (Integer) field.get(alertCalled);
						queryWrapper.eq(name, fileValue);
					} else if (type.equals(String.class)) {
						String fileValue = (String) field.get(alertCalled);
						queryWrapper.eq(name, fileValue);
					} else if (type.equals(Boolean.class)) {
						Boolean fileValue = (Boolean) field.get(alertCalled);
						queryWrapper.eq(name, fileValue);
					}else if (type.equals(Long.class) || "long".equals(type.toString())) {
						Long fileValue = (Long) field.get(alertCalled);
						queryWrapper.eq(name, fileValue);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("系统异常");
			}
		});
		return queryWrapper;
	}
}
