<?php
//ini_set('display_errors', on);
Doo::loadClass('auth');
Doo::loadClass('attfile');
Doo::loadClass('profile');
Doo::loadClass('project');
Doo::loadClass('contractact');
Doo::loadClass('actmeasure');
Doo::loadClass('numofperact');
Doo::loadClass('measureauditact');
Doo::loadClass('sign');
Doo::loadClass('sms');
Doo::loadModelAt('aconfig', 'admin');
//define('FPDF_FONTPATH','protected/class/fpdf1.5/font/');
//Doo::loadClass('fpdf');

/* * proDetail
 * MainController
 * Feel free to delete the methods and replace them with your own code.
 *
 * @author darkredz
 */

class SignController extends DooController
{

    private $aconfig, $data, $sms, $sign, $auth, $attfile, $profile, $project, $contractact, $actmeasure, $measureauditact, $numofperact, $statusArray = array('uncheck' => '<span class = "colGray">未审批</span>', 'checking' => '<span class = "colOrange">审批中</span>', 'checked' => '<span class = "colGreen">审批通过</span>', 'checkno' => '<span class = "colRed">审批不通过</span>');

    public function beforeRun($resource, $action)
    {
        if ($this->auth->getUid()) {
            $uGroups = $this->profile->getProWithUid($this->auth->getUid());
            $falg = Doo::acl()->isAllowed($uGroups['groups'], $resource, $action);
            if (!$falg)
                return Doo::acl()->defaultFailedRoute;
        } else {
            return Doo::acl()->defaultFailedRoute;
        }
    }

    public function __construct()
    {
        $this->aconfig = new AConfig();
        $this->auth = new Auth();
        $this->attfile = new attFile();
        $this->profile = new Profile();
        $this->project = new Project();
        $this->contractact = new Contractact();
        $this->actmeasure = new actMeasure();
        $this->numofperact = new NumofperAct();
        $this->measureauditact = new MeasureauditAct();
        $this->sign = new Signn();
        $this->sms = new Sms(Doo::conf()->SMS_URL, Doo::conf()->SMS_AUTHKEY);
//        $this->pdf = new FPDF('P','mm','A4');
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->data['currChannle'] = 'sign';
        $this->data['user'] = $this->profile->getProWithUid($this->auth->getUid());
        $mpidArray = $this->measureauditact->getAuditProject2($this->auth->getUid());
        $this->data['numofchecking'] = 0;
        if (isset($mpidArray[0]['pid'])) {
            foreach ($mpidArray as $key => $value) {
                // 审批操作按照时间排序多标段
                $this->data['numofchecking'] += $this->measureauditact->getCountMyChecking($value['pid'], $this->auth->getUid());
            }
        }
        if (!isset($this->data['numofchecking']) || $this->data['numofchecking'] == 0) {
            $this->data['numofchecking'] = null;
        }

        $signSwitch = $this->aconfig->getOne(array('select' => 'signswitch', 'asArray' => TRUE))['signswitch'];
        if ($signSwitch == 0)
            exit('未开启在线签名功能');

        $this->data['signSwitch'] = $signSwitch;

        //获取需要您签署的数目
        $this->data['needSignNum'] = $this->sign->getNeedSignNumbyUid($this->auth->getUid()) != 0 ? $this->sign->getNeedSignNumbyUid($this->auth->getUid()) : '';

        //获取桌面版本
        $this->getsoftware();
    }

    function getsoftware(){
        $StrJson = ($this->aconfig->getOne(array('select' => 'upgradeinfo', 'asArray' => TRUE))['upgradeinfo']);
        $upgradeinfo = json_decode($StrJson, true);
        if ($upgradeinfo) {
            $this->data['version'] = $upgradeinfo['version'];
            $this->data['download'] = $upgradeinfo['download'];
        }
    }

    /**
     *
     * @return type
     */
    public function index()
    {

        //获取我发起的签署数目
        $this->data['mySignNum'] = $this->sign->getMySignNumbyUid($this->auth->getUid());

        //获取关于我的正在签署数目
        $this->data['doingSignNum'] = $this->sign->getDoingSignNumbyUid($this->auth->getUid());

        //获取关于我的完成签署数目
        $this->data['doneSignNum'] = $this->sign->getDoneSignNumbyUid($this->auth->getUid());

        $this->data['launchsign'] = $this->aconfig->getOne(array('select' => 'launchsignswitch', 'asArray' => TRUE))['launchsignswitch'];

        $this->render('sign-index', $this->data, TRUE);
    }

