<?php

session_start(); // starts new or resumes existing session
Doo::loadModelAt('auser', 'admin');
Doo::loadModelAt('ausers', 'admin');
Doo::loadModelAt('ameasure', 'admin');
Doo::loadModelAt('fileup', 'admin');
Doo::loadModelAt('measureaudit', 'admin');
Doo::loadModelAt('numofper', 'admin');
Doo::loadModel('users');
Doo::loadClass('profile');
Doo::loadClass('contractact');
Doo::loadClass('PasswordHash');
Doo::loadClass('mailer');
Doo::loadClass('project');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

// 列表停用 编辑 重置密码
// 管理员权限管理
// 管理员修改密码
class ItemController extends DooController {

    private $data, $users, $user, $profile, $ph, $userz, $mailer, $project, $am, $cc, $an, $ama, $statusArray = array('checking' => '审批中', 'checked' => '完成', 'checkno' => '不通过'), $colorArray = array('checking' => 'colOrange', 'checked' => 'colGreen', 'checkno' => 'colRed');

    public function beforeRun($resource, $action) {
        if (!isset($_SESSION['auid'])) {
            return Doo::conf()->APP_URL . 'manage';
        }
    }

    public function __construct() {
        $this->users = new AUsers();
        $this->user = new AUser();
        $this->userz = new Users();
        $this->profile = new Profile();
        $this->mailer = new Mailer();
        $this->ph = new PasswordHash(8, FALSE);
        $this->am = new Ameasure();
        $this->ama = new AmeasureAudit();
        $this->af = new Afileup();
        $this->an = new Anumofper();
        $this->project = new Project();
        $this->cc = new Contractact();
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
    }

