<?php
/**
 * 账号列表
 *
 * @author Daniel Chen
 */

class Merchant_AccountController extends Ec_Controller_Action {
  const ACCOUNT_DISABLED = 0;
  const ACCOUNT_ENABLED = 1;

  public function preDispatch() {
    $this->tplDir = 'merchant/views/account/';
    $this->user = $this->_customerAuth;

    // 不是主账号就不要继续了吧
    if (!$this->user['is_master']) {
      header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden', TRUE, 403);
      exit('403 Forbidden');
    }
  }

  /**
   * 账号列表
   */
  public function listAction() {
    $condition = array();
    $data = array();
    $total = 0;
    $page = 1;
    $size = 20;
    $name = '';
    $email = '';

    if ($this->getRequest()->isPost()) {
      $name = trim($this->getRequest()->getPost('account_name', ''));
      $email = trim($this->getRequest()->getPost('account_email', ''));
      $page = trim($this->getRequest()->getPost('page', 0));
      $size = trim($this->getRequest()->getPost('size', 0));
      $condition = array(
        'customer_id' => $this->user['id'],
        'account_name' => $name,
        'account_email' => $email
      );
      $total = Service_Account::getByCondition($condition, TRUE);
      $size = ($size > 0 && $size < 1000) ? (int) $size : 20;
      $maxPage = $total / $size;
      $page = ($page > 0) ? (($maxPage && $page > $maxPage) ? $maxPage : $page) : 1;
      $condition['page'] = $page;
      $condition['size'] = $size;
      $data = Service_Account::getByCondition($condition);
    }
    else {
      $condition = array(
        'customer_id' => $this->user['id'],
        'page' => $page,
        'size' => $size
      );
      $total = Service_Account::getByCondition($condition, TRUE);
      $data = Service_Account::getByCondition($condition);
    }

    $this->view->name = $name;
    $this->view->email = $email;
    $this->view->data = $data;
    $this->view->total = $total;
    $this->view->page = $page;
    $this->view->size = $size;
    $this->view->privilege = Service_AccountPrivilege::getAssignedPrivilege(); // 可分配给子账号的权限

    echo Ec::renderTpl($this->tplDir . 'list.tpl', 'noleftlayout');
  }

  /**
   * 添加子账号
   */
  public function addAction() {
    $tip = '';
    $message = '';
    $name = '';
    $email = '';
    $password = '';
    $repeatPassword = '';

    if ($this->getRequest()->isPost()) {
      $name = trim($this->getRequest()->getPost('account_name', ''));
      $email = trim($this->getRequest()->getPost('account_email', ''));
      $password = trim($this->getRequest()->getPost('account_password', ''));
      $repeatPassword = trim($this->getRequest()->getPost('account_repeat_password', ''));
      $account = array(
        'account_name' => $name,
        'account_email' => $email,
        'account_password' => $password,
        'account_repeat_password' => $repeatPassword
      );
      $validate = $this->validate($account);

      if (!empty($validate)) {
        $tip = 'error';
        $message = join($validate, '；');
      }
      else {
        $date = date('Y-m-d H:i:s');
        $mark = new Common_Customer();
        $accountCode = $mark->markCustomCode('register');
        $account['account_code'] = $accountCode;
        $account['account_password'] = md5($account['account_password']);
        $account['customer_id'] = (int) $this->user['id'];
        $account['customer_code'] = $this->user['code'];
        $account['created_time'] = $date;
        $account['updated_time'] = $date;
        $account['account_status'] = self::ACCOUNT_ENABLED;
        unset($account['account_repeat_password']);
        $accountId = Service_Account::insert($account);

        if ($accountId) {
          $tip = 'info';
          $name = '';
          $email = '';
          $password = '';
          $repeatPassword = '';
        }
        else {
          $tip = 'error';
          $message = '系统错误，添加子账号失败';
        }
      }
    }

    $this->view->tip = $tip;
    $this->view->message = $message;
    $this->view->name = $name;
    $this->view->email = $email;
    $this->view->password = $password;
    $this->view->repeatPassword = $repeatPassword;

    echo Ec::renderTpl($this->tplDir . 'add.tpl', 'noleftlayout');
  }

