package com.izouma.awesomeadmin.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.izouma.awesomeadmin.constant.AppConstant;
import com.izouma.awesomeadmin.dto.Page;
import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.dto.TreeNode;
import com.izouma.awesomeadmin.model.DepartInfo;
import com.izouma.awesomeadmin.service.DepartInfoService;
import com.izouma.awesomeadmin.service.PowerInfoService;
import com.izouma.awesomeadmin.service.SysMenuService;
import com.izouma.awesomeadmin.shiro.PhoneCodeToken;
import com.izouma.awesomeadmin.util.CookieUtil;
import com.izouma.awesomeadmin.util.ExportExcelUtil;
import com.izouma.awesomeadmin.util.MD5Util;
import org.activiti.engine.IdentityService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.izouma.awesomeadmin.model.UserInfo;
import com.izouma.awesomeadmin.service.UserInfoService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * user_info controller类
 * Tue Apr 17 10:32:49 CST 2018  Suo Chen Cheng
 */
@Controller
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private PowerInfoService powerInfoService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private DepartInfoService departInfoService;
    @Autowired
    private IdentityService identityService;

    /**
     * <p>获取全部记录。</p>
     */
    @RequiresAuthentication
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Result all(UserInfo record) {

        List<UserInfo> pp = userInfoService.getUserInfoList(record);
        return new Result(true, pp);
    }

    /**
     * <p>根据Id。</p>
     */
    @RequiresAuthentication
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public Result getUserInfo(@RequestParam(required = false, value = "id") String id) {
        if (StringUtils.isEmpty(id)) {
            try {
                Subject subject = SecurityUtils.getSubject();
                UserInfo userInfo = (UserInfo) subject.getPrincipal();
                if (userInfo != null) {
                    userInfo = userInfoService.getUserInfoById(userInfo.getId().toString());
                    if (userInfo != null) {
                        return new Result(true, userInfo);
                    }
                }
            } catch (Exception ignored) {

            }
        }

        UserInfo data = userInfoService.getUserInfoById(id);
        return new Result(true, data);
    }

    /**
     * <p>根据条件获取。</p>
     */
    @RequiresAuthentication
    @RequestMapping(value = "/getOne", method = RequestMethod.GET)
    @ResponseBody
    public Result getOne(UserInfo record) {

        UserInfo data = userInfoService.getUserInfo(record);
        return new Result(true, data);
    }

    /**
     * <p>分页查询。</p>
     */
    @RequiresAuthentication
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public Result page(Page page, UserInfo record) {

        Map<String, Object> result = new HashMap<>();

        List<UserInfo> pp = userInfoService.getUserInfoByPage(page, record);

        result.put(AppConstant.PAGE, page);
        result.put("pp", pp);
        return new Result(true, result);
    }

    /**
     * <p>保存。</p>
     */
    @RequiresAuthentication
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(UserInfo record) {

        boolean num = userInfoService.createUserInfo(record);
        if (num) {
            return new Result(true, record.getId());
        }
        return new Result(false, "保存异常");
    }

    /**
     * <p>更新信息。</p>
     */
    @RequiresAuthentication
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Result updateUserInfo(UserInfo record) {

        boolean num = userInfoService.updateUserInfo(record);
        if (num) {
            return new Result(true, "保存成功");
        }
        return new Result(false, "保存异常");
    }

    @RequiresAuthentication
    @RequestMapping(value = "/initPassword", method = RequestMethod.POST)
    @ResponseBody
    public Result initPassword(String id) {
        UserInfo record = new UserInfo();
        record.setId(Integer.valueOf(id));
        record.setPassword(MD5Util.getMD5("123456"));
        boolean num = userInfoService.changePassword(record);
        if (num) {
            return new Result(true, "保存成功");
        }
        return new Result(false, "保存异常");
    }

    @RequiresAuthentication
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    @ResponseBody
    public Result changePassword(String old, String newPassword) {

        try {
            Subject subject = SecurityUtils.getSubject();
            UserInfo userInfo = (UserInfo) subject.getPrincipal();
            if (userInfo != null) {
                userInfo = userInfoService.getUserInfoById(userInfo.getId().toString());
                if (userInfo != null) {
                    if (MD5Util.getMD5(old).equals(userInfo.getPassword())) {

                        UserInfo record = new UserInfo();
                        record.setId(userInfo.getId());
                        record.setPassword(MD5Util.getMD5(newPassword));
                        boolean num = userInfoService.changePassword(record);
                        if (num) {
                            return new Result(true, "修改密码成功");
                        }
                    } else {
                        return new Result(false, "原始密码不正确");
                    }
                }
            }
        } catch (Exception ignored) {

        }

        return new Result(false, "保存异常");
    }

    /**
     * <p>删除。</p>
     */
    @RequiresAuthentication
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteUserInfo(@RequestParam(required = true, value = "id") String id) {

        boolean num = userInfoService.deleteUserInfo(id);
        if (num) {
            return new Result(true, "删除成功");
        }
        return new Result(false, "删除异常");
    }

    @RequiresAuthentication
    @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
    @ResponseBody
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<UserInfo> userInfos = userInfoService.getUserInfoList(null);

        String sheetName = "用户信息";
        String titleName = "用户信息数据表";
        String fileName = "用户信息表";
        int columnNumber = 4;
        int[] columnWidth = {20, 20, 10, 20};
        String[] columnName = {"用户名", "昵称", "性别", "电话"};
        String[][] dataList = new String[userInfos.size()][4];

        for (int i = 0; i < userInfos.size(); i++) {
            dataList[i][0] = userInfos.get(i).getUsername();
            dataList[i][1] = userInfos.get(i).getNickname();
            dataList[i][2] = userInfos.get(i).getSex();
            dataList[i][3] = userInfos.get(i).getPhone();
        }

        ExportExcelUtil.ExportWithResponse(sheetName, titleName, fileName,
                columnNumber, columnWidth, columnName, dataList, response);
    }
}

