<?php

Doo::loadCore('auth/DooAuth');
Doo::loadClass('PasswordHash');
Doo::loadClass('client');
Doo::loadClass('auth');
Doo::loadClass('attachment');
Doo::loadClass('attfile');
Doo::loadClass('actmeasure');
Doo::loadClass('contractact');
Doo::loadClass('project');
Doo::loadClass('profile');
Doo::loadClass('numofperact');
Doo::loadClass('measureauditact');
Doo::loadClass('itemfile');
Doo::loadModel('users');
Doo::loadClass('itemmeasurenum');
Doo::loadModelAt('aconfig', 'admin');
Doo::loadClass('sms');
Doo::loadClass('Hashids/Hashids');

/**
 * MainController
 * Feel free to delete the methods and replace them with your own code.
 *
 * @author EllisRan
 */
class AppController extends DooController {

    private $data, $client, $auth, $att, $file, $zip, $actmeasure, $contractact, $project, $profile, $numofperact, $measureauditact, $attfile, $users, $itemfile, $modelconfig, $aconfig, $sms, $itemMeasureNum, $__hashids;

    private $statusArray = array('uncheck' => '1', 'checking' => '2', 'checked' => '3', 'checkno' => '4');
    private $fileTypeArray = array('台帐附件');

    public function __construct()
    {
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->client = new client();
        $this->auth = new Auth();
        $this->att = new attachment();
        $this->attfile = new attFile();
//        $this->zip = new ZipArchive();
        $this->actmeasure = new actMeasure();
        $this->contractact = new Contractact();
        $this->project = new Project();
        $this->profile = new Profile();
        $this->numofperact = new NumofperAct();
        $this->measureauditact = new MeasureauditAct();
        $this->users = new Users();
        $this->itemfile = new ItemFile();
        $this->modelconfig = new AConfig();
        $this->itemMeasureNum = new ItemMeasureNumpofper();
        $this->aconfig = new AConfig();
        $this->sms = new Sms(Doo::conf()->SMS_URL, Doo::conf()->SMS_AUTHKEY);
        $this->__hashids = new Hashids\Hashids('jlzfuserid', 8);
    }

    public function ServerLogin() {
        if(isset($_POST['sname']) && !empty($_POST['sname'])){
            $allserver = array($_SERVER['HTTP_HOST']);
            if(in_array(trim($_POST['sname']), $allserver)){
                echo json_encode(array('status' => TRUE, 'msg' => ''), JSON_UNESCAPED_UNICODE);
                die;
            }else{
                echo json_encode(array('status' => FALSE, 'msg' => '服务器不存在。'), JSON_UNESCAPED_UNICODE);
                die;
            }
        }else{
            echo json_encode(array('status' => FALSE, 'msg' => '请输入服务器名称。'), JSON_UNESCAPED_UNICODE);
            die;
        }
    }

    public function AppSignin() {
        if(!isset($_POST['username']) || empty($_POST['username'])){
            echo json_encode(array('status' => FALSE, 'msg' => '请输入邮箱'), JSON_UNESCAPED_UNICODE);
            die;
        }
        if(!isset($_POST['userpwd']) || empty($_POST['userpwd'])){
            echo json_encode(array('status' => FALSE, 'msg' => '请输入密码'), JSON_UNESCAPED_UNICODE);
            die;
        }

        if ($this->auth->login($_POST['username'], $_POST['userpwd'])) {
            $uinfo = $this->auth->getUinfo();
            if (isset($uinfo['isstop']) && $uinfo['isstop'] > 0) {
                echo json_encode(array('status' => FALSE, 'msg' => '邮箱不存在或者密码错误'), JSON_UNESCAPED_UNICODE);
                die;
            }
            if (isset($uinfo['uid'])) {
                $userArray = $this->profile->getProWithUid($uinfo['uid']);
                $avatarStr = $userArray['avatar'];
                if (isset($userArray['userid'])) {
//                    $this->auth->setUid($uinfo['uid']);
                    $msgArray = array('uid' => $uinfo['uid'], 'name' => $userArray['name'], 'email' => $uinfo['uemail'], 'ucompany' => $userArray['company'], 'jobtitle' => $userArray['jobs'], 'avatar' => Doo::conf()->APP_URL . $avatarStr);
                    echo json_encode(array('status' => TRUE, 'msg' => '', 'userinfo' => $msgArray), JSON_UNESCAPED_UNICODE);
                    die;
                }
            }

        } else {
            echo json_encode(array('status' => FALSE, 'msg' => '邮箱不存在或者密码错误'), JSON_UNESCAPED_UNICODE);
            die;
        }
    }

