package com.prolog.upcloud.base.wh.operate.controller.common;

import com.github.pagehelper.PageHelper;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.upcloud.base.wh.operate.core.PageDomain;
import com.prolog.upcloud.base.wh.operate.core.TableSupport;
import com.prolog.upcloud.base.wh.operate.utils.DateUtils;
import com.prolog.upcloud.base.wh.operate.utils.ServletUtils;
import com.prolog.upcloud.base.wh.operate.utils.SqlUtil;
import com.prolog.upcloud.base.wh.operate.utils.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;

/**
 * web层通用数据处理
 *
 * @author wujunjie
 */
public class BaseController {

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNull(pageNum)) {
            pageNum = 1;
        }
        if (StringUtils.isNull(pageSize)) {
            pageSize = 10;
        }
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        PageHelper.startPage(pageNum, pageSize, orderBy);
    }

    /**
     * 设置请求分页数据
     */
    protected <T> Page<T> emptyPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNull(pageNum)) {
            pageNum = 1;
        }
        if (StringUtils.isNull(pageSize)) {
            pageSize = 10;
        }
        return (Page<T>) PageUtils.getEmptyPage(pageNum, pageSize);
    }

    /**
     * 设置请求排序数据
     */
    protected void startOrderBy() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.orderBy(orderBy);
        }
    }

    /**
     * 获取request
     */
    public HttpServletRequest getRequest() {
        return ServletUtils.getRequest();
    }

    /**
     * 获取response
     */
    public HttpServletResponse getResponse() {
        return ServletUtils.getResponse();
    }

    /**
     * 获取session
     */
    public HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 响应请求分页数据
     */
    protected <T> RestMessage<Page<T>> getPageTable(List<T> list) {
        return RestMessage.querySuccess(PageUtils.getPage(list));
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected RestMessage toAjax(int rows) {
        return rows > 0 ? success() : error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected RestMessage toAjax(boolean result) {
        return result ? success() : error();
    }

    /**
     * 返回成功
     */
    public RestMessage<Object> success() {
        return RestMessage.doSuccess(null);
    }

    /**
     * 返回失败消息
     */
    public RestMessage error() {
        return RestMessage.doError("操作失败");
    }

    /**
     * 返回成功消息
     */
    public RestMessage success(String message) {
        return RestMessage.newInstance(true, "操作成功");
    }

    /**
     * 返回成功消息
     */
    public <T> RestMessage<T> success(T data) {
        return RestMessage.newInstance(true, "操作成功", data);
    }


    /**
     * 返回失败消息
     */
    public RestMessage<Object> error(String message) {
        return RestMessage.error(message);
    }


    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StringUtils.format("redirect:{}", url);
    }

    public RestMessage doError(BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder errBuilder = new StringBuilder();
        fieldErrors.stream().findFirst().ifPresent(fieldError -> errBuilder.append("参数").append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(";"));
        return RestMessage.doError(errBuilder.toString());
    }
}