    function addUser() {
        $params = NULL;
        if (isset($_POST['email'])) {
            if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $postArray = $_POST;
                $passwdStr = $this->randomPassword();
                $postArray['userid'] = $this->users->createUser($_POST['email'], $passwdStr);
                if (isset($postArray['userid'])) {
                    $this->profile->insertProfile($postArray);
                    $this->mailer->setEmails($_POST['email']);
                    $this->mailer->seteTitle('新账号开通');
                    $this->mailer->setClientName($postArray['realname']);
                    $signupConfigStr = '<p>开通了计量支付云版的帐号：</p><p>登录帐号（邮箱）：<b><a href="mailto:' . $_POST['email'] . '" target="_blank">' . $_POST['email'] . '</a></b></p><p>登录密码：<b>' . $passwdStr . '</b></p><p>请及时登录并修改您的个人信息及密码。</p><p><b style="font-size:20px">登录云端，下载桌面软件：</b><br><a href="'.Doo::conf()->APP_URL.'" style="font-size:20px">'.Doo::conf()->APP_URL.'</a></p>';
                    $this->mailer->setContent($signupConfigStr);
                    $this->mailer->send_mail();
                    return Doo::conf()->APP_URL . 'manage/user/list';
                } else {
                    return Doo::conf()->APP_URL . 'manage/user/add';
                }
            } else {
                return Doo::conf()->APP_URL . 'manage/user/add';
            }
        }
        $this->render('admin-addUser', $this->data, TRUE);
    }

    public function randomPassword() {
        $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }

    function editUser() {
        $this->data['users'] = $this->users->getOne(array('where' => 'uid = ?', 'param' => array($this->params['uid']), 'asArray' => TRUE));
        $this->data['profile'] = $this->profile->getProWithUid($this->params['uid']);
        if (isset($_POST['email']) && ($_POST['email'] != $this->data['users']['uemail']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            if (!$this->userz->getOne(array('where' => 'uemail = ?', 'param' => array($_POST['email']), 'asArray' => TRUE))) {
                $this->userz->uemail = $_POST['email'];
                $this->userz->update(array('where' => 'uid = ?', 'param' => array($this->params['uid'])));
            }
        }
        if (isset($_POST['company']) && isset($_POST['jobs']) && isset($_POST['name']) && isset($_POST['phone']) && isset($_POST['mobile'])) {
            $this->profile->upProfile($this->params['uid'], $_POST);
            return Doo::conf()->APP_URL . 'manage/user/list';
        }
        $this->render('admin-editUser', $this->data, TRUE);
    }

    function option() {
        $this->data['auser'] = $this->user->getOne(array('where' => 'auid = ?', 'param' => array($_SESSION['auid']), 'asArray' => TRUE));
        if (isset($_POST['oldpasswd']) && isset($_POST['newpasswd']) && isset($_POST['renewpasswd']) && ($_POST['newpasswd'] == $_POST['renewpasswd']) && $this->ph->CheckPassword($_POST['oldpasswd'], $this->data['auser']['aupass'])) {
            $this->user->upPasswWd($_SESSION['auid'], $this->ph->HashPassword($_POST['newpasswd']));
            return Doo::conf()->APP_URL . 'manage/user/list';
        }
        $this->render('admin-option', $this->data, TRUE);
    }

    function userSwitch() {
        $userzArray = $this->userz->getOne(array('where' => 'uid = ?', 'param' => array($this->params['uid']), 'asArray' => TRUE));
        if (isset($userzArray['uid']) && $userzArray['isstop']) {
            $this->userz->isstop = 0;
        } else {
            $this->userz->isstop = 1;
        }
        $this->userz->update(array('where' => 'uid = ?', 'param' => array($this->params['uid'])));
        return Doo::conf()->APP_URL . 'manage/user/list';
    }

    function userRepasswd() {
        $userzArray = $this->userz->getOne(array('where' => 'uid = ?', 'param' => array($this->params['uid']), 'asArray' => TRUE));
        if (isset($userzArray['uemail'])) {
            $passwdStr = $this->randomPassword();
            $this->userz->upass = $this->ph->HashPassword($passwdStr);
            if ($this->userz->update(array('where' => 'uid=?', 'param' => array($this->params['uid'])))) {
                $proArray = $this->profile->getProWithUid($this->params['uid']);
                $this->mailer->setEmails($userzArray['uemail']);
                $this->mailer->seteTitle('密码重置');
                $this->mailer->setClientName($proArray['name']);
                $signupConfigStr = '<p>重置了计量支付云版的帐号密码：</p><p>登录帐号（邮箱）：<b><a href="mailto:' . $userzArray['uemail'] . '" target="_blank">' . $userzArray['uemail'] . '</a></b></p><p>登录密码：<b>' . $passwdStr . '</b></p><p>请及时登录并修改您的新密码。</p>';
                $this->mailer->setContent($signupConfigStr);
                $this->mailer->send_mail();
                echo $userzArray['uemail'];
            }
        }
    }

    function userList() {
        if (isset($_SESSION['passwd'])) {
            echo '添加用户的密码是：' . $_SESSION['passwd'];
        }
        $this->data['userlist'] = $this->users->getRowAll();
        foreach ($this->data['userlist'] as $key => $value) {
            $proArray = $this->profile->getProWithUid($value['uid']);
            if (isset($proArray)) {
                $this->data['userlist'][$key]['name'] = $proArray['name'];
                $this->data['userlist'][$key]['company'] = $proArray['company'];
                $this->data['userlist'][$key]['jobs'] = $proArray['jobs'];
                $this->data['userlist'][$key]['phone'] = $proArray['phone'];
                $this->data['userlist'][$key]['mobile'] = $proArray['mobile'];
                $this->data['userlist'][$key]['isstop'] = $value['isstop'];
            }
            unset($proArray);
            $this->data['userlist'][$key]['email'] = $value['uemail'];
        }
        $this->data['menu'] = 2;
        $this->render('admin-userlist', $this->data, TRUE);
    }

    function itemList() {
        // TODO：增加判断审批人期数和上报最新期数比较来显示是否需要显示删除审批人操作
        // TODO：提示信息：可能显示的是瞬时状态，需要与客户经过确认之后方可删除。
        // TODO：审批人状态和标段状态暂未加入审批人与标段是否一直的判断
        if ($this->params['pid'] > 0) {
            $mArray = $this->am->getRowAll($this->params['pid']);
            $this->data['pid'] = $this->params['pid'];
        }
        foreach ($mArray as $key => $value) {
            $mArray[$key]['contracttotal'] = number_format($value['contracttotal'], 2, '.', ',');
            $mArray[$key]['stname'] = $this->cc->getRowByStid($value['stid'])['stname'];
            $tmp = $this->an->getOne(array('where' => 'pmid=?', 'param' => array($value['pmid']), 'groupby' => 'numpname', 'desc' => 'numpname', 'asArray' => TRUE));
            if ($tmp) {// 没有标段数据
                $mArray[$key]['has'] = 1;
                $mArray[$key]['status'] = $this->statusArray[$tmp['currstatus']];
                $mArray[$key]['color'] = $this->colorArray[$tmp['currstatus']];
                $mArray[$key]['numpname'] = $tmp['numpname'];
                $intTimes = $this->ama->getOne(array('where' => 'pmid=? and numpname=?', 'param' => array($value['pmid'], $tmp['numpname']), 'groupby' => 'times', 'desc' => 'times', 'asArray' => TRUE))['times'];
                $auditArray = $this->ama->find(array('where' => 'pmid=? and numpname=? and times=?', 'param' => array($value['pmid'], $tmp['numpname'], $intTimes), 'asArray' => TRUE));
                foreach ($auditArray as $k => $v) {
                    if (($v['last'] == 1) && ($v['mastatus'] != 'uncheck')) {
                        $mArray[$key]['auditor'] = $this->profile->getProWithUid($v['auditoruid'])['name'];
                        $mArray[$key]['auditor'] = '终审-' . $mArray[$key]['auditor'];
                        $mArray[$key]['auditstatus'] = $this->statusArray[$v['mastatus']];
                        break;
                    } elseif (($v['last'] == 2) && ($v['mastatus'] != 'uncheck')) {
                        $mArray[$key]['auditor'] = $this->profile->getProWithUid($v['auditoruid'])['name'];
                        $mArray[$key]['auditstatus'] = $this->statusArray[$v['mastatus']];
                        $mArray[$key]['auditnum'] = $k . '审';
                    }
                }
            } else {
                $mArray[$key]['has'] = 0;
            }
        }
        $pArray = $this->project->getAll();
        $this->data['userlist'] = $mArray;
        $this->data['pArray'] = $pArray;
        $this->data['menu'] = 4;
        $this->render('admin-item', $this->data, TRUE);
    }

    function itemDel() {
        $this->am->delete(array('where' => 'pmid=?', 'param' => array($this->params['pmid'])));
        $this->ama->delete(array('where' => 'pmid=?', 'param' => array($this->params['pmid'])));
        $this->af->delete(array('where' => 'pmid=?', 'param' => array($this->params['pmid'])));
        $this->an->delete(array('where' => 'pmid=?', 'param' => array($this->params['pmid'])));
        return Doo::conf()->APP_URL . 'manage/item/list';
    }

}
