package com.fjs.scenic.controller.user;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.fjs.scenic.entity.user.UserStatistical;
import com.fjs.scenic.service.user.StatisticalPermissionsService;
import com.fjs.scenic.service.user.UserStatisticalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.fjs.scenic.entity.user.User;
import com.fjs.scenic.service.user.UserService;
import com.fjs.scenic.utils.ReturnResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * This class is used for ...
 *
 * @author lfj
 * @version 1.0
 * @CreateDate ${date} ${time}
 */
@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StatisticalPermissionsService statisticalPermissionsService;
    @Autowired
    private UserStatisticalService userStatisticalService;

    @GetMapping("index")
    public ModelAndView sceniclist(HttpSession session) {
        return new ModelAndView("/user/user");
    }

    /**
     * @param record      条件
     * @param currentPage 页码
     * @param pageSize    每页显示数量
     * @return
     * @throws Exception
     */
    @PostMapping("page")
    public ReturnResult page(User record, int currentPage, int pageSize,
                             @RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime) throws Exception {
        currentPage = (currentPage == 0) ? 1 : currentPage;
        pageSize = (pageSize == 0) ? 1 : pageSize;
        PageHelper.startPage(currentPage, pageSize);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = "";

        //根据会员名模糊查询
        if (record.getNickName() != "" && record.getNickName() != null) {
            str = " nick_name like '%" + record.getNickName() + "%'";
        } else {
            //避免前端缓存 传值为 ""||null
            record.setNickName(null);
        }

        //根据手机号模糊查询
        if (record.getPhone() != "" && record.getPhone() != null) {

            if (!"".equals(str)) {
                str += " and ";
            }

            str += " phone like '%" + record.getPhone() + "%'";
        } else {
            //避免前端缓存 传值为 ""||null
            record.setPhone(null);
        }

        List<User> userList = null;
        //根据时间区间模糊查询
        if ((startTime != null && !"".equals(startTime)) || (endTime != null && !"".equals(endTime))) {

            //开始时间为空 默认为一个月以前 -- 结束时间为空默认当前时间
            Calendar c = Calendar.getInstance();
            if (startTime == null || "".equals(startTime)) {
                c.setTime(df.parse(endTime));
                c.add(Calendar.MONTH, -1);
                Date mouthLater = c.getTime();
                startTime = df.format(mouthLater);
            }
            if (endTime == null || "".equals(endTime)) {
                endTime = df.format(new Date());
            }

            startTime = df.format(df.parse(startTime));
            endTime = df.format(df.parse(endTime));

            if (!"".equals(str)) {
                str += " and ";
            }

            str += " create_time between '" + startTime + "' and '" + endTime + "'";
        }

        if (!"".equals(str)) {
            userList = userService.selectByParam(null, str);
        } else {
            userList = userService.select(record);
        }
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return ReturnResult.ok(pageInfo);
    }


    /**
     * 根据ID查询新闻
     *
     * @param id
     * @return
     */
    @PostMapping("get/{id}")
    @ResponseBody
    public ReturnResult get(@PathVariable("id") Integer id) {
        return ReturnResult.ok(userService.select(new User().setId(id)));
    }

    /**
     * 根据ID删除会员  -- false
     *
     * @param id
     * @return
     */
    @PostMapping("del")
    @ResponseBody
    public ReturnResult del(Integer id) {
        userService.delete(new User().setId(id));
        return ReturnResult.ok();
    }

    /**
     * 根据ID修改会员  -- false
     *
     * @return
     */
    @PostMapping("update")
    @ResponseBody
    public ReturnResult update(User user) {
        userService.update(user);
        return ReturnResult.ok();
    }

    /**
     * 冻结用户
     *
     * @param id 用户id
     * @return
     */
    @PostMapping("frozen")
    @ResponseBody
    public ReturnResult frozen(Integer id) {
        return userService.frozen(id);
    }

    /**
     * 获取登录名称
     *
     * @return
     */
    @GetMapping("getLoginName")
    @ResponseBody
    public ReturnResult getLoginName() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return ReturnResult.ok(auth.getName());
    }

    /**
     * 获取用户统计权限信息
     *
     * @param id
     * @return
     */
    @PostMapping("selectByUserID")
    public ReturnResult selectByUserID(Integer id) {
        return ReturnResult.ok(statisticalPermissionsService.selectByUserID(id));
    }

    /**
     * 为用户分配权限和秘钥
     * @param userID
     * @param ids
     * @param secretKey
     * @return
     */
    @PostMapping("allocationPermission")
    public ReturnResult allocationPermission(Integer userID, String ids, String secretKey) {
//        验证秘钥
        if(!userStatisticalService.verifySecretKey(userID,secretKey)){
            return ReturnResult.error("秘钥验证不通过");
        }
        List<UserStatistical> list = new ArrayList<>();
        //如果权限集合ids为 空，则直接删除已有权限;如果权限集合ids 不 为空，则先删除在新增
        if(!ids.isEmpty()){
            String[] idsArray = ids.split(",");
            for (String id : idsArray) {
                UserStatistical userStatistical = new UserStatistical();
                userStatistical.setSecretKey(secretKey);
                userStatistical.setUserId(userID);
                userStatistical.setStatiscalPermissionsId(Integer.parseInt(id));
                list.add(userStatistical);
            }
        }
        return ReturnResult.ok(userStatisticalService.allocationPermission(userID,list));
    }
}
