package com.dgtly.api.controller;


import com.dgtly.apiframework.exception.LessParamException;
import com.dgtly.apiframework.util.TokenUtil;
import com.dgtly.common.constant.UserConstants;
import com.dgtly.common.core.controller.BaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.system.domain.EntryPass;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.IEntryPassService;
import com.dgtly.system.service.ISysUserService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/grid")
public class GridController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IEntryPassService entryPassService;

    /**
     * 获取社区内人员列表
     * @return
     */
    @PostMapping("/getCommunityPeople")
    @ResponseBody
    public AjaxResult getCommunityPeople(){
        Long userId = Long.parseLong(TokenUtil.getTokenUserId());
        SysUser user = sysUserService.selectUserById(userId);
        SysUser paramUser =  new SysUser();
        paramUser.setChargeCommunityId(user.getChargeCommunityId());
        List<SysUser> resultUsers = sysUserService.selectPeople(paramUser);
        return AjaxResult.success().putKV("list",resultUsers);
    }

    /**
     * 新增所属网格内的普通人员
     * @return
     */
    @PostMapping("/addCommunityPeople")
    @ResponseBody
    public AjaxResult addCommunityPeople(){
        Long userId = Long.parseLong(TokenUtil.getTokenUserId());
        SysUser user = sysUserService.selectUserById(userId);

        Map param = getJsonMap();
        SysUser addUser = new SysUser();
        Long[] i = {3L};
        addUser.setRoleIds(i);
        if(!param.containsKey("phonenumber")||!param.containsKey("username")||!param.containsKey("idcard")
                ||!param.containsKey("sex")||!param.containsKey("isWuhan")){
            throw  new LessParamException();
        }
        addUser.setPhonenumber(param.get("phonenumber").toString());
        addUser.setLoginName(param.get("phonenumber").toString());
        addUser.setPassword(param.get("phonenumber").toString());
        addUser.setChargeCommunityId(user.getChargeCommunityId());
        addUser.setUserName(param.get("username").toString());
        addUser.setIdCard(param.get("idcard").toString());
        addUser.setSex(param.get("sex").toString());
        addUser.setIsWuhan(param.get("isWuhan").toString());
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(sysUserService.checkLoginNameUnique(addUser.getLoginName(),0L)))
        {
            return error("新增用户'" + addUser.getLoginName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(addUser)))
        {
            return error("新增用户'" + addUser.getLoginName() + "'失败，手机号码已存在");
        }
        addUser.setSalt(randomSalt());
        addUser.setPassword(EncryptPassWordClass.encryptPassword(addUser.getLoginName(), addUser.getPassword(), addUser.getSalt()));
        addUser.setCreateBy(user.getLoginName());

        int num = sysUserService.insertUser(addUser);
        if(num>0){
            return success();
        }else{
           return error();
        }

    }

    /**
     * 获取出入证待审批列表
     * @return
     */
    @PostMapping("/getUncheckedPostList")
    @ResponseBody
    public AjaxResult getUncheckedPostList(){
        Long userId = Long.parseLong(TokenUtil.getTokenUserId());
        SysUser user = sysUserService.selectUserById(userId);
        EntryPass ep = new EntryPass();
        ep.setChargeCommunityId(user.getChargeCommunityId());
        ep.setStatus("0");
        List<EntryPass> result = entryPassService.selectEntryPassList(ep);
        return success().putKV("list",result);
    }

    /**
     * 获取出入证待审批列表
     * @return
     */
    @PostMapping("/checkPass")
    @ResponseBody
    public AjaxResult checkPass(){
        Long userId = Long.parseLong(TokenUtil.getTokenUserId());
        SysUser user = sysUserService.selectUserById(userId);
        Map param = getJsonMap();
        if(!param.containsKey("status")||!param.containsKey("userId")){
            throw new LessParamException();
        }
        EntryPass ep = new EntryPass();
        ep.setUpdateBy(user.getLoginName());
        ep.setUserId(Long.parseLong(param.get("userId").toString()));
        ep.setStatus(param.get("status").toString());
        if(param.containsKey("auditOpinion")){
            ep.setAuditOpinion(param.get("auditOpinion").toString());
        }
        int i  = entryPassService.updateEntryPass(ep);
        if(i>0){
            return success();
        }
        return error();
    }


    /**
     * 生成随机盐
     */
    public static String randomSalt()
    {
        // 一个Byte占两个字节，此处生成的3字节，字符串长度为6
        SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
        String hex = secureRandom.nextBytes(3).toHex();
        return hex;
    }


}
