package com.dgtis.dorm.manager.admin.web;

import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.dgtis.dorm.manager.admin.annotation.LoginAdmin;
import com.dgtis.dorm.manager.admin.service.AdminTokenManager;
import com.dgtis.dorm.manager.admin.util.bcrypt.BCryptPasswordEncoder;
import com.dgtis.dorm.manager.db.domain.Admin;
import com.dgtis.dorm.manager.db.domain.AlumniUser;
import com.dgtis.dorm.manager.db.service.AdminService;
import com.dgtis.dorm.manager.db.service.UserService;
import com.dgtis.dorm.manager.db.util.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("/admin/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;

    @GetMapping("/info")
    public Object info(String token){
        Integer adminId = AdminTokenManager.getUserId(token);
        if(adminId == null){
            return ResponseUtil.badArgumentValue();
        }
        Admin admin = adminService.findById(adminId);
        if(admin == null){
            return ResponseUtil.badArgumentValue();
        }

        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());

        // 目前roles不支持，这里简单设置admin
        List<String> roles = new ArrayList<>();
        roles.add("admin");
        data.put("roles", roles);
        data.put("introduction", "admin introduction");
        return ResponseUtil.ok(data);
    }

    @GetMapping("/list")
    public Object list(@LoginAdmin Integer adminId,
                       String username,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                       String sort, String order){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        List<Admin> adminList = adminService.querySelective(username, page, limit, sort, order);
        int total = adminService.countSelective(username, page, limit, sort, order);
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", adminList);

        return ResponseUtil.ok(data);
    }

    @PostMapping("/create")
    public Object create(@LoginAdmin Integer adminId, @RequestBody Admin admin){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        //String rawPassword = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //String encodedPassword = encoder.encode(rawPassword);
        //admin.setPassword(encodedPassword);
        admin.setPassword(encoder.encode(admin.getPassword()));

        adminService.add(admin);
        return ResponseUtil.ok(admin);
    }

    @GetMapping("/read")
    public Object read(@LoginAdmin Integer adminId, Integer id){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        if(id == null){
            return ResponseUtil.badArgument();
        }

        Admin admin = adminService.findById(id);
        return ResponseUtil.ok(admin);
    }

    @PostMapping("/update")
    public Object update(@LoginAdmin Integer adminId, @RequestBody Admin admin){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        Integer anotherAdminId = admin.getId();
        if(anotherAdminId.intValue() == 1 && adminId.intValue() != 1){//只有超管本人能修改
            return ResponseUtil.fail(403, "超级管理员不能修改");
        }
        
        //String rawPassword = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //String encodedPassword = encoder.encode(rawPassword);
        //admin.setPassword(encodedPassword);
        admin.setPassword(encoder.encode(admin.getPassword()));
        
        adminService.updateById(admin);

        return ResponseUtil.ok(admin);
    }

    @PostMapping("/delete")
    public Object delete(@LoginAdmin Integer adminId, @RequestBody Admin admin){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        Integer anotherAdminId = admin.getId();
        if(anotherAdminId.intValue() == 1){
            return ResponseUtil.fail(403, "超级管理员不能删除");
        }
        adminService.deleteById(anotherAdminId);
        return ResponseUtil.ok();
    }

    @GetMapping("/getWxUserId")
    public Object getWxUserId(@LoginAdmin Integer adminId, String phone) {

        int userId = 0;

        if(StringUtils.isNotBlank(phone)) {
            AlumniUser alumniUser = new AlumniUser();
            alumniUser.setPhone(phone);
            PageInfo<AlumniUser> pageInfo = userService.querySelective(alumniUser, 1, 10, null, null);

            if (pageInfo.getList().size() == 1) {
                userId = pageInfo.getList().get(0).getId();
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("userId", userId);
        return ResponseUtil.ok(data);
    }


    public Object uploadAvatar(@RequestParam("file") MultipartFile file){

        return ResponseUtil.ok();
    }


    /**
     * @descption: 子系统同步添加用户方法
     * @param: [data]
     * @return: java.lang.Object
     * @auther: koucx
     * @date: 2019/6/4 13:24
     */
    @PostMapping("/syncCreate")
    public Object syncCreate(String data){

        if(StringUtils.isNotBlank(data)){
            //获取同步信息字符串，解析后封装成当前系统管理实体存储
            JSONArray array = JSONArray.fromObject(data);
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            for (Object obj:array) {
                JSONObject jsonObject = JSONObject.fromObject(obj);
                String id = jsonObject.get("id").toString();//用户主键
                Admin admin = adminService.selectByUserId(Integer.parseInt(id));
               /* String loginId = jsonObject.get("loginId").toString();//登录名
                admin.setUsername(loginId);
                String loginPwd = jsonObject.get("loginPwd").toString();//密码
                admin.setPassword(encoder.encode(loginPwd));*/
               if(admin==null){
                   admin = new Admin();
                   String userName = jsonObject.get("userName").toString();//用户名
                   admin.setNickname(userName);//用户主键
                   admin.setUserId(Integer.parseInt(id));
                   String employeNo = jsonObject.get("employeNo").toString();
                   admin.setEmployeNo(employeNo);
                   Object phone = jsonObject.get("userPhone");//手机
                   if(phone!=null){
                       admin.setPhone(phone.toString());
                   }
                   Object userEmail = jsonObject.get("userEmail");//邮箱
                   if(userEmail!=null){
                       admin.setUserEmail(userEmail.toString());
                   }
                   Object post = jsonObject.get("post");//岗位
                   if(post!=null){
                       admin.setPost(post.toString());
                   }
                   admin.setDeleted(false);
                   adminService.add(admin);
               }
            }
            return ResponseUtil.ok();
        }

        return ResponseUtil.fail();
    }

    /**
     * @descption: 子系统同步修改用户方法
     * @param: [data]
     * @return: java.lang.Object
     * @auther: koucx
     * @date: 2019/6/4 13:24
     */
    @PostMapping("/syncUpdate")
    public Object syncUpdate(String data){

        if(StringUtils.isNotBlank(data)){
            //获取同步信息字符串，解析后封装成当前系统管理实体存储
            JSONArray array = JSONArray.fromObject(data);
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            for (Object obj:array) {
                JSONObject jsonObject = JSONObject.fromObject(obj);
                String userId = jsonObject.get("id").toString();//用户主键
                Admin admin = adminService.selectByUserId(Integer.parseInt(userId));
                if(admin!=null){
                   /* String loginId = jsonObject.get("loginId").toString();//登录名
                    admin.setUsername(loginId);
                    Object loginPwd = jsonObject.get("loginPwd");
                   if(loginPwd!=null){
                       admin.setPassword(encoder.encode(loginPwd.toString()));
                   }*/
                    String userName = jsonObject.get("userName").toString();//用户名
                    admin.setNickname(userName);
                    Object phone = jsonObject.get("userPhone");//手机
                    if(phone!=null){
                        admin.setPhone(phone.toString());
                    }
                    Object userEmail = jsonObject.get("userEmail");//邮箱
                    if(userEmail!=null){
                        admin.setUserEmail(userEmail.toString());
                    }
                    Object post = jsonObject.get("post");//岗位
                    if(post!=null){
                        admin.setPost(post.toString());
                    }
                    adminService.updateById(admin);
                }
            }
            return ResponseUtil.ok();
        }

        return ResponseUtil.fail();
    }

    /**
     * @descption: 子系统同步删除用户方法
     * @param: [data]
     * @return: java.lang.Object
     * @auther: koucx
     * @date: 2019/6/4 13:24
     */
    @PostMapping("/syncDelete")
    public Object syncDelete(String data){

        if(StringUtils.isNotBlank(data)){
            //获取同步信息字符串
            JSONArray array = JSONArray.fromObject(data);
            for (Object obj:array) {
                String userId = obj.toString();//用户主键
                Admin admin = adminService.selectByUserId(Integer.parseInt(userId));
                if(admin!=null){
                    adminService.deleteById(admin.getId());
                }
            }
            return ResponseUtil.ok();
        }

        return ResponseUtil.fail();
    }
}
