package com.cnd3b.restcontroller.publicmethod.users;

import com.cnd3b.utility.Encryption;
import com.alibaba.fastjson.JSONObject;
import com.cnd3b.common.Controller;
import com.cnd3b.common.D3bException;
import com.cnd3b.common.data.Rows;
import com.cnd3b.common.parameter.parameter;
import com.cnd3b.common.restful.WebClientRest;
import com.cnd3b.utility.Sms;
import p2.pao.PaoRemote;
import p2.pao.PaoSetRemote;
import p2.util.P2Exception;

import java.util.Calendar;
import java.util.Random;

public class Users extends Controller {
    public Users(JSONObject content) {
        super(content);
    }

    /**
     * 二级推广人角色创建
     *
     * @return
     */
    public String register_promoters() throws D3bException, P2Exception {
        String fphonenumber = content.getString("fphonenumber", "tenterprise_users.fphonenumber", "手机号");
        String fname = "匿名";
        if (content.containsKey(fname)) {
            fname = content.getString("fname", "tenterprise_users.fname", "姓名");
        }
        PaoSetRemote tenterprise_users = getP2ServerSystemPaoSet("tenterprise_users", "fphonenumber='" + fphonenumber + "' and siteid='PROMOTERS'");
        if (tenterprise_users.isEmpty()) {
            PaoRemote pao = tenterprise_users.addAtEnd();
            pao.setValue("siteid", "PROMOTERS", 11L);
            pao.setValue("fphonenumber", fphonenumber, 11L);
            pao.setValue("fname", fname, 11L);
            pao.setValue("fusertype", "推广人", 11L);
            tenterprise_users.save();
        } else {
            return getErrReturnObject().setErrMsg("该手机号已注册").toString();
        }
        WebClientRest rest = new WebClientRest();
        String password = rest.createPassWord();
        parameter.phonenumber_password.put(fphonenumber, password);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 30000000);
        parameter.phonenumber_date.put(fphonenumber, calendar.getTime());

        JSONObject object = new JSONObject();
        object.put("phonenumber", fphonenumber);
        object.put("password", new Encryption().Encode_MD5(password));

