<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Home\Controller;
use Think\Controller;
use Base\Repository\PromoteRepository;

/**
 * 扩展控制器
 * 用于调度各个扩展的URL访问需求
 */
class SafeController extends BaseController{
    
    public function setSafeIndex() {
        $id = get_pid();
        $safePwd = M('promote','tab_')->where(['id'=>$id])->field('second_pwd')->find();
        if(empty($safePwd['second_pwd'])) {
            return $this->display();
        }else {
            return $this->display("verifySafePwd");
        }
        
    }

    public function setSafePwd() {
        $this->display('Public/setSafePwd');
    }
    
    public function setSafePassword() {
        $password = $_REQUEST['password'];
        $confirmpassword = $_REQUEST['confirm_password'];
        if($password == "") {
            $this->error("新密码不能为空");
        }
        if($confirmpassword == "") {
            $this->error("确认密码不能为空");
        }
        if($password !== $confirmpassword) {
            $this->error("两次密码不一致,请确认!");
        }
        $this->checkPaswwordFormat($confirmpassword);
        $data['second_pwd'] = $this->think_ucenter_md5($confirmpassword, UC_AUTH_KEY);
        $id = get_pid();
        $updateRs = M("promote","tab_")->where(['id'=>$id])->save($data);
        if($updateRs) {
            recordPromoteLogs('安全管理','设置安全密码');
            $this->success("安全密码设置成功");
        }
    }
    
     public function think_ucenter_md5($str, $key = 'ThinkUCenter')
    {
        return '' === $str ? '' : md5(sha1($str) . $key);
    }
    
    public function checkPaswwordFormat($confirmpwd) {
        if(strlen($confirmpwd) < 6 || strlen($confirmpwd) > 24) {
            $this->error("密码至少6位数,最多24位");
        }
        if(preg_match("/^\d*$/",$confirmpwd))
        {
          $this->error("密码必须包含字母,强度:弱");
        }
        if(preg_match("/^[a-z]*$/i",$confirmpwd))
        {
           $this->error("密码必须包含数字,强度:中");
        }
        if(!preg_match("/^[a-z\d]*$/i",$confirmpwd))
        {
          $this->error("密码只能包含数字和字母,强度:强");
        }
    }
    
    public function modifyPwdIndex() {
        if($_POST) {
            $oldpwd = $_POST['oldpwd'];
            $safepwd = $_POST['safepwd'];
            if(empty($oldpwd)) {
                $this->error("旧密码不能为空");
            }
            if(empty($safepwd)) {
                $this->error("安全密码不能为空");
            }
            $id = get_pid();
            $safePwd = M('promote','tab_')->where(['id'=>$id])->field('second_pwd')->find();
            if($safePwd['second_pwd'] == $this->think_ucenter_md5($oldpwd, UC_AUTH_KEY)){
               $data['second_pwd'] = $this->think_ucenter_md5($safepwd, UC_AUTH_KEY);
               $updateRs = M("promote","tab_")->where(['id'=>$id])->save($data);
               if($updateRs) {
                   $this->success("修改成功");
               }else {
                   $this->error("修改失败,请重新操作");
               }
            }
            else {
                $this->error('旧密码错误,请确认');
            }
        }
        $this->display();
    }
    
    
    public function verifySafePwd() {
        if($_POST) {
            $password = $_POST['safepwd'];
            if($password == "" || $password == NULL) {
                $this->error("密码不能为空");
            }
            $id = get_pid();
            $safePwd = M('promote','tab_')->where(['id'=>$id])->field('second_pwd')->find();
            if($safePwd['second_pwd'] == $this->think_ucenter_md5($password, UC_AUTH_KEY)){
                $this->success("登陆成功,即将跳转",U('modifyPwdIndex'));
            }
            else {
                $this->error('密码错误,请重新输入密码');
            }
        }
        $this->display();
    }
    