    // 获取待审批标段名
    public function UnSectionList(){
        if(isset($_POST['uid']) && !empty($_POST['uid']) && is_numeric($_POST['uid'])){
            $unsectionlist = $this->measureauditact->getCheckedRowbyUID6($_POST['uid']);
            $unslist = array();
            if(!empty($unsectionlist)){
                foreach($unsectionlist as $k => $v){
                    $unslist[$k]['pname'] = $this->project->getRowByPid($v['pid'])['pname'];
                    $unslist[$k]['sectionlist'] = array();
                    $sectionlist = $this->measureauditact->getCheckedRowbyUID7($_POST['uid'],$v['pid']);
                    if(!empty($sectionlist)){
                        foreach($sectionlist as $sk => $sv){
                            $name = $this->actmeasure->getRowByPmid($sv['pmid']);
                            $unslist[$k]['sectionlist'][$sk]['pmname'] = !empty($name) ? $name['pmname'] : '';
                            $countNum = $this->numofperact->getLastNew2($sv['pmid'])['numpname'];
                            $unslist[$k]['sectionlist'][$sk]['countNum'] = !empty($countNum) ? $countNum : 0;
                            $unslist[$k]['sectionlist'][$sk]['audittime'] = !empty($sv['audittime']) ? date('Y-m-d',$sv['audittime']) : '';
                            $unslist[$k]['sectionlist'][$sk]['url'] = '/app/rproject/' . $sv['pid'] . '/section/' . $sv['pmid'] . '/detail';
                            $stname = $this->contractact->getRowByStid($sv['stid']);
                            $unslist[$k]['sectionlist'][$sk]['stname'] = !empty($stname) ? $stname['stname'] : '';
                        }
                    }
                }
            }
            echo json_encode(array('status' => TRUE, 'msg' => '', 'unsectionlist' => $unslist), JSON_UNESCAPED_UNICODE);
            die();
        }else{
            $status = array('status' => FALSE, 'msg' => '获取待审批标段列表出错');
            echo json_encode($status, JSON_UNESCAPED_UNICODE);
            die();
        }
    }

    //获取已审核项目名
    public function ItemCkeckedList(){
        if(isset($_POST['uid']) && !empty($_POST['uid']) && is_numeric($_POST['uid'])){
            $Itemlist = $this->measureauditact->getCheckedRowbyUID3($_POST['uid']);
            $Itemcheckedlist = array();
            if(!empty($Itemlist)){
                foreach($Itemlist as $k => $v){
                    $name = $this->project->getRowByPid($v['pid']);
                    $Itemcheckedlist[$k]['pid'] = $v['pid'];
                    $Itemcheckedlist[$k]['pname'] = $name['pname'];
                }
            }
            echo json_encode(array('status' => TRUE, 'msg' => '', 'Itemlist' => $Itemcheckedlist), JSON_UNESCAPED_UNICODE);
            die();
        }else{
            $status = array('status' => FALSE, 'msg' => '获取已审核项目列表出错');
            echo json_encode($status, JSON_UNESCAPED_UNICODE);
            die();
        }
    }

