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

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
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.CommonUtil;
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.alibaba.fastjson.JSON;
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.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.FormValue;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ESAlertCalledDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ESAlertCalledRequestDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertCalledServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.AlertFormValueServiceImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.ESAlertCalledService;

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

/**
 * 警情接警记录
 *
 * @author tb
 * @date 2021-06-17
 */
@RestController
@Api(tags = "警情接警记录Api")
@RequestMapping(value = "/alert-called")
public class AlertCalledController extends BaseController {

    @Autowired
    AlertCalledServiceImpl iAlertCalledService;
    @Autowired
    AlertFormValueServiceImpl iAlertFormValueService;
    @Autowired
    private ESAlertCalledService eSAlertCalledService;
    @Autowired
    RedisUtils redisUtils;
    @Value("${redis.cache.failure.time}")
    private long time;
    /**
     * 新增警情接警记录
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增警情接警记录", notes = "新增警情接警记录")
    @Transactional
    public ResponseModel<AlertCalled> saveAlertCalled(@RequestBody AlertCalledObjsDto alertCalledObjsDto) throws Exception{

    	 if (ValidationUtil.isEmpty(alertCalledObjsDto)
                 || ValidationUtil.isEmpty(alertCalledObjsDto.getAlertCalled()))
             throw new BadRequest("参数校验失败.");
    	 ReginParams reginParams =
 				JSONObject.parseObject(null != redisUtils.get(getToken()) ?
 						redisUtils.get(getToken()).toString() : null, ReginParams.class);
    		//获取当前登录人公司
    	String name= reginParams.getCompany().getCompanyName();
    	AlertCalled alertCalled =  alertCalledObjsDto.getAlertCalled();
    	alertCalled.setCompanyName(name);
    	alertCalledObjsDto.setAlertCalled(alertCalled);
    	alertCalledObjsDto =iAlertCalledService.createAlertCalled(alertCalledObjsDto);
    	 return ResponseHelper.buildResponse(alertCalledObjsDto.getAlertCalled());
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean deleteById(@PathVariable Long id) {
        return iAlertCalledService.removeById(id);
    }

    /**
     * 修改警情接警记录
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/updateById")
    @ApiOperation(httpMethod = "PUT", value = "修改警情接警记录", notes = "修改警情接警记录")
    public boolean updateByIdAlertCalled(@RequestBody AlertCalled alertCalled) {
        return iAlertCalledService.updateById(alertCalled);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<Object> selectById(@PathVariable Long id) {

     return ResponseHelper.buildResponse(iAlertCalledService.selectAlertCalledById(id));

    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/list")
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<AlertCalled>> listPage(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);
    }

    /**
     *
     * <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));
    }

    /**
     *
     * <pre>
     * 初始化ES
     * </pre>
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "初始化ES")
    @PutMapping(value = "/es/init")
    public ResponseModel<Boolean> initEs() throws Exception {
        return ResponseHelper.buildResponse(eSAlertCalledService.initEs());
    }

    /**
     * 列表无分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getList")
    @ApiOperation(httpMethod = "GET", value = "列表无分页查询", notes = "列表无分页查询")
    public ResponseModel<List<AlertCalled>> list(AlertCalled alertCalled) {
        QueryWrapper<AlertCalled> alertCalledQueryWrapper = new QueryWrapper<>();
        setQueryWrapper(alertCalledQueryWrapper, alertCalled,null);
        List<AlertCalled> list = iAlertCalledService.list(alertCalledQueryWrapper);
        return ResponseHelper.buildResponse(list);
    }

    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");
        }
        if (!ValidationUtil.isEmpty(alertCalled.getAlertSourceCodeStr())){
            String[] arr = alertCalled.getAlertSourceCodeStr().split(",");
            List<String> collect = Arrays.stream(arr).collect(Collectors.toList());
            queryWrapper.in("alert_source_code", collect);
        }
        Stream<Field> fieldStream = Arrays.stream(aClass.getDeclaredFields()).filter(field -> {
            String name = NameUtils.camel2Underline(field.getName());
            return !("IS_FATHER_ALERT".equals(name) || "ALERT_SOURCE_CODE_STR".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;
    }

    /**
     * 查询指定日期内警情列表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/dateRange/list")
    @ApiOperation(httpMethod = "GET", value = "查询指定日期内警情列表", notes = "查询指定日期内警情列表")
    public ResponseModel<Map<String, Object>> listByDateRange(@RequestParam(value = "beginDate", required = false) String beginDate,
                                                                    @RequestParam("endDate") String endDate) {
        return ResponseHelper.buildResponse(iAlertCalledService.getAlertInfoList(beginDate, endDate));
    }
}