    //修改登陆密码
    public function modifyLoginPassword() {
        if($_POST) {
            $oldpwd = $_POST['oldpwd'];
            $newpwd = $_POST['newpwd'];
            $id = get_pid();
            $pwd = M('promote','tab_')->where(['id'=>$id])->field('password')->find();
            $password = $pwd["password"];
            if($oldpwd != "0" && empty($oldpwd)) {
                $this->error("旧密码不能为空");
                return false;
            }
            if($newpwd != "0" && empty($newpwd)) {
                $this->error("新密码不能为空");
                return false;
            }
            if($this->think_ucenter_md5($oldpwd, UC_AUTH_KEY) !== $password) {
                $this->error("请输入正确旧密码");
                return false;
            }
            $this->checkPaswwordFormat($newpwd);
            $data['password'] = $this->think_ucenter_md5($newpwd, UC_AUTH_KEY);
            $updateRs = M('promote','tab_')->where(['id'=>$id])->save($data);
            if($updateRs) {
                recordPromoteLogs('安全管理','修改登陆密码');
                $this->success("修改成功");
            }else {
                $this->error("修改失败");
                return false;
            }
        }
        $this->display();
    }
    
    //修改用户信息
    public function modifyBaseInfo() {
        $id = get_pid();
        $safePwd = M('promote','tab_')->where(['id'=>$id])->field('second_pwd')->find();
        if(empty($safePwd['second_pwd'])) {
            $this->display('Public/setSafePwd');
            exit;
        }
        $metaTitle = '基础信息';
        $modelList = ['基础信息', $metaTitle];
        $this->verifyPasswordView($modelList);
        $ver_status = M('promote','tab_')->where(['id'=>$id])->getField('ver_status',true);
        if($ver_status[0] == 1) {
            //return $this->display('editModify'); 
            $this->redirect('editModify');
            exit;       
        }
        if($_POST) {
            $username = $_REQUEST['username']; //真实姓名
            $id_card = $_REQUEST["id_card"]; //身份证号码
            $tel = $_REQUEST['tel'];
            $address = $_REQUEST['s_province'].$_REQUEST['s_city'].$_REQUEST['s_county'];  //省市县
            $contactAddress = $_REQUEST['address'];  //具体地址
          //  $userAddress = $address.'('.$contactAddress.')';
            $userAddress[0] = $_REQUEST['s_province'].','.$_REQUEST['s_city'].','.$_REQUEST['s_county'];
            $userAddress[1] = $contactAddress;
            $email = $_REQUEST['email'];
            $account_type = $_REQUEST['account_type'];  //账户类型
            $bank_name = $_REQUEST["bank_name"];             //开户银行
            $bank_account = $_REQUEST['bank_account'];        //银行账户名
            $bank_card = $_REQUEST['bank_card'];            //银行账号
            $idcarpic = $_REQUEST['idcarpic'];
            $businesspic = $_REQUEST['businesspic']; 
            $agreementpic = $_REQUEST['agreementpic'];
            if(empty($_REQUEST['agree'])) {
                $this->error("请先认真阅读协议,然后勾选协议");
                return false;
            }
            if(empty($username)) {
                $this->error("真实姓名不能为空");
                return false;
            }
             if(empty($tel)) {
                $this->error("手机号码不能为空");
                return false;
            }
            $pattern = "/^1[3|5|7|8]\\d{9}$/i";
            if(!preg_match($pattern, $tel)) {
                $this->error("手机号码格式不合法");
                return false;
            }
            $telInfo = M('promote','tab_')->field('id')->where(['mobile_phone'=>$tel])->find();
            if(!empty($telInfo)) {
                $this->error("手机号码已存在");
                return false;
            }
            if(empty($id_card)) {
                $this->error("身份证号码不能为空");
                return false;
            }
            if(empty($idcarpic)) {
                $this->error("身份证证件照不能为空");
                return false;
            }
            if(!is_idcard($id_card)) {
                $this->error('证件号码错误');
                return false;
            }
            if(empty($address)) {
                $this->error("城市地址不能为空");
                return false;
            }
            if(empty($contactAddress)) {
                $this->error("联系地址不能为空");
            }
            if(empty($email)) {
                $this->error("邮箱不能为空");
                return false;
            }
            $patternemail = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
            if (!preg_match($patternemail, $email)) {
                $this->error('邮箱地址错误');
                return false;
            }
            if(empty($account_type)) {
                $this->error("账户类型不能为空");
                return false;
            }
            if(empty($bank_name)) {
                $this->error("开户银行不能为空");
                return false;
            }
            if(empty($bank_account)) {
                $this->error("银行户名不能为空");
                return false;
            }
            $bank_account_pattern = "/^[\x{4e00}-\x{9fa5}]{2,}$/u";
            if (!preg_match($bank_account_pattern, $bank_account)) {
                $this->error('银行卡开户人姓名错误');
                return false;
            }
             if(empty($bank_card)) {
                $this->error("卡号不能为空");
                return false;
            }
            $bank_card_pattern = "/^\d{10,19}$/u";
            if (!preg_match($bank_card_pattern, $bank_card)) {
                $this->error('卡号格式错误');
                return false;
            } 
            $data["real_name"] = $username;
            $data['mobile_phone'] = $tel;
            $data['idcard'] = $id_card;
            $data['address'] = json_encode($userAddress,FALSE);
            $data['email'] = $email;
            $data['account_type'] = $account_type;
            $data['bank_name'] = $bank_name;
            $data['bank_account'] = $bank_account;
            $data['bank_card'] = $bank_card;
            $data['idcarpic'] = $idcarpic;
            $data['businesspic'] = $businesspic;
            $data['agreementpic'] = $agreementpic;
            $data['ver_status'] = 3;
            if($account_type == "公司") {
                $data['account_type'] = 1;
            }else {
                $data['account_type'] = 2;
            }
            
            $updateRs = M("promote","tab_")->where(['id'=>$id])->save($data);
            if($updateRs) {
                recordPromoteLogs('安全管理','修改用户信息');
                $this->success("更新信息成功");
            }else {
                $this->error("更新信息失败");
            }
            
            
        }else {
            $id = get_PID();
            $result = M("promote","tab_")->where(['id'=>$id])->select();
            $promoteInfo = $result[0];
            $idcarpic = $promoteInfo['idcarpic'];
            $businesspic = $promoteInfo['businesspic'];
            $agreementpic = $promoteInfo['agreementpic'];
            $account_type = $promoteInfo['account_type'];
            $address = $promoteInfo["address"]; 
            if(!empty($idcarpic)) {
                $idcarpicArr = explode(',', $idcarpic);
                $str = '';
                foreach ($idcarpicArr as $key => $value) {
                   $promoteInfo['valuedata'][$key] =$value;
                }
            }
            if(!empty($businesspic)) {
               $businesspicArr = explode(',', $businesspic);
                $str = '';
                foreach ($businesspicArr as $key1 => $value1) {
                   $promoteInfo['valuedata1'][$key1] =$value1;
                }
            }
             if(!empty($agreementpic)) {
                $agreementpicArr = explode(',', $agreementpic);
                $str = '';
                foreach ($agreementpicArr as $key2 => $value2) {
                   $promoteInfo['valuedata2'][$key2] =$value2;
                }
            }
            if($account_type == 1) {
                $promoteInfo['complanystatus'] = true;
                $promoteInfo['personalstatus'] = false;
            }else {
                $promoteInfo['personalstatus'] = true;
                $promoteInfo['complanystatus'] = false;
            }
            if(!empty(json_decode($address)) && count(json_decode($address)) >= 2) {
                $addressArr = explode(',', json_decode($address)[0]);
                $promoteInfo['addressdata'] = $addressArr;
                $this->assign('addr',json_decode($address)[1]);
            }
            $promoteInfo['address'] = json_decode($address);
            
            $this->assign("ver_status",$promoteInfo['ver_status']);
            $this->assign('promoteinfo', $promoteInfo);
            
            
        }
        $this->display();
    }