  /**
   * 更改账号状态
   */
  public function changeStatusAction() {
    $response = array(
      'status' => 0,
      'message' => '非法请求'
    );

    if ($this->getRequest()->isPost()) {
      $type = trim($this->getRequest()->getPost('type', ''));
      $accountId = trim($this->getRequest()->getPost('id', ''));

      if (is_numeric($type)) {
        $type = (int) $type;
      }

      if (is_numeric($accountId)) {
        $accountId = (int) $accountId;
      }

      switch ($type) {
        case self::ACCOUNT_DISABLED:
          if (Service_Account::update(array('account_status' => 0, 'updated_time' => date('Y-m-d H:i:s')), $accountId)) {
            $response['status'] = 1;
            $response['message'] = '已禁用';
          }
          break;

        case self::ACCOUNT_ENABLED:
          if (Service_Account::update(array('account_status' => 1, 'updated_time' => date('Y-m-d H:i:s')), $accountId)) {
            $response['status'] = 1;
            $response['message'] = '已启用';
          }
          break;

        default:
          break;
      }
    }

    exit(Zend_Json::encode($response));
  }

  /**
   * 分配权限
   */
  public function assignPrivilegeAction() {
    $response = array('status' => 0, 'message' => '非法请求');

    if ($this->getRequest()->isPost()) {
      $privilege = $this->getRequest()->getPost('privilege', array());
      $account = (int) $this->getRequest()->getPost('account', 0);

      if (is_array($privilege) && !empty($privilege) && $account) {
        $result = Service_AccountPrivilege::setAccountPrivilege($privilege, $account, $this->user['id']);

        if (TRUE === $result) {
          $response['status'] = 1;
          $response['message'] = '权限分配成功';
        }
        else {
          $response['message'] = $result;
        }
      }
      elseif ($account) {
        $response['message'] = '至少需要分配一项权限';
      }
      else {
        $response['message'] = '传递信息有误';
      }
    }

    exit(Zend_Json::encode($response));
  }

  /**
   * 获取子账号已分配的权限
   */
  public function getAssignedPrivilegeAction() {
    $response = array('status' => 0, 'message' => '非法请求', 'data' => array());

    if ($this->getRequest()->isPost()) {
      $account = (int) $this->getRequest()->getPost('account', 0);
      $privilege = Service_AccountPrivilege::getAccountAssignedPrivilege($account);

      if ($privilege) {
        $response['status'] = 1;
        $response['message'] = '请求成功';
        $response['data'] = $privilege;
      }
      else {
        $response['message'] = '没有找到相应权限';
      }
    }

    exit(Zend_Json::encode($response));
  }

  /**
   * 数据校验
   */
  private function validate($data) {
    $error = array();
    $validPassword = FALSE;
    $validRepeatPassword = FALSE;
    $default = array(
      'account_name' => '',
      'account_email' => '',
      'account_password' => '',
      'account_repeat_password' => ''
    );
    $default = array_merge($default, $data);
    if ('' === $default['account_name']) {
      $error[] = Ec::_('User Name required');
    }
    elseif (!Service_Account::isUniqueName($default['account_name'], $this->user['id'])) {
      $error[] = sprintf(Ec::_("User Name exist"), $default['account_name']);
    }

    if ('' === $default['account_email']) {
      $error[] =Ec::_("email Not be null");
    }
    elseif (FALSE === filter_var($default['account_email'], FILTER_VALIDATE_EMAIL)) {
      $error[] = Ec::_('Incorrect Email');
    }
    elseif (!Service_Account::isUniqueEmail($default['account_email'])) {
      $error[] = sprintf(Ec::_("Email is Regestry"),$default['account_email'] );
    }

    if ('' === $default['account_password']) {
      $error[] = Ec::_('password Not be null');
    }
    elseif (mb_strlen($default['account_password'], 'utf-8') < 6) {
      $error[] = Ec::_("Password must be greater than 6 character(inlude 6 character)");
    }
    else {
      $validPassword = TRUE;
    }

    if ('' === $default['account_repeat_password']) {
      $error[] = Ec::_('Confirm Password Can\'t be null');
    }
    elseif (mb_strlen($default['account_repeat_password'], 'utf-8') < 6) {
      $error[] = Ec::_('Confirm password must be greater than 6 character');
    }
    else {
      $validRepeatPassword = TRUE;
    }

    if ($validPassword && $validRepeatPassword && $default['account_password'] !== $default['account_repeat_password']) {
      $error[] = Ec::_('Password not equal Confirm password');
    }

    return $error;
  }
}