    //获取已审核项目中已审核标段的信息
    public function SectionCheckedList(){
        if(isset($_POST['uid']) && is_numeric($_POST['uid']) && isset($this->params['pid']) && is_numeric($this->params['pid'])){
            //先获取标段类型列表
            $stlist = $this->measureauditact->getCheckedRowbyUID4($_POST['uid'], $this->params['pid']);
            $sectioncheckedlist = array();
            if(!empty($stlist)){
                $i = 0;
                foreach($stlist as $k => $v){
                    //再获取标段名信息
                    $sectionlist = $this->measureauditact->getCheckedRowbyUID5($_POST['uid'], $this->params['pid'],$v['stid']);
                    $sectioncheckedlistarray = array();
                    if(!empty($sectionlist)){
                        $j = 0;
                        foreach($sectionlist as $key => $value){
                            $numStatusArray = $this->numofperact->getLastStatus3($this->params['pid'], $value['pmid']);
                            if (!isset($numStatusArray['currstatus'])) {
                                $numStatusArray['currstatus'] = 'uncheck';
                            }
                            $datatmp = $this->measureauditact->getMyAuditStatus2($numStatusArray['pmid'], $numStatusArray['numpname'], $numStatusArray['times'], $_POST['uid']);
                            if ($datatmp && ($datatmp['mastatus'] == 'checked' || $datatmp['mastatus'] == 'checkno') ) {
                                $pmname = $this->actmeasure->getRowByPmid($value['pmid']);
                                $sectioncheckedlistarray[$j]['pmname'] =  !empty($pmname) ? $pmname['pmname'] : '';
                                $sectioncheckedlistarray[$j]['countNum'] = !empty($datatmp['numpname']) ? $datatmp['numpname'] : 0;
                                $sectioncheckedlistarray[$j]['audittime'] = !empty($datatmp['audittime']) ? date('Y-m-d',$datatmp['audittime']) : '';
                                $sectioncheckedlistarray[$j]['url'] = '/app/rproject/' . $this->params['pid'] . '/section/' . $value['pmid'] . '/detail';
                                $j++;
                            }
                        }
                    }
                    if(!empty($sectioncheckedlistarray)){
                        $stname = $this->contractact->getRowByStid($v['stid']);
                        $sectioncheckedlist[$i]['stname'] = !empty($stname['stname']) ? $stname['stname'] : '';
                        $sectioncheckedlist[$i]['stlist'] = $sectioncheckedlistarray;
                    }
                    $i++;
                }
            }
            echo json_encode(array('status' => TRUE, 'msg' => '', 'sectionlist' => $sectioncheckedlist), JSON_UNESCAPED_UNICODE);
            die();
        }else{
            $status = array('status' => FALSE, 'msg' => '获取已审核标段列表出错');
            echo json_encode($status, JSON_UNESCAPED_UNICODE);
            die();
        }
    }