    public function editModify() {
        $id = get_pid();
        $rs =  M("promote","tab_")->field('anothpic,ver_status,real_name,bank_card,mobile_phone,email,address,idcard')->where(['id'=>$id])->find();
        $anothpic = $rs['anothpic'];
        $promoteInfo = "";
        $address = json_decode($rs['address'],false)[1];
        $realname = mb_strlen($rs['real_name'],'utf-8') == 2 ? mb_substr($rs['real_name'],0,1,'utf-8').'*':mb_substr($rs['real_name'],0,1,'utf-8').'**';
        $this->assign('addr',$address);
        $this->assign('ver_status',$rs['ver_status']);
        $this->assign('rs',$rs);
        $this->assign('idcard',encryption($rs['idcard']));
        $this->assign('real_name',$realname);
        $this->assign('promoteInfo',$promoteInfo);
        $this->assign('tel',encryption($rs['mobile_phone']));
        $this->display();
    }  

    public function edit() {
        $id = get_pid();
        $tel = $_REQUEST["tel"];
        $address1 = $_REQUEST["address"];
        $email = $_REQUEST["email"];
        $account_type = $_REQUEST["account_type"];
        $bank = $_REQUEST["bank"];
        $agreementpic = $_REQUEST["agreementpic"];
        if(empty($tel)) {
            $this->error("手机号码不能为空");
            return false;
        }
        $pattern = "/^1[3|5|7|8]\\d{9}$/i";
        if(!preg_match($pattern, $tel)) {
            $this->error("手机号码格式不合法");
            return false;
        }
        $telInfo = M('promote','tab_')->field('id')->where(['mobile_phone'=>$tel])->find();
        if(!empty($telInfo)) {
            $this->error("手机号码已存在");
            return false;
        }

        if(empty($address1)) {
            $this->error("地址不能为空");
            return false;
        }
        if(empty($email)) {
            $this->error("邮箱不能为空");
            return false;
        }
        $patternemail = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
        if (!preg_match($patternemail, $email)) {
            $this->error('邮箱地址错误');
            return false;
        }
        if(empty($bank)) {
            $this->error("卡号不能为空");
            return false;
        }
        $bank_card_pattern = "/^\d{10,19}$/u";
        if (!preg_match($bank_card_pattern, $bank)) {
            $this->error('卡号格式错误');
            return false;
        } 
        if(empty($agreementpic)) {
            $this->error("补充协议不能为空");
            return false;
        }
        $Res = M("promote","tab_")->field('address')->where(['id'=>$id])->find();
        $address = json_decode($Res['address'],false);
        $address[1] = $address1;
        $data['mobile_phone'] = $tel;
        $data['address'] = json_encode($address,TRUE);
        $data['email'] = $email;
        $data['account_type'] = $account_type;
        $data['bank_card'] = $bank;
        $data['ver_status'] = 4;
     //  $data['agreementpic'] = $
        $data['anothpic'] = $agreementpic;
        $id = get_pid();
        $updateRs = M("promote","tab_")->where(['id'=>$id])->save($data);
            if($updateRs) {
                recordPromoteLogs('安全管理','二次修改信息');
                $this->success("更新信息成功",U('modifyBaseInfo'));
            }else {
                $this->error("更新信息失败");
            }
    }

