package com.ztmap.framework.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ztmap.common.utils.DateUtils;
import com.ztmap.common.utils.StringUtils;
import com.ztmap.common.utils.security.ShiroUtils;
import com.ztmap.common.utils.sql.SqlUtil;
import com.ztmap.framework.shiro.service.PasswordService;
import com.ztmap.framework.web.domain.AjaxResult;
import com.ztmap.framework.web.domain.AjaxResult.Type;
import com.ztmap.framework.web.file.service.FileService;
import com.ztmap.framework.web.page.PageDomain;
import com.ztmap.framework.web.page.TableDataInfo;
import com.ztmap.framework.web.page.TableSupport;
import com.ztmap.framework.web.service.TokenService;
import com.ztmap.project.system.config.service.IConfigService;
import com.ztmap.project.system.dept.service.IDeptService;
import com.ztmap.project.system.dict.service.IDictDataService;
import com.ztmap.project.system.role.service.IRoleService;
import com.ztmap.project.system.user.domain.LoginUser;
import com.ztmap.project.system.user.domain.User;
import com.ztmap.project.system.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * web层通用数据处理
 * 
 * @author ztmap
 */
public class BaseController
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    public IUserService userService;
    @Autowired
    public IRoleService roleService;
    @Autowired
    public IDeptService iDeptService;
    @Autowired
    public IDictDataService dictDataService;
    @Autowired
    public TokenService tokenService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    public PasswordService passwordService;
    @Autowired
    public FileService fileService;
    @Autowired
    public IConfigService configService;
    /**
     * 将前台传递过来的日期格式的字符串，自动转化为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.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage(Map<String,Object> params)
    {
        if (!StringUtils.isEmpty((String) params.get("pageNum"))&&!StringUtils.isEmpty((String) params.get("pageSize"))) {
            Integer pageNum = Integer.parseInt((String) params.get("pageNum"));
            Integer pageSize = Integer.parseInt((String) params.get("pageSize"));
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
            {
                PageHelper.startPage(pageNum, pageSize);
            }
        }
    }

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

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

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

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

    /**
     * 返回成功
     */
    public AjaxResult success()
    {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error()
    {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message)
    {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message)
    {
        return AjaxResult.error(message);
    }

    /**
     * 返回错误码消息
     */
    public AjaxResult error(Type type, String message)
    {
        return new AjaxResult(type, message);
    }

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

    public User getSysUser()
    {
        return ShiroUtils.getSysUser();
    }

    public User getUserByToken(){
        LoginUser loginUser = tokenService.getLoginUser(request);
        User user = userService.selectUserById(loginUser.getUser().getUserId());
        return user;
    }

    public void remove_file(String ids){
        int i = fileService.deleteBydataFile(ids);
    }

    public void setSysUser(User user)
    {
        ShiroUtils.setSysUser(user);
    }

    public Long getUserId()
    {
        return getSysUser().getUserId();
    }

    public String getLoginName()
    {
        return getSysUser().getLoginName();
    }

    public String getLastYear(int num){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, -1);
        Date y = c.getTime();
        return new SimpleDateFormat("yyyy").format(y);
    }

    public String getLastDate(int num){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, -1);
        Date y = c.getTime();
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(y);
    }

    public static List<String> getMonthTime(){
        List<String> ids = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            if (i<10) {
                ids.add("0"+i);
            }else {
                ids.add(String.valueOf(i));
            }
        }
        return ids;
    }
}
