<?php
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('itemmeasurenum');
Doo::loadClass('itemfile');
Doo::loadClass('attachment');
Doo::loadHelper('DooPager');
Doo::loadClass('sign');
Doo::loadModelAt('aconfig', 'admin');

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

    private $aconfig,$data, $sign, $auth, $attfile, $profile, $project, $contractact, $actmeasure, $numofperact, $measureauditact, $itemmeasurenum, $itemfle, $att;

    public function beforeRun($resource, $action)
    {
//	$uGroups = $this->profile->getProWithUid($this->auth->getUid());
//	$falg = Doo::acl()->isAllowed($uGroups['groups'], $resource, $action);
//	if (!$falg)
//	    return Doo::acl()->defaultFailedRoute;
        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->itemmeasurenum = new ItemMeasureNumpofper();
        $this->itemfle = new ItemFile();
        $this->att = new attachment();
        $this->sign = new Signn();
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->data['currChannle'] = 's';
        $this->data['user'] = $this->profile->getProWithUid($this->auth->getUid());
        $mpidArray = $this->measureauditact->getAuditProject2($this->auth->getUid());
        if (isset($mpidArray[0]['pid'])) {
            $this->data['numofchecking'] = 0;
            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;
        }

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

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

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

        //草图入口
        $this->data['imediateSwitch'] = $this->aconfig->getOne(array('select' => 'imediateswitch', 'asArray' => TRUE))['imediateswitch'];
    }

    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'];
        }
    }

    public function index()
    {
        $this->data['conArray'] = NULL;
        $conArray = $this->actmeasure->getGroupProject($this->auth->getUid());
        if (isset($conArray)) {
            foreach ($conArray as $k => $v) {
                $proArray = $this->project->getRowByPid($v['pid']);
                $this->data['conArray'][] = $proArray;
                $profileArray = $this->profile->getProWithUid($proArray['uid']);
                $this->data['conArray'][$k]['company'] = $profileArray['company'];
                $countMeasureInt = $this->actmeasure->getCountMeasure($v['stid']);
                $countTotalMeasureInt = $this->actmeasure->getMearsureCount($v['pid']);
                $this->data['conArray'][$k]['countmeasure'] = $countMeasureInt;
                $this->data['conArray'][$k]['countTotalMeasureInt'] = $countTotalMeasureInt;
                $this->data['conArray'][$k]['changTotal'] = $this->numofperact->getChangTotal($v['pid']);
                $this->data['conArray'][$k]['currdone'] = $this->numofperact->getCurrDoneNow($v['pid']);
                $this->data['conArray'][$k]['contracttotal'] = $this->actmeasure->getTotalWithPid($v['pid']);
                if ($this->data['conArray'][$k]['contracttotal']) {
                    $this->data['conArray'][$k]['pcurrdone'] = round(($this->data['conArray'][$k]['currdone'] / $this->data['conArray'][$k]['contracttotal']) * 100) . '%';
                } else {
                    $this->data['conArray'][$k]['pcurrdone'] = '0%';
                }
                $this->data['conArray'][$k]['bcontracttotal'] = number_format($this->data['conArray'][$k]['contracttotal'], 2, '.', ',');
                $this->data['conArray'][$k]['bchangTotal'] = number_format($this->data['conArray'][$k]['changTotal'], 2, '.', ',');
                $this->data['conArray'][$k]['index'] = $k%8+1;
            }
        }
        $this->render('s-project', $this->data, TRUE);
    }

    public function proOverview()
    {
//	$this->data['pros'] = $this->project->getAll();
//	if (isset($_POST['pname']) && $_POST['pname']) {
//	    $this->project->insertProject($_POST['pname']);
//	    return Doo::conf()->APP_URL . 'project/index';
//	}
        $this->data['pid'] = $this->params['pid'];
        $this->render('w-project-detail', $this->data);
    }

    public function proSection()
    {
        $this->data['currproArray'] = $this->data['allproArray'] = NULL;
        $proArray = $this->actmeasure->getGroupProject($this->auth->getUid());
        foreach ($proArray as $v) {
            $pidArray[] = $v['pid'];
        }
        $pidstr = implode(',', $pidArray);
        // 项目名称
        $allproArray = $this->project->getFewRow($pidstr);
        // 面包屑导航项目
        foreach ($allproArray as $kk => $vv) {
            if ($vv['pid'] == $this->params['pid']) {
                $this->data['currproArray'] = $vv;
            } else {
                $this->data['allproArray'][] = $vv;
            }
        }

        // 标段按月进度
//        for ($i = 1; $i <= 7; $i++) {
//            $monthz[] = date('n月', strtotime('+' . $i . ' months', $this->data['currproArray']['intime']));
//            if ($i == 1) {
//                $ii = date('Y年', $this->data['currproArray']['intime']) . date('n月', strtotime('+' . $i . ' months', $this->data['currproArray']['intime']));
//            } else {
//                $ii = date('n月', strtotime('+' . $i . ' months', $this->data['currproArray']['intime']));
//            }
//            $this->data['months'][$i]['month'] = $ii;
//        }
        // 标段
        // 搜索有没有相应的月份，有就把实际赋值，没有就为零
        $this->data['MeasureArray'] = $this->actmeasure->getRowsByPid($this->params['pid']);
        $this->data['MyMeasureArray'] = array();
        $i = 0;
        $totalstid = 0;
        $monthArray = [];
        foreach ($this->data['MeasureArray'] as $key => $value) {
            $this->data['MeasureArray'][$key]['pmid'] = $value['pmid'];
            $this->data['MeasureArray'][$key]['type'] = $this->contractact->getRowByStid($value['stid'])['stname'];
            $totalstid += $this->actmeasure->getTotal($value['stid'])['total'];
//            $numArray = $this->numofperact->getRowByPmid2($value['pmid']);
//            $num = $num1 = 0;
//            $this->data['MeasureArray'][$key]['num'] = $this->data['MeasureArray'][$key]['num1'] = NULL;
//            foreach ($numArray as $k => $v) {
//                if ($v['currstatus'] == 'checked') {
//                    $monthInt = date('n月', $v['audittime']);
//                    $retval = in_array($monthInt, $monthz);
//                    if ($retval) {
//                        $num = round(($v['currdone'] / $value['contracttotal']) * 100);
//                        $num1 = round(($v['curralltotal'] / $value['contracttotal']) * 100);
//                    }
//                }
//                $this->data['MeasureArray'][$key]['num'] .= $num . ',';
//                $this->data['MeasureArray'][$key]['num1'] .= $num1 . ',';
//            }
            $this->data['MeasureArray'][$key]['totalnum'] = $this->numofperact->getCountTotalnum($value['pmid']);
            $this->data['MeasureArray'][$key]['totalplus'] = number_format($this->actmeasure->getRowByPmid($value['pmid'])['contracttotal'], 2, '.', ',');
            $this->data['MeasureArray'][$key]['stopnow'] = $this->numofperact->getStopNowTotal($value['pmid'])['sntotal'];
            $this->data['MeasureArray'][$key]['nstopnow'] = number_format($this->numofperact->getStopNowTotal($value['pmid'])['sntotal'], 2, '.', ',');
            $this->data['MeasureArray'][$key]['currdone'] = $this->numofperact->getCurrdoneNew($value['pmid'])['currtotal'];
            $this->data['MeasureArray'][$key]['ncurrdone'] = number_format($this->data['MeasureArray'][$key]['currdone'], 2, '.', ',');
            $this->data['MeasureArray'][$key]['pstopnow'] = '0%';
            $this->data['MeasureArray'][$key]['pcurrdone'] = '0%';
            $this->data['MeasureArray'][$key]['pless'] = '0%';
            if ($value['contracttotal'] > 0) {
                $this->data['MeasureArray'][$key]['pstopnow'] = round(($this->data['MeasureArray'][$key]['stopnow'] / $value['contracttotal']) * 100);
                $this->data['MeasureArray'][$key]['dispstopnow'] = $this->data['MeasureArray'][$key]['pstopnow'] . '%';
                $this->data['MeasureArray'][$key]['pcurrdone'] = round(($this->data['MeasureArray'][$key]['currdone'] / $value['contracttotal']) * 100);
                $this->data['MeasureArray'][$key]['dispcurrdone'] = $this->data['MeasureArray'][$key]['pcurrdone'] . '%';
                $this->data['MeasureArray'][$key]['pless'] = (100 - $this->data['MeasureArray'][$key]['pstopnow'] - $this->data['MeasureArray'][$key]['pcurrdone']) . '%';
            }
            $this->data['MeasureArray'][$key]['nless'] = number_format($value['contracttotal'] - $this->data['MeasureArray'][$key]['stopnow'] - $this->data['MeasureArray'][$key]['currdone'], 2, '.', ',');
            $tenderArray = $this->numofperact->getRowTender2($value['pmid']);
            $this->data['MeasureArray'][$key]['ownstatus'] = '审批中';
            $ownerStatusArray = $this->measureauditact->getStatusTen($tenderArray['pmid'], $tenderArray['numpname']);
            if (isset($ownerStatusArray[0]['last']) && isset($ownerStatusArray[0]['mastatus']))
                if (($ownerStatusArray[0]['last'] == 1) && ($ownerStatusArray[0]['mastatus'] == 'checked')) {
                    $this->data['MeasureArray'][$key]['ownstatus'] = '已审批';
                } else {
                    $this->data['MeasureArray'][$key]['ownstatus'] = '审批中';
                }

            // 分组出年月 每个月份的独立相加  累计完成总量
            $month = $this->numofperact->getCurrTotalStMonthNoCheckno($value['stid']);
            foreach ($month as $k => $v) {
                $allmonth[] = $v;
                if (!in_array($v['month'], $monthArray))
                    $monthArray[] = $v['month'];
            }

            // 分组出年月 每个月份的独立相加   本月完成总量
            $month1 = $this->numofperact->getCurrDoneStMonthNoCheckno($value['stid']);
            foreach ($month1 as $k => $v) {
                $allmonth1[] = $v;
            }

            if($value['uid'] == $this->auth->getUid()){
                $this->data['MyMeasureArray'][$i] = $this->data['MeasureArray'][$key];
                $i++;
            }
        }

        // 中文表述年月
        $total = $total1 = array();
        $startyear = $cnymArray = array();
        foreach ($monthArray as $kk => $vv) {
            $ymarray = explode('-', $vv);
            if (!in_array($ymarray[0], $startyear))
                $startyear[] = $ymarray[0];
        }
        $thismonth = 0;
        foreach($startyear as $sk => $sv){
            for($i = 1; $i <= 12; $i++){
                $j = $i < 10 ? '0'.$i : $i;
                $month = $sv.'-'.$j;
                $thismonth1 = 0;
                foreach ($allmonth1 as $k1 => $v1) {
                    if ($v1['month'] == $month)
                        $thismonth1 += $v1['currdone'];
                }
                $total1[] = $thismonth1 != 0 ? $thismonth1 : 0;
                foreach ($allmonth as $keyk => $valuev) {
                    if ($valuev['month'] == $month)
                        $thismonth += $valuev['currtotal'];
                }
                $total[] = ($thismonth != 0 && $thismonth1 != 0) ? $thismonth : 0;
                $cnymArray[] = $i == 1 ? '\'' .$sv.'年'.$i.'月'. '\'' : '\'' .$i.'月'. '\'';
            }
        }
        foreach ($total as $value2) {
            $total3[] = round(($value2 / $totalstid) * 100);
        }
        foreach ($total1 as $value11) {
            $total4[] = round(($value11 / $totalstid) * 100);
        }
        $this->data['projectDate'] = implode(',', $cnymArray);
        $this->data['t1'] = implode(',', $total3);
        $this->data['t2'] = implode(',', $total4);

        $this->render('s-project-section', $this->data, TRUE);
    }

    public function proDetail()
    {
        $this->data['currproArray'] = $this->data['allproArray'] = NULL;
        $proArray = $this->actmeasure->getGroupProject($this->auth->getUid());
        foreach ($proArray as $v) {
            $pidArray[] = $v['pid'];
        }
        $pidstr = implode(',', $pidArray);
        // 项目名称
        $allproArray = $this->project->getFewRow($pidstr);
        // 面包屑导航项目
        foreach ($allproArray as $kk => $vv) {
            if ($vv['pid'] == $this->params['pid']) {
                $this->data['currproArray'] = $vv;
            } else {
                $this->data['allproArray'][] = $vv;
            }
        }
        // 面包屑导航合同
        $conArray = $this->contractact->getAll();
        $measureArray = $this->actmeasure->getRowByPmid($this->params['pmid']);
        if (isset($measureArray['stid'])) {
            foreach ($conArray as $kkk => $vvv) {
                if ($vvv['stid'] == $measureArray['stid']) {
                    $this->data['currconArray'] = $vvv;
                } else {
                    if ($vvv['pid'] == $this->params['pid'])
                        $this->data['allconArray'][] = $vvv;
                }
            }
        } else {
            $this->data['currconArray'] = $this->data['allconArray'] = NULL;
        }
        // 面包屑导航标段
        $this->data['curractmeasureArray'] = NULL;
        $this->data['allactmeasureArray'] = [];
//        $actmeasureArray = $this->actmeasure->getAll();
        $actmeasureArray = $this->actmeasure->getRowUser($this->auth->getUid());
        foreach ($actmeasureArray as $kkkk => $vvvv) {
            if ($vvvv['stid'] == $measureArray['stid']) {
                if (($vvvv['pmid'] == $this->params['pmid'])) {
                    $this->data['curractmeasureArray'] = $vvvv;
                } else {
                    $this->data['allactmeasureArray'][] = $vvvv;
                }
            }
        }
        // 图标
        $this->data['MeasureArray'] = $this->numofperact->getGroupByLastOne($this->params['pmid']);
        $measureArray = $this->actmeasure->getRowByPmid($this->params['pmid']);
        foreach ($this->data['MeasureArray'] as $key => $value) {
            if ($value['currdone'] > 0 && $measureArray['contracttotal'] > $value['currdone']) {
                $this->data['MeasureArray'][$key]['lessTotal'] = round(($value['currdone'] / $measureArray['contracttotal']) * 100);
            } else {
                $this->data['MeasureArray'][$key]['lessTotal'] = 0;
            }
        }
        $this->data['pid'] = $this->params['pid'];
        $this->data['pmid'] = $this->params['pmid'];
        // 获取当前合同段的期数
//	$this->data['allNumArray'] = $this->numofperact->getNumByStid(1);
        $this->render('s-project-section-detail', $this->data, TRUE);
    }

    public function proMeasure()
    {
        $MpidArray = $this->measureauditact->getRowByMpid(1);
        foreach ($MpidArray as $key => $value) {
            $uidArray = $value['uid'];
        }
        $this->data['pid'] = $this->params['pid'];
        $this->render('s-project-section-measure', $this->data);
    }

    Function fNumber($number)
    {
        if ($number == '')
            Return "-";
        $nlen = strlen($number);
        while ($nlen > 3) {
            $fNumber = "," . substr($number, $nlen - 3, 3);
            $number = substr($number, 0, -3);
            $nlen = strlen($number);
        }

        if ($nlen <= 3) {
            $fNumber = $number . $fNumber;
        }
        Return $fNumber;
    }

    public function welcome()
    {
//	if (!$this->auth->isLoggedIn())
//	    return Doo::conf()->APP_URL;
        if ($this->profile->getProWithUid($_SESSION['uid'])['userid'])
            return Doo::conf()->APP_URL . 'project/list';
        if (isset($_POST['welform'])) {
            $profileUserArray = $_POST;
            $profileUserArray['userid'] = $_SESSION['uid'];
            $this->profile->insertProfile($profileUserArray); // 无自增字段返回0
            return Doo::conf()->APP_URL . 'project/list';
        }
        $this->render('welcome', $this->data);
    }

    public function prolist()
    {
//	if (!$this->auth->isLoggedIn())
//	    return Doo::conf()->APP_URL;
//	$proArray = new stdClass();
//	$jsonpath = pathinfo($this->attfile->getMaxRow()['filepath']);
//	$extPathdir = Doo::conf()->SITE_PATH . $jsonpath['dirname'] . '/' . $jsonpath['filename'];
//	if ($handle = opendir($extPathdir)) {
//	    while (false !== ($file = readdir($handle))) {
//		$filename = pathinfo($file);
//		if ($filename['extension'] == 'json')
//		    $proArray = json_decode(file_get_contents($extPathdir . '/' . $file));
//	    }
//	    closedir($handle);
//	}
//	$this->data['proArray'] = null;
        $this->render('s-project', $this->data);
    }

    function proSectionFiles()
    {
        if (isset($_POST['optype']) && ($_POST['optype'] == 'replace') && ($_POST['imnid'])) {
            $imnidArray = $this->itemmeasurenum->getRowData($_POST['imnid']);
            if ($imnidArray['iaid'] > 0) {
                $fileArray = $this->upItemFile('file')[0];
                if (isset($fileArray['filepath'])) {
                    $itemArray = $this->itemfle->getItemFile($imnidArray['iaid']);
                    if (isset($itemArray)) {
                        if ($itemArray['oldiaid'] > 0) {
                            $oldiaid = $itemArray['oldiaid'];
                        } else {
                            $oldiaid = $imnidArray['iaid'];
                        }
                        $postArray = array('ownerid' => $this->auth->getUid(), 'pid' => $itemArray['pid'], 'pmid' => $itemArray['pmid'], 'filename' => $fileArray['filename'], 'filesize' => $fileArray['filesize'], 'fileext' => $fileArray['fileext'], 'filepath' => $fileArray['filepath'], 'oldiaid' => $oldiaid);
                        $iaid = $this->itemfle->insertItemFileRecord($postArray);
                        if ($iaid > 1) {
                            $this->itemmeasurenum->updateIAID($imnidArray['iaid'], $iaid);
                            echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                            die();
                        }
                    }
                }
            }
        }
        if (isset($_POST['optype']) && ($_POST['optype'] == 'del') && isset($_POST['imnid'])) {
            ini_set('display_errors', 1);
            $imnidArray = $this->itemmeasurenum->getRowData($_POST['imnid']);
            if ($imnidArray['iaid'] > 0) {
                $this->itemmeasurenum->updateDeltag($_POST['imnid'], $this->auth->getUid());
                echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                die();
            }
        }
        if (isset($_POST['filename']) && isset($_POST['filedesc']) && isset($_POST['upimnid'])) {
            $filename = $_POST['filename'];
            $filedesc = $_POST['filedesc'];
            $imnidArray = $this->itemmeasurenum->getRowData($_POST['upimnid']);
            if ($imnidArray['iaid'] > 0) {
                if (isset($filedesc))
                    $this->itemmeasurenum->updateItemFields($_POST['upimnid'], $filedesc, 0);
                if (isset($filename))
                    $this->itemfle->updateItemFields($imnidArray['iaid'], $filename, 0);
                echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                die();
            }
        }

        // 面包屑导航项目
        $this->data['currproArray'] = $this->data['allproArray'] = NULL;
        $proArray = $this->actmeasure->getGroupProject($this->auth->getUid());
        foreach ($proArray as $v) {
            $pidArray[] = $v['pid'];
        }
        $pidstr = implode(',', $pidArray);
        // 项目名称
        $allproArray = $this->project->getFewRow($pidstr);
        // 面包屑导航项目
        foreach ($allproArray as $kk => $vv) {
            if ($vv['pid'] == $this->params['pid']) {
                $this->data['currproArray'] = $vv;
            } else {
                $this->data['allproArray'][] = $vv;
            }
        }
// 面包屑导航合同
        $conArray = $this->contractact->getAll();
        $measureArray = $this->actmeasure->getRowByPmid($this->params['pmid']);
        if (isset($measureArray['stid'])) {
            foreach ($conArray as $kkk => $vvv) {
                if ($vvv['stid'] == $measureArray['stid']) {
                    $this->data['currconArray'] = $vvv;
                } else {
                    if ($vvv['pid'] == $this->params['pid'])
                        $this->data['allconArray'][] = $vvv;
                }
            }
        } else {
            $this->data['currconArray'] = $this->data['allconArray'] = NULL;
        }
// 面包屑导航标段
        $this->data['curractmeasureArray'] = NULL;
        $this->data['allactmeasureArray'] = [];
        $actmeasureArray = $this->actmeasure->getRowUser($this->auth->getUid());
        foreach ($actmeasureArray as $kkkk => $vvvv) {
            if ($vvvv['stid'] == $measureArray['stid']) {
                if (($vvvv['pmid'] == $this->params['pmid'])) {
                    $this->data['curractmeasureArray'] = $vvvv;
                } else {
                    $this->data['allactmeasureArray'][] = $vvvv;
                }
            }
        }
        // 选取查询
        $groupArray = $this->numofperact->getGroupByLastOne2($this->params['pmid']);
        $this->data['groupArray'] = $groupArray;
        $owneridArray = $this->itemfle->getGroupOwnerid($this->params['pmid']);
        foreach ($owneridArray as $k => $v) {
            $this->data['owneridArray'][$k]['name'] = $this->profile->getProWithUid($v['ownerid'])['name'];
            $this->data['owneridArray'][$k]['iaid'] = $v['iaid'];
            $this->data['owneridArray'][$k]['ownerid'] = $v['ownerid'];
        }


// 分页
        $totalArchive = $this->itemmeasurenum->getCount($this->params['pmid'], 0, $this->params['numpname'], $this->params['userid']);
        if ($totalArchive) {
            if ($this->params['numpname'] && $this->params['userid']) {
                $pager = new DooPager(Doo::conf()->APP_URL . 'project/' . $this->params['pmid'] . '/section/' . $this->params['pmid'] . '/files/num/' . $this->params['numpname'] . '/user/' . $this->params['userid'] . '/page', $totalArchive, 20, 100);
            } elseif ($this->params['numpname']) {
                $pager = new DooPager(Doo::conf()->APP_URL . 'project/' . $this->params['pmid'] . '/section/' . $this->params['pmid'] . '/files/num/' . $this->params['numpname'] . '/page', $totalArchive, 20, 100);
            } elseif ($this->params['userid']) {
                $pager = new DooPager(Doo::conf()->APP_URL . 'project/' . $this->params['pmid'] . '/section/' . $this->params['pmid'] . '/files/user/' . $this->params['userid'] . '/page', $totalArchive, 20, 100);
            } else {
                $pager = new DooPager(Doo::conf()->APP_URL . 'project/' . $this->params['pmid'] . '/section/' . $this->params['pmid'] . '/files/page', $totalArchive, 20, 100);
            }
            $pager->setCss('', 'disabled', 'active');
            if (isset($this->params['pindex']))
                $pager->paginate(intval($this->params['pindex']));
            else
                $pager->paginate(1);
            $this->data['itemMeasureArray'] = $this->itemmeasurenum->getItemMeasureNum($this->params['pmid'], $pager->limit, $this->params['numpname'], $this->params['userid']);
        }

        foreach ($this->data['itemMeasureArray'] as $k => $v) {
            $fileArray = $this->itemfle->getItemFile($v['iaid']);
            $this->data['itemMeasureArray'][$k]['realname'] = $this->profile->getProWithUid($v['ownerid'])['name'];
            $this->data['itemMeasureArray'][$k]['pmname'] = $this->actmeasure->getRowByPmid($v['pmid'])['pmname'];
            $this->data['itemMeasureArray'][$k]['filename'] = $fileArray['filename'];
            $this->data['itemMeasureArray'][$k]['fileext'] = $fileArray['fileext'];
            $this->data['itemMeasureArray'][$k]['tips'] = $v['tips'];
        }

        $this->data['pid'] = $this->params['pid'];
        $this->data['pmid'] = $this->params['pmid'];
        $this->data['mpid'] = $this->params['mpid'];
        $this->data['userid'] = $this->params['userid'];
        $this->data['num'] = $this->params['numpname'];
        $this->data['pager'] = $pager->output;
        $this->render('s-project-section-files', $this->data, TRUE);
    }

    function proSectionFilesRecover()
    {
        if (isset($_POST['optype']) && ($_POST['optype'] == 'reconvery') && isset($_POST['imnid'])) {
            $imnidArray = $this->itemmeasurenum->getRowData($_POST['imnid']);
            if ($imnidArray['iaid'] > 0) {
                $this->itemmeasurenum->recoveryDel($_POST['imnid']);
                echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                die();
            }
        }

        if (isset($_POST['optype']) && ($_POST['optype'] == 'del') && isset($_POST['imnid'])) {
            $imnidArray = $this->itemmeasurenum->getRowData($_POST['imnid']);
            if ($imnidArray['iaid'] > 0) {
                $iaidArray = $this->itemfle->getItemFile($imnidArray['iaid']);
                if ($iaidArray['ownerid'] == $this->auth->getUid()) {
                    $this->itemfle->delItem($imnidArray['iaid']);
                    $this->itemmeasurenum->delItemIAID($imnidArray['iaid']);
                    echo json_encode(array('status' => 1), JSON_UNESCAPED_UNICODE);
                    die();
                } else {
                    echo json_encode(array('status' => 2), JSON_UNESCAPED_UNICODE);
                    die();
                }
            }
        }

        // 面包屑导航项目
        $this->data['currproArray'] = $this->data['allproArray'] = NULL;
        $proArray = $this->actmeasure->getGroupProject($this->auth->getUid());
        foreach ($proArray as $v) {
            $pidArray[] = $v['pid'];
        }
        $pidstr = implode(',', $pidArray);
        // 项目名称
        $allproArray = $this->project->getFewRow($pidstr);
        // 面包屑导航项目
        foreach ($allproArray as $kk => $vv) {
            if ($vv['pid'] == $this->params['pid']) {
                $this->data['currproArray'] = $vv;
            } else {
                $this->data['allproArray'][] = $vv;
            }
        }
// 面包屑导航合同
        $conArray = $this->contractact->getAll();
        $measureArray = $this->actmeasure->getRowByPmid($this->params['pmid']);
        if (isset($measureArray['stid'])) {
            foreach ($conArray as $kkk => $vvv) {
                if ($vvv['stid'] == $measureArray['stid']) {
                    $this->data['currconArray'] = $vvv;
                } else {
                    if ($vvv['pid'] == $this->params['pid'])
                        $this->data['allconArray'][] = $vvv;
                }
            }
        } else {
            $this->data['currconArray'] = $this->data['allconArray'] = NULL;
        }
// 面包屑导航标段
        $this->data['curractmeasureArray'] = NULL;
        $this->data['allactmeasureArray'] = [];
        $actmeasureArray = $this->actmeasure->getRowUser($this->auth->getUid());
        foreach ($actmeasureArray as $kkkk => $vvvv) {
            if ($vvvv['stid'] == $measureArray['stid']) {
                if (($vvvv['pmid'] == $this->params['pmid'])) {
                    $this->data['curractmeasureArray'] = $vvvv;
                } else {
                    $this->data['allactmeasureArray'][] = $vvvv;
                }
            }
        }

        $totalArchive = $this->itemmeasurenum->getCount($this->params['pmid']);
        if ($totalArchive) {
            $pager = new DooPager(Doo::conf()->APP_URL . 'sproject/' . $this->params['pmid'] . '/section/' . $this->params['pmid'] . '/files/recover/page', $totalArchive, 20, 100);
            $pager->setCss('', 'disabled', 'active');
            if (isset($this->params['pindex']))
                $pager->paginate(intval($this->params['pindex']));
            else
                $pager->paginate(1);
            $this->data['itemMeasureArray'] = $this->itemmeasurenum->getItemMeasureNumDel($pager->limit, $this->params['pmid']);
        }


        foreach ($this->data['itemMeasureArray'] as $k => $v) {
            $fileArray = $this->itemfle->getItemFile($v['iaid']);
            $this->data['itemMeasureArray'][$k]['realname'] = $this->profile->getProWithUid($v['ownerid'])['name'];
            $this->data['itemMeasureArray'][$k]['delname'] = $this->profile->getProWithUid($v['deluid'])['name'];
            $this->data['itemMeasureArray'][$k]['pmname'] = $this->actmeasure->getRowByPmid($v['pmid'])['pmname'];
            $this->data['itemMeasureArray'][$k]['filename'] = $fileArray['filename'];
            $this->data['itemMeasureArray'][$k]['fileext'] = $fileArray['fileext'];
            $this->data['itemMeasureArray'][$k]['tips'] = $v['tips'];
            $this->data['itemMeasureArray'][$k]['filepath'] = $fileArray['filepath'];
        }
        $this->data['pid'] = $this->params['pid'];
        $this->data['pmid'] = $this->params['pmid'];
        $this->data['mpid'] = $this->params['mpid'];
        $this->data['pager'] = $pager->output;
        $this->render('s-project-section-files-recover', $this->data, TRUE);
    }

    /**
     * @return actMeasure
     */
    public function proSectionGetFiles()
    {
        $attaArray = $this->itemfile->getItemFile($this->params['iaid']);
        $this->file_down($attaArray['filepath'], $attaArray['filesize'], $attaArray['filename'] . '.' . $attaArray['fileext']);
        return;
    }

    public function proSectionInterMediate(){

        //草图功能开关控制
        if($this->data['imediateSwitch'] == 0){
            exit('中间计量表草图添加功能未启用...');
        }

        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));
        }

        $this->data['currproArray'] = $this->data['allproArray'] = NULL;
        $proArray = $this->actmeasure->getGroupProject($this->auth->getUid());
        foreach ($proArray as $v) {
            $pidArray[] = $v['pid'];
        }
        $pidstr = implode(',', $pidArray);
        // 项目名称
        $allproArray = $this->project->getFewRow($pidstr);
        // 面包屑导航项目
        foreach ($allproArray as $kk => $vv) {
            if ($vv['pid'] == $this->params['pid']) {
                $this->data['currproArray'] = $vv;
            } else {
                $this->data['allproArray'][] = $vv;
            }
        }
        // 面包屑导航合同
        $conArray = $this->contractact->getAll();
        $measureArray = $this->actmeasure->getRowByPmid($this->params['pmid']);
        if (isset($measureArray['stid'])) {
            foreach ($conArray as $kkk => $vvv) {
                if ($vvv['stid'] == $measureArray['stid']) {
                    $this->data['currconArray'] = $vvv;
                } else {
                    if ($vvv['pid'] == $this->params['pid'])
                        $this->data['allconArray'][] = $vvv;
                }
            }
        } else {
            $this->data['currconArray'] = $this->data['allconArray'] = NULL;
        }
        // 面包屑导航标段
        $this->data['curractmeasureArray'] = NULL;
        $this->data['allactmeasureArray'] = [];
        $actmeasureArray = $this->actmeasure->getRowUser($this->auth->getUid());
        foreach ($actmeasureArray as $kkkk => $vvvv) {
            if ($vvvv['stid'] == $measureArray['stid']) {
                if (($vvvv['pmid'] == $this->params['pmid'])) {
                    $this->data['curractmeasureArray'] = $vvvv;
                } else {
                    $this->data['allactmeasureArray'][] = $vvvv;
                }
            }
        }

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

        //获取项目信息
        $searchsql = 'isinter!=0 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'])){
            $pagestr .= '/'.$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'])){
                $pagestr .= '/section/'.$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){
                        $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->getSignNum($sqlstr.' and '.$searchsql);
        $pager = new DooPager(Doo::conf()->APP_URL . 'sproject'.$pagestr.'/intermediate/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' ? 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->data['pid'] = $this->params['pid'];
        $this->data['pmid'] = $this->params['pmid'];
        $this->render('s-project-section-intermediate', $this->data, TRUE);
    }

    public function interMediateMake(){

        //草图功能开关控制
        if($this->data['imediateSwitch'] == 0){
            exit('中间计量表草图添加功能未启用...');die;
        }

        if(isset($this->params['sid']) && is_numeric($this->params['sid'])){
            //获取报表信息
            $signmsg = $this->sign->getOneSignbysid($this->params['sid']);
            if(!empty($signmsg) && ($signmsg['isinter'] == 1 || $signmsg['isinter'] == 2)){
                if($signmsg['pagenum'] == 0){
                    exit('当前中间计量表还没上传图片~');die;
                }
                $this->data['sid'] = $signmsg['sid'];
                $this->data['pid'] = $signmsg['project'];
                $this->data['pmid'] = $signmsg['tender'];
                $this->data['name'] = $signmsg['name'];
                $this->data['totalnum'] = $signmsg['pagenum'];
                if(isset($this->params['page']) && is_numeric($this->params['page'])){
                    $this->data['currnum'] = $this->params['page'];
                    $this->data['lastnum'] = $this->params['page'] - 1 > 0 ? ($this->params['page'] - 1) : '';
                    $this->data['nextnum'] = $this->params['page'] + 1 > $signmsg['pagenum'] ? '' : ($this->params['page'] + 1);
                    $signattmsg = $this->sign->getOneSignAtt($this->params['sid'],$this->params['page']);
                }else{
                    $this->data['currnum'] = 1;
                    $this->data['lastnum'] = '';
                    $this->data['nextnum'] = 1 + 1 > $signmsg['pagenum'] ? '' : 2;
                    $signattmsg = $this->sign->getOneSignAtt($this->params['sid'],1);
                }

                //获取报表图片
                $maxwidth = 794; //默认图片最大宽度   a4
                $maxheight = 1123; //默认图片最大高度  a4

                $imgmsg = getimagesize(Doo::conf()->APP_URL.$signattmsg['filepath']);
                $maxwidth = $imgmsg[0];
                $maxheight = $imgmsg[1];

                $this->data['maxwidth'] = $maxwidth;
                $this->data['maxheight'] = $maxheight;

                if($this->is_pjax()){
                    echo '<div class="page" style="width:'.$maxwidth.'px" id="intermediatePage'.$this->data['currnum'].'"><input type="hidden" value="'.$this->data['currnum'].'" id="pagecurrnum"><img src="'.Doo::conf()->APP_URL.$signattmsg['filepath'].'"></div>';exit;
                }

                $this->data['attmsg'] = $signattmsg;

                $this->render('s-project-section-intermediate-detail', $this->data, TRUE);die;
            }
        }
        exit('没有中间计量表参数');
    }

    public function interMediateUpload(){
        if(isset($this->params['sid']) && is_numeric($this->params['sid']) && isset($_POST['num']) && isset($_POST['data'])){
            $signmsg = $this->sign->getOneSignbysid($this->params['sid']);
            if(!empty($signmsg) && ($signmsg['isinter'] == 1 || $signmsg['isinter'] == 2)){
                if(empty($_POST['data']) && $_POST['num'] == $signmsg['pagenum']){
                    $this->sign->updateInterMediateStatus($this->params['sid'],3);
                    $status = array('code' => 202, 'msg' => '最后一张已上传完毕');
                    echo json_encode($status, JSON_UNESCAPED_UNICODE);
                    die();
                }
                preg_match('/^(data:\s*image\/(\w+);base64,)/', $_POST['data'], $result);
                $img = base64_decode(str_replace($result[1], '', $_POST['data']));
                //path
                $dir = 'signs/'.$this->params['sid'].'/intermediate';
                if (!$this->dir_create2(Doo::conf()->SITE_PATH . $dir)) {
                    $status = array('status' => 400, 'msg' => '文件夹创建失败');
                    echo json_encode($status, JSON_UNESCAPED_UNICODE);
                    die();
                }
                $virtualPath = $dir.'/'.$_POST['num'].'.jpg';
                $a = file_put_contents(Doo::conf()->SITE_PATH .$virtualPath,$img);
                if($a){
                    //更新signatt表信息
                    $result = $this->sign->updateSignAtt($this->params['sid'],$_POST['num'],$virtualPath);
                    if($result){
                        if($_POST['num'] == $signmsg['pagenum']){
                            $this->sign->updateInterMediateStatus($this->params['sid'],3);
                            $status = array('code' => 202, 'msg' => '最后一张已上传完毕');
                            echo json_encode($status, JSON_UNESCAPED_UNICODE);
                            die();
                        }else{
                            $status = array('code' => 200, 'msg' => '');
                            echo json_encode($status, JSON_UNESCAPED_UNICODE);
                            die();
                        }
                    }
                }
                $status = array('code' => 400, 'msg' => '上传中间计量表失败');
                echo json_encode($status, JSON_UNESCAPED_UNICODE);
                die();
            }
        }
        $status = array('code' => 400, 'msg' => '参数有误，不存在此中间计量表或此中间计量表已合成');
        echo json_encode($status, JSON_UNESCAPED_UNICODE);
        die();
    }

    /**
     *
     * @return type
     */
    public function signView()
    {
        //草图功能开关控制
        if($this->data['imediateSwitch'] == 0){
            exit('中间计量表草图添加功能未启用...');die;
        }

        if(!isset($this->params['sid']) || !is_numeric($this->params['sid'])){
            exit('没有报表参数');
        }
        //获取报表信息
        $signmsg = $this->sign->getOneSignbysid($this->params['sid']);
        if(empty($signmsg) || $signmsg['isinter'] != 3){
            exit('不存在此中间计量表');
        }

        $backurl = '/sproject/'.$signmsg['project'].'/section/'.$signmsg['tender'].'/intermediate';
        //获取项目名，标段名，标段期数
        $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];
                }
            }
        }

        $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);
    }

    function is_pjax(){
        return array_key_exists('HTTP_X_PJAX', $_SERVER) && $_SERVER['HTTP_X_PJAX'] === 'true';
    }

    /**
     * 文件下载
     * @param $filepath 文件路径
     * @param $filename 文件名称
     */
    function file_down($filepath, $filesize, $filename = '')
    {
        if (!$filename)
            $filename = basename($filepath);
        if ($this->is_ie())
            $filename = rawurlencode($filename);
        $filetype = $this->fileext($filename);
//        $filesize = sprintf("%u", filesize($filepath));
        if (ob_get_length() !== false)
            @ob_end_clean();
        header('Pragma: public');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Cache-Control: pre-check=0, post-check=0, max-age=0');
        header('Content-Transfer-Encoding: binary');
        header('Content-Encoding: none');
        header('Content-type: ' . $filetype);
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-length: ' . $filesize);
        @readfile($filepath);
        exit;
    }

    /**
     * IE浏览器判断
     */
    function is_ie()
    {
        $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if ((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false))
            return false;
        if (strpos($useragent, 'msie ') !== false)
            return true;
        return false;
    }

    /**
     * 取得文件扩展
     *
     * @param $filename 文件名
     * @return 扩展名
     */
    function fileext($filename)
    {
        return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
    }

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

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


}

?>