    public function ajaxEdit() {
        $id = get_pid();
        $rs =  M("promote","tab_")->field('mobile_phone,address,email,account_type,bank_card,anothpic')->where(['id'=>$id])->find();
        $this->assign('tel',$rs['mobile_phone']);
        $this->assign('address',$rs['address']);
        $this->assign('email',$rs['email']);
        $this->assign('account_type',$rs['account_type']);
        $this->assign('bank_card',$rs['bank_card']);
        $res = [
            'tel'=> $rs['mobile_phone'],
            'address'=> json_decode($rs['address'],false)[1],
            'email'=> $rs['email'],
            'account_type'=> $rs['account_type'],
            'bank_card'=> $rs['bank_card'],
            'idcarpic' => $rs['idcarpic'],
            'anothpic' => $rs['anothpic'],
        ];
        if($rs['account_type'] == 1) {
            $res['complanystatus'] = true;
            $res['personalstatus'] = false;
        }else {
            $res['personalstatus'] = true;
            $res['complanystatus'] = false;
        }
        $this->ajaxReturn($res);
    }

    public function safeDocument() {
        $realname = $_REQUEST['realname'];
        $phone = $_REQUEST['phone'];
        $email = $_REQUEST['email'];
        $address = $_REQUEST['address'];
        if (empty($realname)) {
            $realname = '您未填写真实姓名';
        }
        if (empty($email)) {
            $email = '您未填写联系邮箱';
        }
        if (empty($address)) {
            $address = '您未填写注册地址';
        }
        if (empty($phone)) {
            $phone = '您未填写联系号码';
        }
        $time = time();
        $loginPromote = $this->getLoginPromote();
        $sn = date('Ymd') . '-' . strtoupper(substr(md5($loginPromote['id']), 8, 16));
        $endTime = date('Y-m-d',strtotime('+1 year'));
        $this->assign('time',date('Y-m-d',$time));
        $this->assign('endTime',$endTime);
        $this->assign('sn',$sn);
        $this->assign('realname',$realname);
        $this->assign('email',$email);
        $this->assign('address',$address);
        $this->assign('phone',$phone);
        $this->display();
    }