    public function signNeedList(){

        $needlist = array();
        $searchsql = 'sid in(select `jl_sign_audit`.sid from `jl_sign_audit` where `jl_sign_audit`.status="checking" and `jl_sign_audit`.audituid='.$this->auth->getUid().')';
        $projectlist = $this->sign->getSignGroupByProject($searchsql);
        if(!empty($projectlist)){
            foreach($projectlist as $k => $v){
                $projectmsg = $this->project->getRowByPid($v['project']);
                $needlist[$k]['project'] = $projectmsg['pname'];
                $needlist[$k]['tlist'] = array();

                $tenderlist = $this->sign->getSignGroupByTender($v['project'],$searchsql);
                if(!empty($tenderlist)) {
                    foreach ($tenderlist as $tk => $tv) {
                        $tendermsg = $this->actmeasure->getRowByPmid($tv['tender']);
                        $needlist[$k]['tlist'][$tk]['tender'] = $tendermsg['pmname'];
                        $needlist[$k]['tlist'][$tk]['plist'] = array();

                        $phasenolist = $this->sign->getSignGroupByPhaseno($tv['tender'],$searchsql);
                        if(!empty($phasenolist)) {
                            foreach ($phasenolist as $pk => $pv) {
//                                $phasenomsg = $this->numofperact->getCurrStatus($pv['phaseno']);
                                $needlist[$k]['tlist'][$tk]['plist'][$pk]['phaseno'] = $pv['phaseno'];
                                $needlist[$k]['tlist'][$tk]['plist'][$pk]['signlist'] = array();

                                $signlist = $this->sign->getSignList($searchsql.' and (status="checking" or status="back") and tender='.$tv['tender'].' and phaseno='.$pv['phaseno'], '0,1000');
                                if(!empty($signlist)) {
                                    foreach ($signlist as $sk => $sv) {
                                        $needlist[$k]['tlist'][$tk]['plist'][$pk]['signlist'][$sk]['sid'] = $sv['sid'];
                                        $needlist[$k]['tlist'][$tk]['plist'][$pk]['signlist'][$sk]['name'] = $sv['name'];
                                        $needlist[$k]['tlist'][$tk]['plist'][$pk]['signlist'][$sk]['auditlist'] = $this->sign->getSignAuditlist($sv['sid']);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        $this->data['needlist'] = $needlist;
        $this->render('sign-list-need_sign',$this->data, TRUE);
    }

    public function signNeedView(){
        if(!isset($this->params['sid']) || !is_numeric($this->params['sid'])){
            exit('没有报表参数');
        }
        $issign = $this->sign->getisSignbySidUid($this->params['sid'],$this->auth->getUid());
        if(empty($issign)){
            exit('不是当前签署人无法访问本页');
        }

        if(isset($_POST['status'])){
            //终止签署
            if($_POST['status'] == 'stop'){
                $result = $this->sign->updateSignStatusAndTime($this->params['sid'],'stop',time());
                $signAudit = $this->sign->getOneSignAudit($this->params['sid'],$this->auth->getUid());
                $result2 = $this->sign->updateSignAudit($signAudit['satid'],'stop',time());
                if($result && $result2){
                    // SMS Start
                    $signArray = $this->sign->getOneSignbysid($this->params['sid']);
                    $pmname = $this->actmeasure->getRowByPmid($signArray['tender']);
                    $userProArray = $this->profile->getProWithUid($signArray['audituid']);
                    if (isset($userProArray) && !empty($userProArray['mobile'])) {
                        $sendarr1 = '“' .$pmname['pmname'].'”的“'. $signArray["name"] .'”';
                        $sendarr2 = str_replace('【','',$sendarr1);
                        $sendmsg = str_replace('】','',$sendarr2);
                        $retval = $this->__auditNotice($userProArray['mobile'], Doo::conf()->SMS_TIPS_PRE . $sendmsg .Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR6"]);
                    }
                    // SMS End
                    echo json_encode(array('code' => 200, 'url' => '/sign/list'));
                    exit;
                }
                echo json_encode(array('code' => 400, 'msg' => '终止签署失败'));
                exit;
            }elseif($_POST['status'] == 'back'){
                $signauditlist = $this->sign->getSignAuditList($this->params['sid']);
                $change = -1;
                foreach($signauditlist as $k => $v){
                    if($v['status'] == 'checking' && $k != 0) {
                        $change = $k-1;
                        break;
                    }
                }
                if($change != -1){
                    $result = $this->sign->updateSignStatusAndTime($this->params['sid'],'back',time());
                    $signAudit = $this->sign->getOneSignAudit($this->params['sid'],$this->auth->getUid());
                    $result3 = $this->sign->updateSignAudit($signAudit['satid'],'uncheck',0);
                    $result2 = $this->sign->updateSignAudit($signauditlist[$change]['satid'],'checking',0);
                    if($result && $result2 && $result3){
                        //删除上一个签名者的所有签名
                        $signattlist = $this->sign->getSignAttList($this->params['sid']);
                        foreach($signattlist as $key => $value){
                            $sign2 = new SignAuditAtt();
                            $sign2->audituid = $signauditlist[$change]['audituid'];
                            $sign2->said = $value['said'];
                            $sign2->delete();
                        }

                        // SMS Start
                        $signArray = $this->sign->getOneSignbysid($this->params['sid']);
                        $pmname = $this->actmeasure->getRowByPmid($signArray['tender']);
                        $userProArray = $this->profile->getProWithUid($signauditlist[$change]['audituid']);
                        if (isset($userProArray) && !empty($userProArray['mobile'])) {
                            $sendarr1 = '“' .$pmname['pmname'].'”的“'. $signArray["name"] .'”';
                            $sendarr2 = str_replace('【','',$sendarr1);
                            $sendmsg = str_replace('】','',$sendarr2);
                            $retval = $this->__auditNotice($userProArray['mobile'], Doo::conf()->SMS_TIPS_PRE . $sendmsg .Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR7"]);
                        }
                        // SMS End
                        echo json_encode(array('code' => 200, 'url' => '/sign/onlist'));
                        exit;
                    }
                }
                echo json_encode(array('code' => 400, 'msg' => '退回签署失败'));
                exit;
            }
        }

        //获取报表信息
        $signmsg = $this->sign->getOneSignbysid($this->params['sid']);
        //获取项目名，标段名，标段期数
        $project = $this->project->getRowByPid($signmsg['project']);
        $tender = $this->actmeasure->getRowByPmid($signmsg['tender']);
//        $phaseno = $this->numofperact->getCurrStatus($signmsg['phaseno']);

        $signmsg['project'] = $project['pname'];
        $signmsg['tender'] = $tender['pmname'];
//        $signmsg['phaseno'] = $phaseno['numpname'];


        //获取签署人列表
        $firstsign = 0;
        $signauditlist = $this->sign->getSignAuditList($this->params['sid']);
        if(!empty($signauditlist)){
            foreach($signauditlist as $k => $v){
                //获取签署人头像
                $signauditlist[$k]['index'] = $k+1;
                $signauditlist[$k]['avatar'] = $this->auth->getAvatar($v['audituid']);
                if($this->auth->getUid() == $v['audituid'] && $k == 0){
                    $firstsign = 1;
                }
            }
        }

        //获取报表图片
        $maxwidth = 794; //默认图片最大宽度   a4
        $maxheight = 1123; //默认图片最大高度  a4
        if(!empty($signmsg['widhei'])){
            $widhei = explode('_', $signmsg['widhei']);
            $style = $widhei[0].'mm '.$widhei[1].'mm';
        }else{
            $style = '210mm 297mm';
        }
        $signattlist = $this->sign->getSignAttList($this->params['sid']);
        if(!empty($signattlist)){
            foreach($signattlist as $sak => $sav){
                $signattlist[$sak]['auditatt'] = $this->sign->getSignAuditAttList($sav['said']);
                if($sak == 0){
                    $imgmsg = getimagesize(Doo::conf()->APP_URL.$sav['filepath']);
                    $maxwidth = $imgmsg[0];
                    $maxheight = $imgmsg[1];
                }
            }
        }

        $this->data['signmsg'] = $signmsg;
        $this->data['auditlist'] = $signauditlist;
        $this->data['attlist'] = $signattlist;
        $this->data['picpath'] = $this->auth->getSignpath($this->auth->getUid());
        $this->data['signsid'] = $this->params['sid'];
        $this->data['maxwidth'] = $maxwidth;
        $this->data['maxheight'] = $maxheight;
        $this->data['style'] = $style;
        $this->data['firstsign'] = $firstsign;
        $this->render('sign-view-signer_sign',$this->data, TRUE);
    }

    public function signDone(){
        if(!isset($_POST['sid']) || !is_numeric($_POST['sid'])){
            echo json_encode(array('code' => 400, 'msg' => '没有报表参数'));
            exit;
        }

        if(!isset($_POST['path']) || empty($_POST['path'])){
            echo json_encode(array('code' => 400, 'msg' => '没有签名图片'));
            exit;
        }

        //改变签署状态并判断报表是否签署完成或传到下一个签署人签署
        $signAudit = $this->sign->getOneSignAudit($_POST['sid'],$this->auth->getUid());
        $result = $this->sign->updateSignAudit($signAudit['satid'],'checked');

        foreach($_POST['said'] as $satk => $satv){
            $sign3 = new Signn();
            $sign3->insertSignAuditAtt($this->auth->getUid(),$satv,$_POST['path'],$_POST['position'][$satk]);
        }
        if($result){
            $sign2 = new Signn();
            $signAuditList = $sign2->getSignAuditList($_POST['sid']);
            $flag = true;
            foreach($signAuditList as $k => $v){
                if($v['status'] == 'uncheck'){
                    $sign2->updateSignAudit($v['satid'],'checking');
                    $flag = false;
                    //发送签署短信
                    // SMS Start
                    $signArray = $this->sign->getOneSignbysid($_POST['sid']);
                    $pmname = $this->actmeasure->getRowByPmid($signArray['tender']);
                    $userProArray = $this->profile->getProWithUid($v['audituid']);
                    if (isset($userProArray) && !empty($userProArray['mobile'])) {
                        $sendarr1 = '“' .$pmname['pmname'].'”的“'. $signArray["name"] .'”';
                        $sendarr2 = str_replace('【','',$sendarr1);
                        $sendmsg = str_replace('】','',$sendarr2);
                        $retval = $this->__auditNotice($userProArray['mobile'], Doo::conf()->SMS_TIPS_PRE . $sendmsg .Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR5"]);
                    }
                    // SMS End
                    break;
                }
            }
            if($flag){
                $this->sign->updateSignStatus($_POST['sid']);
                echo json_encode(array('code' => 200, 'url' => '/sign/view/'.$_POST['sid'].'?status=done'));
                exit;
            }else{
                $this->sign->updateSignStatusAndTime($_POST['sid'],'checking',0);
                echo json_encode(array('code' => 200, 'url' => '/sign/view/'.$_POST['sid'].'?status=doing'));
                exit;
            }
        }else{
            echo json_encode(array('code' => 400, 'msg' => '签署失败'));
            exit;
        }

    }

    public function signMyList(){
        Doo::loadHelper('DooPager');
        $pagestr = '';
        $sqlstr = ' 1';
        $this->data['project'] = '';
        $this->data['tender'] = '';
        $this->data['phaseno'] = '';

        //获取项目信息
        $searchsql = 'audituid='.$this->auth->getUid();
        $itemlist = $this->sign->getSignGroupByProject($searchsql);
        if(!empty($itemlist)){
            foreach($itemlist as $ik => $iv){
                $itemmsg = $this->project->getRowByPid($iv['project']);
                $itemlist[$ik]['pname'] = $itemmsg['pname'];
            }
        }

        if(isset($this->params['pid']) && is_numeric($this->params['pid'])){
            $this->data['project'] = $this->params['pid'];
            $pagestr .= '/project/'.$this->params['pid'];
            $sqlstr .= ' and project='.$this->params['pid'];
            //获取标段信息
            $tenderlist = $this->sign->getSignGroupByTender($this->params['pid'],$searchsql);
            if(!empty($tenderlist)){
                foreach($tenderlist as $tk => $tv){
                    $tendermsg = $this->actmeasure->getRowByPmid($tv['tender']);
                    $tenderlist[$tk]['pmname'] = $tendermsg['pmname'];
                }
            }

            if(isset($this->params['pmid']) && is_numeric($this->params['pmid'])){
                $this->data['tender'] = $this->params['pmid'];
                $pagestr .= '/tender/'.$this->params['pmid'];
                $sqlstr .= ' and tender='.$this->params['pmid'];
                //获取期数信息
                $phasenolist = $this->sign->getSignGroupByPhaseno($this->params['pmid'],$searchsql);
                if(!empty($phasenolist)){
                    foreach($phasenolist as $pk => $pv){
//                        $phasenomsg = $this->numofperact->getCurrStatus($pv['phaseno']);
                        $phasenolist[$pk]['numpname'] = $pv['phaseno'];
                    }
                }

                if(isset($this->params['mpid']) && is_numeric($this->params['mpid'])){
                    $this->data['phaseno'] = $this->params['mpid'];
                    $pagestr .= '/phaseno/'.$this->params['mpid'];
                    $sqlstr .= ' and phaseno='.$this->params['mpid'];
                }
            }
        }

        $totalArchive = $this->sign->getMySignNumbyUid($this->auth->getUid(),$sqlstr);
        $pager = new DooPager(Doo::conf()->APP_URL . 'sign/mylist'.$pagestr.'/page', $totalArchive, 10, 100);
        $pager->setCss('', 'disabled', 'active');
        if (isset($this->params['pindex']))
            $pager->paginate(intval($this->params['pindex']));
        else
            $pager->paginate(1);
        if ($pager->limit != ' -10,10')
            $mylist = $this->sign->getMySignListbyUid($this->auth->getUid(), $sqlstr, $pager->limit);
        if(isset($mylist) && !empty($mylist)){
            foreach($mylist as $k => $v){
                //获取项目名，标段名，标段期数
                $project = $this->project->getRowByPid($v['project']);
                $tender = $this->actmeasure->getRowByPmid($v['tender']);
//                $phaseno = $this->numofperact->getCurrStatus($v['phaseno']);

                $mylist[$k]['project'] = $project['pname'];
                $mylist[$k]['tender'] = $tender['pmname'];
//                $mylist[$k]['phaseno'] = $phaseno['numpname'];
            }
        }
        $this->data['mylist'] = isset($mylist) ? $mylist : '';
        $this->data['itemlist'] = $itemlist;
        $this->data['tenderlist'] = isset($tenderlist) ? $tenderlist : '';
        $this->data['phasenolist'] = isset($phasenolist) ? $phasenolist : '';
        $this->data['pager'] = $pager->output;
        $this->render('sign-list-my_create',$this->data, TRUE);
    }

    public function signChangeShare(){
        if(!isset($_GET['status']) || !isset($_GET['sid'])){
            echo json_encode(array('code' => '400', 'msg' => '请传递正确的参数'));
            exit;
        }
        $status = $_GET['status'] == "true" ? 1 : 0;
        $result = $this->sign->updateSignShareStatus($status,$_GET['sid']);
        if($result){
            echo json_encode(array('code' => '200', 'status' => $status));
            exit;
        }else{
            echo json_encode(array('code' => '400', 'msg' => '无法分享'));
            exit;
        }
        exit;
    }

    public function signOnList(){
        Doo::loadHelper('DooPager');
        $pagestr = '';
        $sqlstr = ' 1';
        $this->data['project'] = '';
        $this->data['tender'] = '';
        $this->data['phaseno'] = '';

        //获取项目信息
        $searchsql = '(status="checking" or status="back") and sid in(select `jl_sign_audit`.sid from `jl_sign_audit` where `jl_sign_audit`.audituid='.$this->auth->getUid().')';
        $itemlist = $this->sign->getSignGroupByProject($searchsql);
        if(!empty($itemlist)){
            foreach($itemlist as $ik => $iv){
                $itemmsg = $this->project->getRowByPid($iv['project']);
                $itemlist[$ik]['pname'] = $itemmsg['pname'];
            }
        }

        if(isset($this->params['pid']) && is_numeric($this->params['pid'])){
            $this->data['project'] = $this->params['pid'];
            $pagestr .= '/project/'.$this->params['pid'];
            $sqlstr .= ' and project='.$this->params['pid'];
            //获取标段信息
            $tenderlist = $this->sign->getSignGroupByTender($this->params['pid'],$searchsql);
            if(!empty($tenderlist)){
                foreach($tenderlist as $tk => $tv){
                    $tendermsg = $this->actmeasure->getRowByPmid($tv['tender']);
                    $tenderlist[$tk]['pmname'] = $tendermsg['pmname'];
                }
            }

            if(isset($this->params['pmid']) && is_numeric($this->params['pmid'])){
                $this->data['tender'] = $this->params['pmid'];
                $pagestr .= '/tender/'.$this->params['pmid'];
                $sqlstr .= ' and tender='.$this->params['pmid'];
                //获取期数信息
                $phasenolist = $this->sign->getSignGroupByPhaseno($this->params['pmid'],$searchsql);
                if(!empty($phasenolist)){
                    foreach($phasenolist as $pk => $pv){
//                        $phasenomsg = $this->numofperact->getCurrStatus($pv['phaseno']);
                        $phasenolist[$pk]['numpname'] = $pv['phaseno'];
                    }
                }

                if(isset($this->params['mpid']) && is_numeric($this->params['mpid'])){
                    $this->data['phaseno'] = $this->params['mpid'];
                    $pagestr .= '/phaseno/'.$this->params['mpid'];
                    $sqlstr .= ' and phaseno='.$this->params['mpid'];
                }
            }
        }

        $totalArchive = $this->sign->getDoingSignNumbyUid($this->auth->getUid(),$sqlstr);
        $pager = new DooPager(Doo::conf()->APP_URL . 'sign/onlist'.$pagestr.'/page', $totalArchive, 10, 100);
        $pager->setCss('', 'disabled', 'active');
        if (isset($this->params['pindex']))
            $pager->paginate(intval($this->params['pindex']));
        else
            $pager->paginate(1);
        if ($pager->limit != ' -10,10')
            $onlist = $this->sign->getDoingSignListbyUid($this->auth->getUid(), $sqlstr, $pager->limit);
        if(isset($onlist) && !empty($onlist)){
            foreach($onlist as $k => $v){
                //获取项目名，标段名，标段期数
                $project = $this->project->getRowByPid($v['project']);
                $tender = $this->actmeasure->getRowByPmid($v['tender']);
//                $phaseno = $this->numofperact->getCurrStatus($v['phaseno']);

                $onlist[$k]['project'] = $project['pname'];
                $onlist[$k]['tender'] = $tender['pmname'];
//                $onlist[$k]['phaseno'] = $phaseno['numpname'];
                $onlist[$k]['auditlist'] = $this->sign->getSignAuditList($v['sid']);
            }
        }
        $this->data['onlist'] = isset($onlist) ? $onlist : '';
        $this->data['itemlist'] = $itemlist;
        $this->data['tenderlist'] = isset($tenderlist) ? $tenderlist : '';
        $this->data['phasenolist'] = isset($phasenolist) ? $phasenolist : '';
        $this->data['pager'] = $pager->output;
        $this->render('sign-list-on_sign',$this->data, TRUE);
    }

    public function signDoneList(){
        Doo::loadHelper('DooPager');
        $pagestr = '';
        $sqlstr = ' 1';
        $this->data['project'] = '';
        $this->data['tender'] = '';
        $this->data['phaseno'] = '';

        //获取项目信息
        $searchsql = 'status="checked" and sid in(select `jl_sign_audit`.sid from `jl_sign_audit` where `jl_sign_audit`.audituid='.$this->auth->getUid().')';
        $itemlist = $this->sign->getSignGroupByProject($searchsql);
        if(!empty($itemlist)){
            foreach($itemlist as $ik => $iv){
                $itemmsg = $this->project->getRowByPid($iv['project']);
                $itemlist[$ik]['pname'] = $itemmsg['pname'];
            }
        }

        if(isset($this->params['pid']) && is_numeric($this->params['pid'])){
            $this->data['project'] = $this->params['pid'];
            $pagestr .= '/project/'.$this->params['pid'];
            $sqlstr .= ' and project='.$this->params['pid'];
            //获取标段信息
            $tenderlist = $this->sign->getSignGroupByTender($this->params['pid'],$searchsql);
            if(!empty($tenderlist)){
                foreach($tenderlist as $tk => $tv){
                    $tendermsg = $this->actmeasure->getRowByPmid($tv['tender']);
                    $tenderlist[$tk]['pmname'] = $tendermsg['pmname'];
                }
            }

            if(isset($this->params['pmid']) && is_numeric($this->params['pmid'])){
                $this->data['tender'] = $this->params['pmid'];
                $pagestr .= '/tender/'.$this->params['pmid'];
                $sqlstr .= ' and tender='.$this->params['pmid'];
                //获取期数信息
                $phasenolist = $this->sign->getSignGroupByPhaseno($this->params['pmid'],$searchsql);
                if(!empty($phasenolist)){
                    foreach($phasenolist as $pk => $pv){
//                        $phasenomsg = $this->numofperact->getCurrStatus($pv['phaseno']);
                        $phasenolist[$pk]['numpname'] = $pv['phaseno'];
                    }
                }

                if(isset($this->params['mpid']) && is_numeric($this->params['mpid'])){
                    $this->data['phaseno'] = $this->params['mpid'];
                    $pagestr .= '/phaseno/'.$this->params['mpid'];
                    $sqlstr .= ' and phaseno='.$this->params['mpid'];
                }
            }
        }

        $totalArchive = $this->sign->getDoneSignNumbyUid($this->auth->getUid(),$sqlstr);
        $pager = new DooPager(Doo::conf()->APP_URL . 'sign/donelist'.$pagestr.'/page', $totalArchive, 10, 100);
        $pager->setCss('', 'disabled', 'active');
        if (isset($this->params['pindex']))
            $pager->paginate(intval($this->params['pindex']));
        else
            $pager->paginate(1);
        if ($pager->limit != ' -10,10')
            $donelist = $this->sign->getDoneSignListbyUid($this->auth->getUid(), $sqlstr, $pager->limit);
        if(isset($donelist) && !empty($donelist)){
            foreach($donelist as $k => $v){
                //获取项目名，标段名，标段期数
                $project = $this->project->getRowByPid($v['project']);
                $tender = $this->actmeasure->getRowByPmid($v['tender']);
//                $phaseno = $this->numofperact->getCurrStatus($v['phaseno']);

                $donelist[$k]['project'] = $project['pname'];
                $donelist[$k]['tender'] = $tender['pmname'];
//                $donelist[$k]['phaseno'] = $phaseno['numpname'];
            }
        }
        $this->data['donelist'] = isset($donelist) ? $donelist : '';
        $this->data['itemlist'] = $itemlist;
        $this->data['tenderlist'] = isset($tenderlist) ? $tenderlist : '';
        $this->data['phasenolist'] = isset($phasenolist) ? $phasenolist : '';
        $this->data['pager'] = $pager->output;
        $this->render('sign-list-done_sign',$this->data, TRUE);
    }

    /**
     *
     * @return type
     */
    public function signCreate()
    {
        $launchsignSwitch = $this->aconfig->getOne(array('select' => 'launchsignswitch', 'asArray' => TRUE))['launchsignswitch'];
        if($launchsignSwitch == 0)
            exit('未开启发起签署功能');

        Doo::loadHelper('DooPager');
        $pagestr = '';
        $sqlstr = ' 1';
        $this->data['project'] = '';
        $this->data['tender'] = '';
        $this->data['phaseno'] = '';

        //获取项目信息
        $searchsql = 'status="uncheck" AND (`isinter`=0 OR `isinter`=3) AND (`ownuid`='.$this->auth->getUid().' OR tender IN (SELECT pmid FROM jl_measure_audit WHERE auditoruid='.$this->auth->getUid().') OR project IN (SELECT pid FROM jl_project_measure WHERE uid='.$this->auth->getUid().'))';
        $itemlist = $this->sign->getSignGroupByProject($searchsql);
        if(!empty($itemlist)){
            foreach($itemlist as $ik => $iv){
                $itemmsg = $this->project->getRowByPid($iv['project']);
                $itemlist[$ik]['pname'] = $itemmsg['pname'];
            }
        }

        if(isset($this->params['pid']) && is_numeric($this->params['pid'])){
            $this->data['project'] = $this->params['pid'];
            $pagestr .= '/project/'.$this->params['pid'];
            $sqlstr .= ' and project='.$this->params['pid'];
            //获取标段信息
            $tenderlist = $this->sign->getSignGroupByTender($this->params['pid'], $searchsql);
            if(!empty($tenderlist)){
                foreach($tenderlist as $tk => $tv){
                    $tendermsg = $this->actmeasure->getRowByPmid($tv['tender']);
                    $tenderlist[$tk]['pmname'] = $tendermsg['pmname'];
                }
            }

            if(isset($this->params['pmid']) && is_numeric($this->params['pmid'])){
                $this->data['tender'] = $this->params['pmid'];
                $pagestr .= '/tender/'.$this->params['pmid'];
                $sqlstr .= ' and tender='.$this->params['pmid'];
                //获取期数信息
                $phasenolist = $this->sign->getSignGroupByPhaseno($this->params['pmid'], $searchsql);
                if(!empty($phasenolist)){
                    foreach($phasenolist as $pk => $pv){
//                        $phasenomsg = $this->numofperact->getCurrStatus($pv['phaseno']);
                        $phasenolist[$pk]['numpname'] = $pv['phaseno'];
                    }
                }

                if(isset($this->params['mpid']) && is_numeric($this->params['mpid'])){
                    $this->data['phaseno'] = $this->params['mpid'];
                    $pagestr .= '/phaseno/'.$this->params['mpid'];
                    $sqlstr .= ' and phaseno='.$this->params['mpid'];
                }
            }
        }

        $totalArchive = $this->sign->getUnSignNum($sqlstr,$this->auth->getUid());
        $pager = new DooPager(Doo::conf()->APP_URL . 'sign/create'.$pagestr.'/page', $totalArchive, 10, 100);
        $pager->setCss('', 'disabled', 'active');
        if (isset($this->params['pindex']))
            $pager->paginate(intval($this->params['pindex']));
        else
            $pager->paginate(1);
        if ($pager->limit != ' -10,10')
            $unlist = $this->sign->getUnSignList($sqlstr, $this->auth->getUid(), $pager->limit);
        if(isset($unlist) && !empty($unlist)){
            foreach($unlist as $k => $v){
                //获取项目名，标段名，标段期数
                $project = $this->project->getRowByPid($v['project']);
                $tender = $this->actmeasure->getRowByPmid($v['tender']);
//                $phaseno = $this->numofperact->getCurrStatus($v['phaseno']);

                $unlist[$k]['project'] = $project['pname'];
                $unlist[$k]['tender'] = $tender['pmname'];
//                $unlist[$k]['phaseno'] = $phaseno['numpname'];
                $unlist[$k]['ownname'] = $this->auth->getName($v['ownuid']);
            }
        }
        $this->data['unlist'] = isset($unlist) ? $unlist : '';
        $this->data['itemlist'] = $itemlist;
        $this->data['tenderlist'] = isset($tenderlist) ? $tenderlist : '';
        $this->data['phasenolist'] = isset($phasenolist) ? $phasenolist : '';
        $this->data['pager'] = $pager->output;
        $this->render('sign-create_sign', $this->data, TRUE);
    }

    /**
     *
     * @return type
     */
    public function signList()
    {
        if(isset($_POST['delid']) && is_numeric($_POST['delid'])){
            //删除未签署报表数据和文件
            $signmsg = $this->sign->getOneSignbysid($_POST['delid']);
            if(empty($signmsg) && $signmsg['status'] == "checked" && $signmsg['ownuid'] != $this->auth->getUid()){
                exit(json_encode(array('code' => 400),JSON_UNESCAPED_UNICODE));
            }
            $this->sign->delSignbysid($_POST['delid'],$signmsg['status']);

            include (DOO::conf()->SITE_PATH . 'protected/plugin/io.han.php');
            $this->IoHandler = new IoHandler();
            $path = DOO::conf()->SITE_PATH."signs/".$_POST['delid'];
            $this->IoHandler->RemoveDir($path);

            exit(json_encode(array('code' => 200),JSON_UNESCAPED_UNICODE));
        }
        Doo::loadHelper('DooPager');
        $pagestr = '';
        $sqlstr = ' 1';
        $this->data['project'] = '';
        $this->data['tender'] = '';
        $this->data['phaseno'] = '';
        $this->data['nosign'] = '';

        //获取项目信息
        $searchsql = '(`isinter`=0 OR `isinter`=3) AND (`ownuid`='.$this->auth->getUid().' OR `audituid`='.$this->auth->getUid().' OR sid IN (SELECT sid FROM jl_sign_audit WHERE jl_sign_audit.audituid='.$this->auth->getUid().'))';
        $itemlist = $this->sign->getSignGroupByProject($searchsql);
        if(!empty($itemlist)){
            foreach($itemlist as $ik => $iv){
                $itemmsg = $this->project->getRowByPid($iv['project']);
                $itemlist[$ik]['pname'] = $itemmsg['pname'];
            }
        }

        if(isset($this->params['pid']) && is_numeric($this->params['pid'])){
            $this->data['project'] = $this->params['pid'];
            $pagestr .= '/project/'.$this->params['pid'];
            $sqlstr .= ' and project='.$this->params['pid'];
            //获取标段信息
            $tenderlist = $this->sign->getSignGroupByTender($this->params['pid'],$searchsql);
            if(!empty($tenderlist)){
                foreach($tenderlist as $tk => $tv){
                    $tendermsg = $this->actmeasure->getRowByPmid($tv['tender']);
                    $tenderlist[$tk]['pmname'] = $tendermsg['pmname'];
                }
            }

            if(isset($this->params['pmid']) && is_numeric($this->params['pmid'])){
                $this->data['tender'] = $this->params['pmid'];
                $pagestr .= '/tender/'.$this->params['pmid'];
                $sqlstr .= ' and tender='.$this->params['pmid'];
                //获取期数信息
                $phasenolist = $this->sign->getSignGroupByPhaseno($this->params['pmid'],$searchsql);
                if(!empty($phasenolist)){
                    foreach($phasenolist as $pk => $pv){
//                        $phasenomsg = $this->numofperact->getCurrStatus($pv['phaseno']);
                        $phasenolist[$pk]['numpname'] = $pv['phaseno'];
                    }
                }

                if(isset($this->params['mpid']) && is_numeric($this->params['mpid'])){
                    $this->data['phaseno'] = $this->params['mpid'];
                    $pagestr .= '/phaseno/'.$this->params['mpid'];
                    $sqlstr .= ' and phaseno='.$this->params['mpid'];
                }
            }
        }

        if((isset($this->params['nosign']) && ($this->params['nosign'] == 'nosign')) || isset($_GET['nosign'])){
            $this->data['nosign'] = 1;
            $pagestr .= '/nosign';
            $searchsql = '(`isinter`=0 OR `isinter`=3) AND (`ownuid`='.$this->auth->getUid().' AND `status`="uncheck")';
        }

        $totalArchive = $this->sign->getSignNum($sqlstr.' and '.$searchsql);
        $pager = new DooPager(Doo::conf()->APP_URL . 'sign/list'.$pagestr.'/page', $totalArchive, 10, 100);
        $pager->setCss('', 'disabled', 'active');
        if (isset($this->params['pindex']))
            $pager->paginate(intval($this->params['pindex']));
        else
            $pager->paginate(1);
        if ($pager->limit != ' -10,10')
            $list = $this->sign->getSignList($sqlstr.' and '.$searchsql,$pager->limit);
        if(isset($list) && !empty($list)){
            foreach($list as $k => $v){
                //获取项目名，标段名，标段期数
                $project = $this->project->getRowByPid($v['project']);
                $tender = $this->actmeasure->getRowByPmid($v['tender']);
//                $phaseno = $this->numofperact->getCurrStatus($v['phaseno']);

                $list[$k]['project'] = $project['pname'];
                $list[$k]['tender'] = $tender['pmname'];
//                $list[$k]['phaseno'] = $phaseno['numpname'];
                $list[$k]['ownname'] = $this->auth->getName($v['ownuid']);
                $list[$k]['auditname'] = $this->auth->getName($v['audituid']);
                $list[$k]['delstatus'] = $this->auth->getUid() == $v['ownuid'] && $v['status'] != 'checked' && $v['isinter'] != 3 ? 1 : 0;
            }
        }

        $this->data['list'] = isset($list) ? $list : '';
        $this->data['itemlist'] = $itemlist;
        $this->data['tenderlist'] = isset($tenderlist) ? $tenderlist : '';
        $this->data['phasenolist'] = isset($phasenolist) ? $phasenolist : '';
        $this->data['pager'] = $pager->output;
        $this->render('sign-list-all', $this->data, TRUE);
    }

    /**
     *
     * @return type
     */
    public function signSignSet()
    {
        $launchsignSwitch = $this->aconfig->getOne(array('select' => 'launchsignswitch', 'asArray' => TRUE))['launchsignswitch'];
        if($launchsignSwitch == 0)
            exit('未开启发起签署功能');

        if(!isset($this->params['sid']) || !is_numeric($this->params['sid'])){
            exit('没有报表参数');
        }
        //获取报表信息
        $signmsg = $this->sign->getOneSignbysid($this->params['sid']);

        //获取标段审批人列表
        $auditactlist = $this->measureauditact->getUserAuditLast($signmsg['tender'],$signmsg['phaseno']);
        $userlist = array();
        if(!empty($auditactlist)){
            foreach($auditactlist as $k => $v){
                $usermsg = $this->auth->getRowByUid($v['auditoruid']);
                $userlist[$k]['userid'] = $usermsg['userid'];
                $userlist[$k]['name'] = $usermsg['name'];
                $userlist[$k]['jobs'] = $usermsg['jobs'];
                $userlist[$k]['avatar'] = $usermsg['avatar'];
            }
        }

        //获取原报人
        $measureArray = $this->actmeasure->getRowByPmid($signmsg['tender']);
//        $lastRowArray = $this->numofperact->getLastNew2($signmsg['tender']);
        $usermsg2 = $this->auth->getRowByUid($measureArray['uid']);
        $orginArray['userid'] = $measureArray['uid'];
        $orginArray['avatar'] = $usermsg2['avatar'];
        $orginArray['name'] = $usermsg2['name'];
        $orginArray['jobs'] = $usermsg2['jobs'];
//        $attfileArray = $this->attfile->getFirstFile($lastRowArray['pmid'], $lastRowArray['numpname'], $lastRowArray['times']);
//        $orginArray['time'] = date('Y-m-d', $attfileArray['intime']);

        //获取项目名，标段名，标段期数
        $project = $this->project->getRowByPid($signmsg['project']);
        $tender = $this->actmeasure->getRowByPmid($signmsg['tender']);
//        $phaseno = $this->numofperact->getCurrStatus($signmsg['phaseno']);

        $signmsg['project'] = $project['pname'];
        $signmsg['tender'] = $tender['pmname'];
//        $signmsg['phaseno'] = $phaseno['numpname'];




        //获取报表图片
        $maxwidth = 794; //默认图片最大宽度   a4
        $maxheight = 1123; //默认图片最大高度  a4
        if(!empty($signmsg['widhei'])){
            $widhei = explode('_', $signmsg['widhei']);
            $style = $widhei[0].'mm '.$widhei[1].'mm';
        }else{
            $style = '210mm 297mm';
        }
        $signattlist = $this->sign->getSignAttList($this->params['sid']);
        if(!empty($signattlist)){
            foreach($signattlist as $sak => $sav){
                if($sak == 0){
                    $imgmsg = getimagesize(Doo::conf()->APP_URL.$sav['filepath']);
                    $maxwidth = $imgmsg[0];
                    $maxheight = $imgmsg[1];
                    break;
                }
            }
        }

        $this->data['signmsg'] = $signmsg;
        $this->data['userlist'] = $userlist;
        $this->data['attlist'] = $signattlist;
        $this->data['reportlist'] = $orginArray;
        $this->data['maxwidth'] = $maxwidth;
        $this->data['maxheight'] = $maxheight;
        $this->data['style'] = $style;
        $this->render('sign-view-set_signer', $this->data, TRUE);
    }

    public function signSearchUser(){
        if(!isset($_GET['email']) || empty($_GET['email'])){
            echo json_encode(array('code' => 400, 'msg' => '请输入邮箱地址'));
            exit;
        }

        $usermsg = $this->auth->checkUserEmail($_GET['email']);
        if(!empty($usermsg)){
            echo json_encode(array('code' => 200, 'user' => $usermsg));
            exit;
        }else{
            echo json_encode(array('code' => 400, 'msg' => '没有此邮箱用户'));
            exit;
        }
    }

    public function signUpSigner(){
        if(!isset($_POST['ids']) || !isset($_POST['names']) || !isset($_POST['sid']) || !is_numeric($_POST['sid'])){
            echo json_encode(array('code' => 400, 'msg' => '上传参数有误'));
            exit;
        }
        $useridarr = $_POST['ids'];
        $usernamearr = $_POST['names'];
        foreach($useridarr as $k => $v){
            $signs = new Signn();
            $status = $k != 0 ? 'uncheck' : 'checking';
            $result = $signs->insertSignAudit($_POST['sid'],$status,$v,$usernamearr[$k]);
            if(empty($result)){
                echo json_encode(array('code' => 400, 'msg' => '添加签署人出错'));
                exit;
            }
            //发送签署短信
            if($k == 0){
                // SMS Start
                $signArray = $this->sign->getOneSignbysid($_POST['sid']);
                $pmname = $this->actmeasure->getRowByPmid($signArray['tender']);
                $userProArray = $this->profile->getProWithUid($v);
                if (isset($userProArray) && !empty($userProArray['mobile'])) {
                    $sendarr1 = '“' .$pmname['pmname'].'”的“'. $signArray["name"] .'”';
                    $sendarr2 = str_replace('【','',$sendarr1);
                    $sendmsg = str_replace('】','',$sendarr2);
                    $retval = $this->__auditNotice($userProArray['mobile'], Doo::conf()->SMS_TIPS_PRE . $sendmsg .Doo::conf()->SMS_TIPS["AUDIT_NOTICE_AUDITOR5"]);
                }
                // SMS End
            }
        }
        //更新报表信息
        $result2 = $this->sign->updateSignMsg($_POST['sid'],$this->auth->getUid());
        if(!empty($result2)){
            echo json_encode(array('code' => 200, 'msg' => '添加成功'));
            exit;
        }else{
            echo json_encode(array('code' => 400, 'msg' => '添加签署人出错'));
            exit;
        }
    }

    /**
     *
     * @return type
     */
    public function signView()
    {
        if(!isset($this->params['sid']) || !is_numeric($this->params['sid'])){
            exit('没有报表参数');
        }
        //获取报表信息
        $signmsg = $this->sign->getOneSignbysid($this->params['sid']);
        //获取项目名，标段名，标段期数
        $project = $this->project->getRowByPid($signmsg['project']);
        $tender = $this->actmeasure->getRowByPmid($signmsg['tender']);
//        $phaseno = $this->numofperact->getCurrStatus($signmsg['phaseno']);

        $signmsg['project'] = $project['pname'];
        $signmsg['tender'] = $tender['pmname'];
//        $signmsg['phaseno'] = $phaseno['numpname'];

        //获取签署人列表
        $signauditlist = $this->sign->getSignAuditList($this->params['sid']);
        if(!empty($signauditlist)){
            foreach($signauditlist as $k => $v){
                //获取签署人头像
                $signauditlist[$k]['index'] = $k+1;
                $signauditlist[$k]['avatar'] = $this->auth->getAvatar($v['audituid']);
            }
        }

        //获取报表图片
        $maxwidth = 794; //默认图片最大宽度   a4
        $maxheight = 1123; //默认图片最大高度  a4
        if(!empty($signmsg['widhei'])){
            $widhei = explode('_', $signmsg['widhei']);
            $style = $widhei[0].'mm '.$widhei[1].'mm';
        }else{
            $style = '210mm 297mm';
        }
        $signattlist = $this->sign->getSignAttList($this->params['sid']);
        if(!empty($signattlist)){
            foreach($signattlist as $sak => $sav){
                $signattlist[$sak]['auditatt'] = $this->sign->getSignAuditAttList($sav['said']);
                if($sak == 0){
                    $imgmsg = getimagesize(Doo::conf()->APP_URL.$sav['filepath']);
                    $maxwidth = $imgmsg[0];
                    $maxheight = $imgmsg[1];
                }
            }
        }

        $backurl = '/sign/list';
        if(isset($_GET['status'])){
            switch($_GET['status']){
                case 'done' : $backurl = '/sign/donelist';break;
                case 'doing' : $backurl = '/sign/onlist';break;
                case 'mylist' : $backurl = '/sign/mylist';break;
                case 'onlist' : $backurl = '/sign/onlist';break;
                case 'donelist' : $backurl = '/sign/donelist';break;
                default: $backurl = '/sign/list';break;
            }

        }

        $this->data['signmsg'] = $signmsg;
        $this->data['auditlist'] = $signauditlist;
        $this->data['attlist'] = $signattlist;
        $this->data['backurl'] = $backurl;
        $this->data['maxwidth'] = $maxwidth;
        $this->data['maxheight'] = $maxheight;
        $this->data['style'] = $style;

        $this->render('sign-view-page', $this->data, TRUE);
    }



    public function substr_replace_cn($string, $repalce = '*', $start = 0, $len = 0)
    {
        $count = mb_strlen($string, 'UTF-8'); //此处传入编码，建议使用utf-8。此处编码要与下面mb_substr()所使用的一致
        if (!$count) {
            return $string;
        }
        if ($len == 0) {
            $end = $count;  //传入0则替换到最后
        } else {
            $end = $start + $len;       //传入指定长度则为开始长度+指定长度
        }
        $i = 0;
        $returnString = '';
        while ($i < $count) { //循环该字符串
            $tmpString = mb_substr($string, $i, 1, 'UTF-8'); // 与mb_strlen编码一致
            if ($start <= $i && $i < $end) {
                $returnString .= $repalce;
            } else {
                $returnString .= $tmpString;
            }
            $i++;
        }
        return $returnString;
    }

    function unicode_encode($name)
    {//to Unicode
        $name = iconv('UTF-8', 'UCS-2', $name);
        $len = strlen($name);
        $str = '';
        for ($i = 0; $i < $len - 1; $i = $i + 2) {
            $c = $name[$i];
            $c2 = $name[$i + 1];
            if (ord($c) > 0) {// 两个字节的字
                $str .= '\\' . base_convert(ord($c), 10, 16) . base_convert(ord($c2), 10, 16);
            } else {
                $str .= $c2;
            }
        }
        $str = strtoupper($str);
        return $str;
    }

    function unicode_decode($name)
    {//Unicode to
        $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
        preg_match_all($pattern, $name, $matches);
        if (!empty($matches)) {
            $name = '';
            for ($j = 0; $j < count($matches[0]); $j++) {
                $str = $matches[0][$j];
                if (strpos($str, '\\u') === 0) {
                    $code = base_convert(substr($str, 2, 2), 16, 10);
                    $code2 = base_convert(substr($str, 4), 16, 10);
                    $c = chr($code) . chr($code2);
                    $c = iconv('UCS-2', 'UTF-8', $c);
                    $name .= $c;
                } else {
                    $name .= $str;
                }
            }
        }
        return $name;
    }

    private function __auditNotice($mobile, $text)
    {
        $smsSignSwitch = $this->aconfig->getOne(array('select' => 'smssignswitch', 'asArray' => TRUE))['smssignswitch'];
        if ($smsSignSwitch > 0)
            return $this->sms->sendSms($mobile, $text);

    }

}

?>