package com.dgtly.api.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.dgtly.apiframework.exception.LessParamException;
import com.dgtly.apiframework.util.TokenUtil;
import com.dgtly.common.annotation.ApiPassToken;
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.domain.UserTemperature;
import com.dgtly.system.service.IEntryPassService;
import com.dgtly.system.service.ISysUserService;
import com.dgtly.system.service.IUserTemperatureService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/people")
public class PeopleController extends BaseController {


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

    /**
     * 新增所属网格内的普通人员
     * @return
     */
    @PostMapping("/addPeople")
    @ResponseBody
    @ApiPassToken
    public AjaxResult addPeople(){
        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")||!param.containsKey("password")
                ||!param.containsKey("chargeCommunity")){
            throw  new LessParamException();
        }
        addUser.setPhonenumber(param.get("phonenumber").toString());
        addUser.setLoginName(param.get("phonenumber").toString());
        addUser.setPassword(param.get("password").toString());
        addUser.setChargeCommunityId((Long)param.get("chargeCommunity"));
        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()));

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

    }


    /**
     * 直接申请通行证
     * @return
     */
    @PostMapping("/getPass")
    @ResponseBody
    @ApiPassToken
    public AjaxResult getPass(){
        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") ||!param.containsKey("chargeCommunityId")){
            throw  new LessParamException();
        }

        if(!param.containsKey("address")||!param.containsKey("householdRelation")
                ||!param.containsKey("residentNum")){
            throw  new LessParamException();
        }
        addUser.setPhonenumber(param.get("phonenumber").toString());
        addUser.setLoginName(param.get("phonenumber").toString());
        addUser.setPassword(param.get("phonenumber").toString());
        addUser.setChargeCommunityId(Long.parseLong(param.get("chargeCommunityId").toString()));
        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(300,"新增用户'" + addUser.getLoginName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(addUser)))
        {
            return error(300,"新增用户'" + addUser.getLoginName() + "'失败，手机号码已存在");
        }
        addUser.setSalt(randomSalt());
        addUser.setPassword(EncryptPassWordClass.encryptPassword(addUser.getLoginName(), addUser.getPassword(), addUser.getSalt()));

        /*--------------------添加通行证信息---------------------------*/
        EntryPass ep = new EntryPass();
        ep.setAddress(param.get("address").toString());
        ep.setHouseholdRelation(param.get("householdRelation").toString());
        ep.setResidentNum(Long.parseLong(param.get("residentNum").toString()));
        if(param.containsKey("ownership")){
            ep.setOwnership(param.get("ownership").toString());
        }
        ep.setStatus("0");

        int num  =sysUserService.insertPass(addUser,ep);

        if(num>0){
            Date start = new Date();
            long currentTime = System.currentTimeMillis() + 12*60* 60 * 1000;//12小时有效时间
            Date end = new Date(currentTime);
            String token = "";

            token = JWT.create().withAudience(addUser.getUserId().toString())
                    .withIssuedAt(start)
                    .withExpiresAt(end)
                    .sign(Algorithm.HMAC256(addUser.getPassword()));
            return success().putKV("userId",addUser.getUserId()).putKV("token",token);
        }
        return error();
    }

    /**
     * 直接申请通行证
     * @return
     */
    @PostMapping("/addTemperature")
    @ResponseBody
    public AjaxResult addTemperature(){
        Map param = getJsonMap();
        if(!param.containsKey("temperature")){
            throw new LessParamException();
        }
        UserTemperature ut = new UserTemperature();
        ut.setUserId(Long.parseLong(TokenUtil.getTokenUserId()));
        ut.setTemperature(param.get("temperature").toString());
        int i =userTemperatureService.insertUserTemperature(ut);
        if(i>0){
            return success();
        }
        return error();
    }

    /**
     * 直接申请通行证
     * @return
     */
    @PostMapping("/getTemperatureList")
    @ResponseBody
    public AjaxResult getTemperatureList(){
        Map param = getJsonMap();
        if(!param.containsKey("userId")){
            throw new LessParamException();
        }
        UserTemperature ut = new UserTemperature();
        ut.setUserId(Long.parseLong(param.get("userId").toString()));
        List<UserTemperature> utList =userTemperatureService.selectUserTemperatureList(ut);
        return success().putKV("list",utList);
    }

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

}