    public function promoteLogs() {
        $page = intval(I('p', 1));
        $row = intval(I('row', 10));
        $user_account = I('user_account');
        $action_type = I('action_type');
        $begTime = strtotime(I('begtime'));
        $endTime = strtotime(I('endtime'));
        $id = get_pid();
        
        $loginPromote = $this->getLoginPromote();
        $map1['chain'] = ['like', $loginPromote['chain'] . $loginPromote['id'] . '/%'];
        $ids = M('promote', 'tab_')->where($map1)->getField('id', true);
        $ids[] = $loginPromote['id'];
        $map = [];
        $map['promote_id'] = ['in', $ids];
        if (!empty($user_account)) {
            $map['promote'] = ['like','%'.$user_account.'%'];
        }
        if (!empty($action_type)) {
            $map['action_type'] = ['like','%'.$action_type.'%'];
        }
     
        if (!empty($begTime) && !empty($endTime)) {
            $map['create_time'] = ['between', [$begTime, $endTime + 24*3600 - 1]];
        }else if (empty($begTime) && !empty($endTime)) {
            $map['create_time'] = ['elt',$endTime + 24*3600];
        }else if (!empty($begTime) && empty($endTime)) {
            $map['create_time'] = ['EGT',$begTime + 24*3600];
        }
        $page = intval(I('get.p', 1));
        $page = $page ? $page : 1; //默认显示第一页数据arraypage
        $rs = M('promote_action_logs','tab_')->where($map)->order('create_time DESC')
            ->page($page, $row)->select();
        foreach($rs as $key => $v) {
                $rs[$key]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                
            }
        $count = M('promote_action_logs', 'tab_')
            ->field('id')
            ->where($map)
            ->select();
        $count = count($count);

        //分页
        $parameter['p'] = $page;
        $parameter['row'] = $row;
        $parameter['begtime'] = I('begtime');
        $parameter['endtime'] = I('endtime');
        $parameter['user_account'] = $user_account;
        $parameter['action_type'] = $action_type;
        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign('listData',$rs);
        $this->assign('initBegTime', I('begtime'));
        $this->assign('initEndTime', I('endtime'));
        $this->display();
    }

    public function deletePromoteLogs() {
        $id = $_REQUEST['id'];
        $rs = M('promote_action_logs','tab_')->where(['id'=>$id])->delete();
        if($rs) {
            $this->ajaxReturn(['code'=>0000,'mes'=>'删除成功']);
        }
    }
}