    //内嵌app页
    public function proDetail() {
        if(isset($_GET['uid']) && is_numeric($_GET['uid'])) {
            if(isset($_GET['approval'])){
                $this->data['approval'] = 1;
            }
            $numStatusArray = $this->numofperact->getLastStatus3($this->params['pid'], $this->params['pmid']);
            if (!isset($numStatusArray['currstatus'])) {
                $numStatusArray['currstatus'] = 'uncheck';
            }
            // 项目名称
            $mpidArray = $this->measureauditact->getAuditProject2($_GET['uid']);
            foreach ($mpidArray as $k1 => $v1) {
                if ($v1['pid'] != $this->params['pid'])
                    $this->data['allproArray'][] = $this->project->getRowByPid($v1['pid']);
            }
            $this->data['currproArray'] = $this->project->getRowByPid($this->params['pid']);
            $this->data['MeasureArray'] = $this->numofperact->getGroupByLastOne($this->params['pmid']);
            $this->data['MeasureArray3'] = array_reverse($this->data['MeasureArray']);
            $measureArray = $this->actmeasure->getRowByPmid($this->params['pmid']);
            foreach ($this->data['MeasureArray'] as $key => $value) {
                if ($measureArray['contracttotal'] > $value['currdone'] && $value['currdone'] > 0) {
                    $this->data['MeasureArray'][$key]['lessTotal'] = round(($value['currdone'] / $measureArray['contracttotal']) * 100);
                } else {
                    $this->data['MeasureArray'][$key]['lessTotal'] = 0;
                }
            }

            // 期数列表
            $tmpArray = $this->numofperact->getGroupByLastOne2($this->params['pmid']);
            foreach ($tmpArray as $k => $v) {
                $intTime = $this->numofperact->getMaxTimes($v['pmid'], $v['numpname'])['times'];
                $nfArray[] = $this->numofperact->getRow($v['pmid'], $v['numpname'], $intTime);
            }
            foreach ($nfArray as $k => $v) {
                if ($v['mpid'] == $numStatusArray['mpid']) {
                    $this->data['mpid'] = $v['mpid'];
                    $this->data['MeasureArray2'][] = $v;
                    $this->data['currnum'] = $v['numpname'];
                } else {
                    $this->data['numArray'][] = $v;
                }
            }
            $measureArray = $this->actmeasure->getRowByPmid($this->params['pmid']);
            foreach ($this->data['MeasureArray2'] as $key => $value) {
                if ($value['mpid'] == $numStatusArray['mpid']) {
                    $this->data['MeasureArray2'][$key]['currstatus'] = $this->statusArray[$value['currstatus']];
                    if ($measureArray['contracttotal'] > $value['currdone'] && $value['currdone'] > 0) {
                        $this->data['MeasureArray2'][$key]['lessTotal'] = round(($value['currdone'] / $measureArray['contracttotal']) * 100);
                    } else {
                        $this->data['MeasureArray2'][$key]['lessTotal'] = 0;
                    }
                }
            }
            $lastRowArray = $this->numofperact->getLastNew2($this->params['pmid']);
            $maxTimes = $this->numofperact->getMaxTimes($lastRowArray['pmid'], $lastRowArray['numpname']);
//        $auditUserArray = $this->measureauditact->getAllAudit($lastRowArray['pmid'], $lastRowArray['numpname'], $maxTimes['times']);
//            $maxtimez = $this->measureauditact->getRowGroupByTimes($numStatusArray['mpid']);
            $maxtimez = $this->numofperact->getRowByMpid($numStatusArray['mpid']);
            $auditUserArray = $this->measureauditact->getRowByMpidTimes($numStatusArray['mpid'], $maxtimez['numpname'], $maxtimez['times']);
            $auditArray = $this->measureauditact->getLastNewRowInfo($lastRowArray['pmid'], $lastRowArray['numpname'], $_GET['uid']);
            if (isset($_POST['act'])) {
                $auditStatusArray = array('checkno', 'checked');
                $myAuditStatus = $this->measureauditact->getMyAuditStatus($lastRowArray['pmid'], $lastRowArray['numpname'], $maxTimes['times'], $_GET['uid']);
                if (in_array($myAuditStatus['mastatus'], $auditStatusArray)) {
                    echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                    die();
                }
            }
            if ($_POST['act'] == 'p') {
                if ($this->measureauditact->setMyAuditPass($auditArray['maid'], $_POST['content'], 1, $_GET['uid'])) {
                    $countAudit = count($auditUserArray);
                    $this->attfile->updateHash($lastRowArray['pmid'], $lastRowArray['numpname'], $maxTimes['times']);
                    if ($auditArray['last'] == 1) {
                        $this->numofperact->updateAuditStatus($lastRowArray['pmid'], $lastRowArray['numpname'], 'checked', $maxTimes['times']);
                        // SMS Start
                        $TenderArray = $this->actmeasure->getRowByPmid($lastRowArray['pmid']);
                        $userProArray = $this->profile->getProWithUid($TenderArray['uid']);
                        if (isset($userProArray) && ($userProArray['mobile'])) {
                            $retval = $this->__auditNotice($userProArray['mobile'], Doo::conf()->SMS_TIPS_PRE . '您好，' . $TenderArray["pmname"] . Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR3"]);
                        }
                        // SMS End
                        echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                        die();
                    } else {
                        if (($countAudit == 2) && ($auditUserArray[1]['last'] == 1) && ($auditUserArray[0]['maid'] == $auditArray['maid'])) {
                            $this->measureauditact->updateMastatus($auditUserArray[1]['maid']);
                            $this->numofperact->updateAuditStatus($lastRowArray['pmid'], $lastRowArray['numpname'], 'checking', $maxTimes['times']);
                            // SMS Start
                            $verifyUserArray = $this->profile->getVerifiedMobile($auditUserArray[1]['auditoruid']);
                            $pmnameArray = $this->actmeasure->getRowByPmid($lastRowArray['pmid']);
                            if (isset($verifyUserArray) && ($verifyUserArray['mobile'])) {// XXXX（标段名），陈特，已审批通过。请您继续审批。
                                $this->__auditNotice($verifyUserArray['mobile'], Doo::conf()->SMS_TIPS_PRE . '您好，' . $pmnameArray["pmname"] . Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR2"]);
                            }
                            // SMS End
                            echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                            die();
                        }
                        if (($countAudit > 2)) {
                            foreach ($auditUserArray as $k => $v) {
                                if ($v['maid'] == $auditArray['maid']) {
                                    if ($k == ($countAudit - 1)) {//如果是最后一个
                                        $this->measureauditact->updateMastatus($auditUserArray[0]['maid']);
                                        // SMS Start
                                        $verifyUserArray = $this->profile->getVerifiedMobile($auditUserArray[0]['auditoruid']);
                                        // var_dump($verifyUserArray);
                                        $pmnameArray = $this->actmeasure->getRowByPmid($auditUserArray[0]['pmid']);
                                        // var_dump($pmnameArray);
                                        // SMS End
                                    } else {
                                        $this->measureauditact->updateMastatus($auditUserArray[$k + 1]['maid']);
                                        // SMS Start
                                        $verifyUserArray = $this->profile->getVerifiedMobile($auditUserArray[$k + 1]['auditoruid']);
                                        // var_dump($verifyUserArray);
                                        $pmnameArray = $this->actmeasure->getRowByPmid($auditUserArray[$k + 1]['pmid']);
                                        // var_dump($pmnameArray);
                                        // SMS End
                                    }
                                    // SMS Start
                                    if (isset($verifyUserArray) && ($verifyUserArray['mobile'])) {// XXXX（标段名），陈特，已审批通过。请您继续审批。
//                                    $retval = $this->__auditNotice($verifyUserArray['mobile'], Doo::conf()->SMS_TIPS_PRE . $pmnameArray["pmname"] . Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR2"]);
                                        $this->__auditNotice($verifyUserArray['mobile'], Doo::conf()->SMS_TIPS_PRE . '您好，' . $pmnameArray["pmname"] . Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR2"]);
//                                        var_dump($pmnameArray["pmname"] . Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR2"]);
//                                        var_dump($retval);
//                                        var_dump($this->sms->getErrors());
                                    }
                                    // SMS End
                                    $this->numofperact->updateAuditStatus($lastRowArray['pmid'], $lastRowArray['numpname'], 'checking', $maxTimes['times']);
                                    echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                                    die();
                                }
                            }
                        }
                    }
                }
            }
            if ($_POST['act'] == 'np') {
                $this->measureauditact->setCheckno($auditArray['maid'], $_POST['content'], 1);
                $this->numofperact->updateAuditStatus($lastRowArray['pmid'], $lastRowArray['numpname'], 'checkno', $maxTimes['times']);
                $this->attfile->updateHash($lastRowArray['pmid'], $lastRowArray['numpname'], $maxTimes['times']);
                // SMS Start
                $TenderArray = $this->actmeasure->getRowByPmid($lastRowArray['pmid']);
                $userProArray = $this->profile->getProWithUid($TenderArray['uid']);
                if (isset($userProArray) && ($userProArray['mobile'])) {// // XXXX（标段名），陈特，已审批通过。请您继续审批。
                    $retval = $this->__auditNotice($userProArray['mobile'], Doo::conf()->SMS_TIPS_PRE . '您好，' . $TenderArray["pmname"] . Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR4"]);
//                var_dump($retval);
//                var_dump($this->sms->getErrors());
//                $this->__auditNotice($userProArray['mobile'], Doo::conf()->SMS_TIPS_PRE . '您好，' . $TenderArray["pmname"] . Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR4"]);
                }
                // SMS End
                echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                die();
            }
            $this->data['pmid'] = $lastRowArray['pmid'];
            $this->data['numpname'] = $lastRowArray['numpname'];
            $this->data['times'] = $lastRowArray['times'];
            foreach ($auditUserArray as $key => $value) {
                $strAvatar = $this->auth->getAvatar($value['auditoruid']);
                if ($value['auditoruid'] == $_GET['uid']) {
                    $this->data['mastatus'] = $value['mastatus'];
                    $this->data['maid'] = $value['maid'];
                    $name = $this->profile->getProWithUid($value['auditoruid'])['name'].'（我）';
                }else{
                    $name = $this->profile->getProWithUid($value['auditoruid'])['name'];
                }
                if ($value['mastatus'] == 'uncheck') {
                    $statushtml = '<div class="approvalImg"><img class="pa2ss" src="'. $strAvatar .'">'.$name.'<b class="colGray fR">待审</b></div>';
                }
                if ($value['mastatus'] == 'checking') {
                    $statushtml = '<div class="approvalImg"><img class="wait" src="'. $strAvatar .'">'.$name.'<b class="colOrange fR">审批中</b></div>';
                }
                if ($value['mastatus'] == 'checked') {
                    $statushtml = '<div class="approvalImg"><img class="pass" src="'. $strAvatar .'">'.$name.'<b class="colGreen fR">审批完成（' . date('Y-m-d', $value['audittime']) . '）</b></div>';
                }
                if ($value['mastatus'] == 'checkno') {
                    $statushtml = '<div class="approvalImg"><img class="unpass" src="'. $strAvatar .'">'.$name.'<b class="colRed fR">审批不通过（' . date('Y-m-d', $value['audittime']) . '）</b></div>';
                }
                $auditUserArray[$key]['statushtml'] = $statushtml;
            }
            $strAvatar = $this->auth->getAvatar($measureArray['uid']);
            $orginArrayname = $this->profile->getProWithUid($measureArray['uid'])['name'];
            $attfileArray = $this->attfile->getFirstFile($lastRowArray['pmid'], $lastRowArray['numpname'], $lastRowArray['times']);
            $orginArray['time'] = date('Y-m-d', $attfileArray['intime']);
            $orginArray['statushtml'] = '<div class="approvalImg"><img class="pass" src="'. $strAvatar .'">'.$orginArrayname.'<b class="colGreen fR">原报上报（' . $orginArray['time'] . '）</b></div>';
            $this->data['auditArray'] = $auditUserArray;
            $this->data['orginArray'] = $orginArray;

            $this->data['uid'] = $_GET['uid'];
            $this->data['pmid'] = $this->params['pmid'];
            $this->data['pid'] = $this->params['pid'];
            $this->data['mpid'] = $numStatusArray['mpid'];
            $this->render('r-project-section-detail-APP', $this->data, TRUE);
        }else{
            exit('error：无参数无法访问本页');
        }
    }

    public function getSignPic(){
        if(isset($_POST['uid']) && is_numeric($_POST['uid'])){
            $userArray = $this->profile->getProWithUid($_POST['uid']);
            if(!empty($userArray)){
                $signPic = $userArray['signpath'];
                $status = array('status' => TRUE, 'msg' => '', 'signpic' => Doo::conf()->APP_URL . $signPic);
                echo json_encode($status, JSON_UNESCAPED_UNICODE);
                die();
            }
        }
        $status = array('status' => FALSE, 'msg' => '参数有误');
        echo json_encode($status, JSON_UNESCAPED_UNICODE);
        die();
    }

    public function uploadSignPic(){
        if(isset($_POST['uid']) && is_numeric($_POST['uid']) && isset($_POST['signbase64'])){
            $userArray = $this->profile->getProWithUid($_POST['uid']);
            if(!empty($userArray)){
                $img = base64_decode($_POST['signbase64']);
                $dir = 'global/signpath';
                $fileName = date("YmdHis") . '_' . floor(microtime() * 1000) . '_' . self::createRandomCode(8);
                $virtualPath = "$dir/php_sign_$fileName.jpg";
                $a = file_put_contents(Doo::conf()->SITE_PATH .$virtualPath,$img);
//                move_uploaded_file($_FILES['sign']["tmp_name"], Doo::conf()->SITE_PATH .$virtualPath);
                if($a){
                    $this->profile->setSignPath($_POST['uid'], $virtualPath);
                    $status = array('status' => TRUE, 'msg' => '');
                    echo json_encode($status, JSON_UNESCAPED_UNICODE);
                    die();
                }else{
                    $status = array('status' => FALSE, 'msg' => '上传签名照失败');
                    echo json_encode($status, JSON_UNESCAPED_UNICODE);
                    die();
                }

            }
        }
        $status = array('status' => FALSE, 'msg' => '参数有误');
        echo json_encode($status, JSON_UNESCAPED_UNICODE);
        die();
    }

//二维数组去掉重复值 并保留键值
    function array_unique_fb($array2D)
    {
        $key = array();
        foreach ($array2D as $k => $v) {
            if (empty($key))
                $key = array_keys($v); //记录数组的KEY
            $v = join(",", $v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            $temp[$k] = $v;
        }
        $temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
        foreach ($temp as $k => $v) {
            $array = explode(",", $v); //再将拆开的数组重新组装
            foreach ($array as $i => $t) {
                $temp2[$k] = !empty($temp2[$k]) ? array_merge($temp2[$k], array("{
        $key[$i]}" => $t)) : array("{
        $key[$i]}" => $t); //依次添加到新的数组中去
            }
        }
        return $temp2;
    }

    function unique_arr($array2D, $stkeep = false, $ndformat = true)
    {
        // 判断是否保留一级数组键 (一级数组键可以为非数字)
        if ($stkeep)
            $stArr = array_keys($array2D);
        // 判断是否保留二级数组键 (所有二级数组键必须相同)
        if ($ndformat)
            $ndArr = array_keys(end($array2D));
        //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        foreach ($array2D as $v) {
            $v = join(",", $v);
            $temp[] = $v;
        }
        //去掉重复的字符串,也就是重复的一维数组
        $temp = array_unique($temp);
        //再将拆开的数组重新组装
        foreach ($temp as $k => $v) {
            if ($stkeep)
                $k = $stArr[$k];
            if ($ndformat) {
                $tempArr = explode(",", $v);
                foreach ($tempArr as $ndkey => $ndval) {
                    $output[$k][$ndArr[$ndkey]] = $ndval;
                }
            } else {
                $output[$k] = explode(",", $v);
            }
        }
        return $output;
    }


    /**
     *   。
     *   标段ID，期号
     */
    private function __auditNotice($mobile, $text)
    {
        $smsSwitch = $this->aconfig->getOne(array('select' => 'smsSwitch', 'asArray' => TRUE))['smsSwitch'];
        if ($smsSwitch > 0)
            return $this->sms->sendSms($mobile, $text);

    }

    function upfile($fildname, $param = 'doc, docx, xls, xlsx, png, zip')
    {
        return $this->att->uploadMut($fildname, $param);
    }

    function upItemFile($fildname, $param = 'doc, docx, xls, xlsx, png, zip')
    {
        $this->att->setUploadDir();
        return $this->att->uploadMut($fildname, $param);
    }

    /**
     *   根据标段ID获取标段是否已经被删除的提示
     *   标段ID
     */
    public function getCountPmid()
    {
        if (isset($this->params['tenderid'])) {
            $isexist = $this->actmeasure->getCountPmid($this->params['tenderid']);
            if ($isexist > 0) {
                echo json_encode(array('status' => TRUE, 'msg' => '', 'info' => null), JSON_UNESCAPED_UNICODE);
                die();
            } else {
                echo json_encode(array('status' => 'FALSE', 'msg' => '该项目[XXX]在云端已被删除，点击“确定”后，可手动删除该项目'), JSON_UNESCAPED_UNICODE);
                die();
            }
        } else {
            $this->msg(0, '获取标段是否存在参数错误');
        }
    }

    function getFileupErrorNo()
    {
        return $this->att->error();
    }

    function Signout()
    {
        session_destroy();
    }

    function isLoggedIn()
    {
        return isset($_SESSION['user_id']);
    }

    function generateFormHash($salt)
    {
        $hash = md5(mt_rand(1, 1000000) . $salt);
        $_SESSION['csrf_hash'] = $hash;
        return $hash;
    }

    function isValidFormHash($hash)
    {
        return $_SESSION['csrf_hash'] === $hash;
    }

    /**
     * 随机字符串函数
     * @param $password 密码
     * @param $random 随机数
     */
    function random($length, $chars = '0123456789')
    {
        $hash = '';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

    /**
     * 生成随机字符串
     * @param string $lenth 长度
     * @return string 字符串
     */
    function create_randomstr($lenth = 6)
    {
        return $this->random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
    }

    function dir_create($path, $mode = 0777)
    {
        if (is_dir($path))
            return TRUE;
        $path = $this->dir_path($path);
        $parent = dirname($path);
        if (!is_dir($parent))
            @mkdir($parent, 0777, true);
        @mkdir($path, 0777, true);
        return is_dir($path);
    }

    function dir_path($path)
    {
        $path = str_replace('\\', '/', $path);
        if (substr($path, -1) != '/')
            $path = $path . '/';
        return $path;
    }

    function msg($isTrue = 0, $msg = null, $retmsg = null)
    {
        if ($isTrue > 0) {
            echo json_encode(array('status' => 'TRUE', 'msg' => ''), JSON_UNESCAPED_UNICODE);
            die();
        } else {
            echo json_encode(array('status' => 'FALSE', 'msg' => $msg), JSON_UNESCAPED_UNICODE);
            die();
        }
    }

    /*     * ************************************************************
     *  生成指定长度的随机码。
     *  @param int $length 随机码的长度。
     *  @access public
     * ************************************************************ */

    function createRandomCode($length)
    {
        $randomCode = "";
        $randomChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for ($i = 0; $i < $length; $i++) {
            $randomCode .= $randomChars{mt_rand(0, 35)};
        }
        return $randomCode;
    }

    public function scanValidate(){
        if(isset($_POST['app']) && $_POST['app'] == 'jlzfAppScanValidate'){
            $uid = $this->__hashids->decode($_POST['user'])[0];
            if(!empty($uid) && is_numeric($uid)){
                if($this->auth->getWebToken($uid) == $_POST['token']){
                    $userArray = $this->profile->getProWithUid($uid);
                    $avatarStr = $userArray['avatar'];
                    if (isset($userArray['userid'])) {
                        $msgArray = array('uid' => $uid, 'name' => $userArray['name'], 'ucompany' => $userArray['company'], 'jobtitle' => $userArray['jobs'], 'avatar' => Doo::conf()->APP_URL . $avatarStr, 'server' => $_SERVER['HTTP_HOST'], 'token' => $_POST['token']);
                        echo json_encode(array('status' => TRUE, 'msg' => '', 'userinfo' => $msgArray), JSON_UNESCAPED_UNICODE);
                        exit;
                    }else{
                        echo json_encode(array('status' => FALSE, 'msg' => '不存在该用户，请联系我们'), JSON_UNESCAPED_UNICODE);
                        exit;
                    }
                }else{
                    echo json_encode(array('status' => FALSE, 'msg' => '请检查二维码是否正确或过期，重新登录web端获取最新二维码或使用账号密码登录'), JSON_UNESCAPED_UNICODE);
                    exit;
                }
            }
        }
        return 'http://a.app.qq.com/o/simple.jsp?pkgname=cn.com.smartcost.jlzf';
    }

    public function ScanLogin(){
        if(isset($_POST['app']) && $_POST['app'] == 'jlzfAppScanLogin'){
            $status = $this->auth->checkLoginByScan($_POST['uid'],$_POST['token']);
            if($status){
                $uinfo = $this->auth->getUinfo();
                $userArray = $this->profile->getProWithUid($uinfo['uid']);
                $avatarStr = $userArray['avatar'];
                if (isset($userArray['userid'])) {
                    $apptoken = sha1($this->create_randomstr() . $uinfo['uid']);
                    $this->auth->AppLoginToken($uinfo['uid'],$apptoken);
                    $msgArray = array('uid' => $uinfo['uid'], 'name' => $userArray['name'], 'email' => $uinfo['uemail'], 'ucompany' => $userArray['company'], 'jobtitle' => $userArray['jobs'], 'avatar' => Doo::conf()->APP_URL . $avatarStr, 'token' => $apptoken);
                    echo json_encode(array('status' => TRUE, 'msg' => '', 'userinfo' => $msgArray), JSON_UNESCAPED_UNICODE);
                    die;
                }
            }else{
                echo json_encode(array('status' => FALSE, 'msg' => '请检查二维码是否正确或过期，重新登录web端获取最新二维码或使用账号密码登录'), JSON_UNESCAPED_UNICODE);
                exit;
            }
        }
        return 'http://a.app.qq.com/o/simple.jsp?pkgname=cn.com.smartcost.jlzf';
    }

    public function autoScanLogin(){
        if ($this->auth->CheckAppLoginToken($_POST['uid'], $_POST['token'])) {
            $uinfo = $this->auth->getUinfo();
            if (isset($uinfo['isstop']) && $uinfo['isstop'] > 0) {
                echo json_encode(array('status' => FALSE, 'msg' => '账号未启用'), JSON_UNESCAPED_UNICODE);
                die;
            }
            if (isset($uinfo['uid'])) {
                $userArray = $this->profile->getProWithUid($uinfo['uid']);
                $avatarStr = $userArray['avatar'];
                if (isset($userArray['userid'])) {
//                    $this->auth->setUid($uinfo['uid']);
                    $msgArray = array('uid' => $uinfo['uid'], 'name' => $userArray['name'], 'email' => $uinfo['uemail'], 'ucompany' => $userArray['company'], 'jobtitle' => $userArray['jobs'], 'avatar' => Doo::conf()->APP_URL . $avatarStr);
                    echo json_encode(array('status' => TRUE, 'msg' => '', 'userinfo' => $msgArray), JSON_UNESCAPED_UNICODE);
                    die;
                }
            }

        } else {
            echo json_encode(array('status' => FALSE, 'msg' => '您的登录信息已过期，请重新登录'), JSON_UNESCAPED_UNICODE);
            die;
        }
    }


//    function checkVersion($version)
//    {
//        preg_match();
//    }

}

?>
