package com.tofly.xrtygis.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.constant.ResponeStatus;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.xrtygis.commons.Constant;
import com.tofly.xrtygis.service.IBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;

import java.lang.reflect.ParameterizedType;
import java.util.Arrays;


/**
 * @ClassName: BaseController
 * @Description: 基础控制器
 * @Author Zev
 * @Date 2021/3/18
 * @Version 1.0.0
 */
@Slf4j
public class BaseController<T, V> {

    private IBaseService<T, V> iBaseService;

    /**
     * 初始化
     */
    public void init(IBaseService<T, V> iBaseService) {
        this.iBaseService = iBaseService;
    }


    /**
     * 分页查询
     *
     * @param page   分页对象
     * @param parDto 查询对象
     * @return 返回分页对象
     */
    public ResultRespone<Page<V>> getInfoPage(Page page, T parDto) {
        ResultRespone<Page<V>> rest = new ResultRespone<>();
        Class model = this.createModel();
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.setEntity(parDto);
//            wrapper.orderByDesc("CREATE_TIME");
            Page infoPageList = iBaseService.page(page, wrapper);

            // 转换前端显示对象
            infoPageList.setRecords(iBaseService.viewConversion(infoPageList.getRecords()));
            rest.setResult(infoPageList);

        } catch (Exception e) {
            log.error("分页查询信息异常:class = {},e = {}", model.getName(), e);
            rest.setCode(ResponeStatus.FAIL.getCode());
        }

        return rest;
    }

    /**
     * 新增对象
     *
     * @param parDto 对象信息
     * @return 是否新增成功
     */
    public ResultRespone<Object> save(T parDto) {
        ResultRespone<Object> rest = new ResultRespone<>();
        Class model = this.createModel();
        try {
            if (!iBaseService.save(parDto)) {
                log.error("新增基本信息对象失败:class = {},parDto = {}", model.getName(), parDto);
                rest.setCode(Constant.NEW_FAIL_CODE);
                rest.setMessage(Constant.NEW_FAIL);
            }
        } catch (Exception e) {
            log.error("新增基本信息对象异常:class = {},e = {}", model.getName(), e);
            rest.setCode(ResponeStatus.FAIL.getCode());
        }
        return rest;
    }

    /**
     * 修改信息
     *
     * @param parDto 修改对象
     * @return 是否修改成功
     */
    public ResultRespone<Object> updateById(T parDto) {
        ResultRespone<Object> rest = new ResultRespone<>();
        Class model = this.createModel();
        try {

            if (!iBaseService.updateById(parDto)) {
                log.error("修改基本信息对象失败:class = {},parDto = {}", model.getName(), parDto);
                rest.setMessage(Constant.UPDATE_FAIL);
                rest.setCode(Constant.UPDATE_FAIL_CODE);
            }

        } catch (Exception e) {
            log.error("修改基本信息异常:class = {},e = {}", model.getName(), e);
            rest.setCode(ResponeStatus.FAIL.getCode());
        }
        return rest;
    }

    /**
     * 通过id查询对象
     *
     * @param id id
     * @return Object
     */
    public ResultRespone<T> getById(Long id) {
        ResultRespone<T> rest = new  ResultRespone<>();
        Class model = this.createModel();
        try {
            T baseInfo = iBaseService.getById(id);
            if (null == baseInfo) {
                log.error("通过id查询信息失败:class = {},id = {}", model.getName(), id);
                rest.setMessage(Constant.DATA_NONENTITY);
                rest.setCode(Constant.DATA_NONENTITY_CODE);
            }

            rest.setResult(baseInfo);
        } catch (Exception e) {
            log.error("通过id查询信息异常:class = {},e = {}", model.getName(), e);
            rest.setCode(ResponeStatus.FAIL.getCode());
        }
        return rest;
    }


    /**
     * 通过id列表删除基本信息对象
     *
     * @param ids id串
     * @return 是否删除成功
     */
    public ResultRespone<Object> removeByIdList(String ids) {
        ResultRespone<Object> rest = new ResultRespone<>();
        Class model = this.createModel();
        try {
            if (!iBaseService.removeByIds(Arrays.asList(ids.split(Constant.CSV)))) {

                log.error("通过ID删除基本信息对象失败:class = {},ids = {}", model.getName(), ids);
                rest.setMessage(Constant.DELETE_FAIL);
                rest.setCode(Constant.DELETE_FAIL_CODE);
            }
        } catch (Exception e) {
            log.error("通过ID删除基本信息对象失败异常:class = {},e = {}", model.getName(), e);
            rest.setCode(ResponeStatus.FAIL.getCode());
        }
        return rest;
    }


//    /**
//     * 批量新增公示牌信息对象
//     *
//     * @param dtoList 新增公示牌信息对象列表
//     * @return Rest<Boolean>
//     */
//    @ApiOperation(value = "批量新增公示牌信息对象")
//    @PostMapping
//    public ResultRespone<Object> saveAll(@Valid @RequestBody ValidListDto<EDto> dtoList, BindingResult result) {
//        ResultRespone<Page<V>> rest = new ResultRespone<>();
//        // 数据校验
//        if (result.hasErrors()){
//            rest.setSuccess(false);
//            rest.setErrCode(CommonRest.MISSING_REQUIRED_PARAMETERS_CODE);
//            rest.setMessage(CommonRest.MISSING_REQUIRED_PARAMETERS);
//            rest.setData(dtoList.getValidation(result));
//            return rest;
//        }
//        try {
//            baseService.saveBatch(baseService.modelConversion(dtoList));
//
//        }catch (Exception e){
//            log.error("批量新增公示牌信息对象", e);
//            rest.setSuccess(false);
//            rest.setErrCode(CommonRest.QUERY_FAILD_CODE);
//            rest.setMessage(CommonRest.QUERY_FAILD);
//        }
//        // 对象转换
//
//        return;
//    }


    /**
     * 获取实列的类信息
     *
     * @return class
     */
    public Class createModel() {
        try {
            ParameterizedType ptype = (ParameterizedType) this.getClass().getGenericSuperclass();
            Class clazz = (Class<T>) ptype.getActualTypeArguments()[0];
            T o = (T) clazz.newInstance();
            return o.getClass();
        } catch (Exception e) {
            log.error("失败异常 方法={},e={}","获取实列的类信息",e);
        }
        return null;

    }

    /**
     * 校验封装返回
     * @param rest 返回对象
     * @param result 检验返回对象
     * @return null说明通过校验
     */
    public ResultRespone<Object> validRest(ResultRespone<Object> rest , BindingResult result){
        if(null==result){
            return null;
        }else {
            // 数据校验
            if (!result.hasErrors()) {
                return null;
            }else {
                rest.setCode(Constant.DATA_VALIDATION_CODE);
                rest.setMessage(Constant.DATA_VALIDATION);
                return rest;

            }
        }


    }
}