        return rest.login(object.toJSONString());
    }

    /**
     * 独立经销商角色创建
     *
     * @return
     */
    public String register_agents() throws D3bException, P2Exception {
        String fagentname = content.getString("fagentname", "tagents.fagentname", "店铺名称");//店铺名、公司名
        String fname = content.getString("fname", "tagents.fname", "姓名");//姓名
        String fphonenumber = content.getString("fphonenumber", "tagents.fphonenumber", "手机号");//手机号
        String fprovince = content.getString("fprovince");//省
        String fcity = content.getString("fcity");//市
        String fcounty = content.getString("fcounty");//县
        String faddress = content.getString("faddress", "tagents.faddress", "店铺地址");//地址
        //String fsex = content.getString("fsex");
        //String fbirthdate = content.getString("fbirthdate");
        //String femail = content.getString("femail");
        //String fwechatno = content.getString("fwechatno");

        PaoSetRemote tagentsSet = getP2ServerSystemPaoSet("tagents", "fphonenumber='" + fphonenumber + "' and siteid='AGENTS' and fagentname='" + fagentname + "'");
        if (!tagentsSet.isEmpty()) {
            return getErrReturnObject().setErrMsg("商家名称不能重复").toString();
        }
        PaoRemote tagents = tagentsSet.addAtEnd();
        tagents.setValue("siteid", "AGENTS", 11L);//企业ID
        tagents.setValue("createdate", getDateTime(), 11L);//录入时间
        tagents.setValue("fagentname", fagentname, 11L);
        tagents.setValue("fagentshortname", fagentname, 11L);
        tagents.setValue("faddress", faddress, 11L);
        tagents.setValue("fcontact", fname, 11L);
        tagents.setValue("fphonenumber", fphonenumber, 11L);
        tagents.setValue("fprovince", fprovince, 11L);
        tagents.setValue("fcity", fcity, 11L);
        tagents.setValue("fcounty", fcounty, 11L);
        tagents.setValue("fjoindate", getDateTime(), 11L);

        PaoSetRemote tenterprise_users = tagents.getPaoSet("tenterprise_users");
        PaoRemote tenterprise_user = tenterprise_users.addAtEnd();
        tenterprise_user.setValue("fisadministrator", true, 11L);
        tenterprise_user.setValue("frole", "管理员", 11L);
        tenterprise_user.setValue("fname", fname, 11L);
        tenterprise_user.setValue("fphonenumber", fphonenumber, 11L);
        //tenterprise_user.setValue("fbirthdate", fbirthdate, 11L);
        //tenterprise_user.setValue("femail", femail, 11L);
        //tenterprise_user.setValue("fwechatno", fwechatno, 11L);
        //tenterprise_user.setValue("fsex", fsex, 11L);
        tagentsSet.save();

        WebClientRest rest = new WebClientRest();
        String password = rest.createPassWord();
        parameter.phonenumber_password.put(fphonenumber, password);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 30000000);
        parameter.phonenumber_date.put(fphonenumber, calendar.getTime());

        JSONObject object = new JSONObject();
        object.put("phonenumber", fphonenumber);
        object.put("password", new Encryption().Encode_MD5(password));

        return rest.login(object.toJSONString());
    }

    /**
     * @return
     */
    public String getUserMsgByShortCode() {
        String fshortcode = content.getString("fshortcode");
        Rows rows = dbConnect.runSqlQuery("select t1.tenterprise_userid,t1.fname,t2.tagentsid,t2.fagentname from tenterprise_users t1 inner join tagents t2 on t1.siteid=t2.siteid and t1.tagentsid=t2.tagentsid where t1.fshortcode='" + fshortcode + "'");
        if (!rows.isEmpty()) {
            return getSucReturnObject().setData(rows).toString();
        } else {
            return getErrReturnObject().setErrMsg("找不到唯一的邀请人信息").toString();
        }
    }

    /**
     * 忘记密码验证码获取
     *
     * @return
     */
    public String getForgetPassword() {
        String faccountno = content.getString("faccountno");//登录账号
        if (faccountno.length() > 9) {
            JSONObject object = new JSONObject();
            object.put("code", 1);
            object.put("msg", "请输入正确的账号信息");
            return object.toString();
        }
        Rows rows = dbConnect.runSqlQuery("select isnull(fphonenumber,'') as fphonenumber from tenterprise_users where faccountno='" + faccountno + "'");
        if (rows.size() != 1) {
            JSONObject object = new JSONObject();
            object.put("code", 1);
            object.put("msg", "不存在当前账号信息");
            return object.toString();
        }
        String phonenumber = rows.get(0).getString("fphonenumber");
        if ("".equals(phonenumber)) {
            JSONObject object = new JSONObject();
            object.put("code", 1);
            object.put("msg", "当前账号没有绑定手机号，无法进行密码重置");
            return object.toString();
        }
        String password = createPassWord();
        parameter.forgetpassword_passwordmap.put(faccountno, password);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        parameter.forgetpassword_date.put(faccountno, calendar.getTime());
        if (parameter.isdebug()) {
            JSONObject object = new JSONObject();
            object.put("code", 1);
            object.put("msg", "验证码：" + password);
            return object.toString();
        } else {
            JSONObject object = new JSONObject();
            Sms sms = new Sms();
            sms.sendOutMsg(phonenumber, password);
            object.put("code", 1);
            object.put("msg", "验证码已发送，请注意查收！");
            return object.toString();
        }
    }

    private String createPassWord() {
        String allChar = "1234567890";
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(allChar.charAt(random.nextInt(allChar.length())));
        }
        if (parameter.forgetpassword_passwordmap.containsValue(sb.toString())) {
            return createPassWord();
        } else {
            return sb.toString();
        }
    }

    /**
     * 忘记密码修改验证码
     *
     * @return
     */
    public String changePassWord() throws P2Exception {
        String password = content.getString("password");//手机短信验证码，md5加密
        String newpassword = content.getString("newpassword");//账号新密码，md5加密
        String faccountno = content.getString("faccountno");//登录账号

        int resultcode;
        if (!parameter.forgetpassword_passwordmap.containsKey(faccountno)) {
            resultcode = 1;//没有获取验证码
        } else if (parameter.forgetpassword_date.get(faccountno).before(Calendar.getInstance().getTime())) {
            resultcode = 2;//验证码已失效
        } else {
            //系统验证码
            String syspassword = parameter.forgetpassword_passwordmap.get(faccountno);
            if (password.equals(new Encryption().Encode_MD5(syspassword))) {
                resultcode = 0;//验证码正确
            } else {
                resultcode = 3;//验证码错误
            }
        }
        if (resultcode == 0) {
            PaoSetRemote tenterprise_usersSet = getP2ServerSystemPaoSet("tenterprise_users", "faccountno='" + faccountno + "'");
            if (!tenterprise_usersSet.isEmpty()) {
                tenterprise_usersSet.getPao(0).setValue("fpassword", newpassword, 11L);
                tenterprise_usersSet.save();
            } else {
                return getErrReturnObject().setErrMsg("找不到当前账号信息").toString();
            }
            return getSucReturnObject().toString();
        } else {
            String msg = "";
            if (resultcode == 1) {
                msg = "请先获取验证码！";
            } else if (resultcode == 2) {
                msg = "验证码已失效，请重新获取！";
            } else if (resultcode == 3) {
                msg = "无效的验证码！";
            }
            JSONObject object = new JSONObject();
            object.put("code", 0);
            object.put("msg", msg);
            return object.toString();
        }
    }
}
