<?php

/**
 *
 */

include_once(dirname(dirname(__FILE__)) . "/library/publicBase.php");
include_once(SERVER_ROOT . "/model/mPage.php");

class index extends publicBase {

    private function _check_login() {
        $uid = $this->post('uid');
        $token = $this->post('token');
        if ($uid < 0 || !$token) $this->ajax_json(false, '参数错误', array('code' => CODE_LOGIN_EXIPRE));

        $m_user = new mUser();
        $is_login = $m_user->validateToken($uid, $token);
        if (!$is_login) $this->ajax_json(false, '未登录或登录已经失效', array('code' => CODE_LOGIN_EXIPRE));

        $obj = new mUser();
        $uinfo = $obj->getUserByUid($uid);
        if (empty($uinfo)) $this->ajax_json(false, '用户不存在', array('code' => CODE_LOGIN_USER_NOT_EXIST));

        return $uinfo;
    }

    public function login() {
        $name = $this->get('name');
        $password = $this->get('password');

        $m_user = new mUser();
        $robj = $m_user->initRedis();

        $user_info = $robj->get(_QR_ADMIN_USER_INFO);
        if (!empty($name) && !empty($password)) {
            $user_info = json_decode($user_info, true);
            if ($user_info['name'] == $name && $user_info['password'] == $password) {
                //设置登录状态
                $robj->setex(_QR_ADMIN_LOGIN_USER_INFO, 12 * 60 * 60, json_encode(array('uid' => 0, 'token' => $m_user->getToken(0))));
                header('Location: /index/home');
            }
        }

        if (empty($user_info)) {
            $robj->setex(_QR_ADMIN_USER_INFO, 12 * 60 * 60, json_encode(array('name' => 'admin', 'password' => bin2hex(openssl_random_pseudo_bytes(8)))));
        }
    }

    public function home() {
        $mformula = new mFormula();
        $robj = $mformula->initRedis();
        $user_info = $robj->get(_QR_ADMIN_LOGIN_USER_INFO);
        $user_info = json_decode($user_info, true);
        if (empty($user_info)) header('Location: /index/login');

        $is_all = $this->get('is_all') + 0;
        $name = trim($this->get('name'));

        $condition = array();
        if ($name) $condition['name'] = $name;
        if (!$is_all) $condition['uid'] = 0;

        $total = $mformula->getFormulaTotal($condition);

        // 分页
        $page = new Page();
        $page->setTotalnum($total);
        $page->setUrl('/index/home/page/');
        $curpage = $this->get('page') > 0 ? $this->get('page') : 1;
        $page->setPage($curpage);

        $this->view['page_list'] = $page->getPageList();
        $this->view['curpage'] = $curpage;

        if ($curpage > 1) $this->view['prev_page'] = $page->url . ($curpage - 1); //上一页连接
        if ($curpage < $page->totalpage) $this->view['post_page'] = $page->url . ($curpage + 1); //下一页连接

        //只取出当前页显示
        $list = $mformula->getFormulaList($condition, $curpage, $page->pagesize);

        $this->view['list'] = $list;
    }

    public function formula_add() {
        $mformula = new mFormula();
        $robj = $mformula->initRedis();
        $user_info = $robj->get(_QR_ADMIN_LOGIN_USER_INFO);
        $user_info = json_decode($user_info, true);
        if (empty($user_info)) header('Location: /index/login');

        $this->view['uid'] = $user_info['uid'];
        $this->view['token'] = $user_info['token'];

        $id = $this->get('id');
        if ($id) {
            $mformula = new mFormula();
            $data = $mformula->getFormulaInfo($id, 0);

            $this->view['data'] = $data;
        }
    }

    public function ajax_save_formula() {
        $uinfo = $this->_check_login();

        $name = trim($this->post('name'));
        $source = trim($this->post('source'));
        $method = trim($this->post('method'));
        $herbs = $this->post('herbs');

        $mformula = new mFormula();

        //生成唯一id 防止重复请求
        $request_id = md5($uinfo['uid'] . $name . $source . $herbs);
        $request_times = $mformula->requestLimit(sprintf(_QR_REQUEST_LIMIT, $request_id), 1, 60);
        if (!$request_times) $this->ajax_json(false, $mformula->getError());

        //新增药方
        $id = $mformula->createFormula($uinfo['uid'], $name, $source, $method, $herbs);
        if (!$id) $this->ajax_json(false, $mformula->getError());

        $this->ajax_json(true, '添加成功', array('id' => $id));
    }

    public function ajax_update_formula() {
        $uinfo = $this->_check_login();

        $id = $this->post('id') + 0;
        $name = trim($this->post('name'));
        $source = trim($this->post('source'));
        $method = trim($this->post('method'));
        $herbs = $this->post('herbs');

        $mformula = new mFormula();
        $res = $mformula->saveFormula($uinfo['uid'], $id, $name, $source, $method, $herbs);
        if (!$res) $this->ajax_json(false, $mformula->getError());

        $this->ajax_json(true, '保存成功');
    }

    public function ajax_user_formula() {
        $uinfo = $this->_check_login();

        $content = trim($this->post('content'));
        $content = empty($content) ? '' : $content;

        $page_num = $this->post('page_num') ? $this->post('page_num') : 1;
        $page_size = $this->post('page_size') ? $this->post('page_size') : 20;

        $condition = array();
        $condition['uid'] = $uinfo['uid'];
        if ($content) $condition['name'] = $content;

        $mformula = new mFormula();
        $list = $mformula->getFormulaList($condition, $page_num, $page_size);
        $total = $mformula->getFormulaTotal($condition);

        $rdata = array(
            'total' => $total,
            'per_page' => $page_size,
            'last_page' => ceil($total / $page_size),
            'current_page' => $page_num,
            'list' => $list,
        );

        $this->ajax_json(true, '获取成功', $rdata);
    }

    public function ajax_user_formula_detail() {
        $uinfo = $this->_check_login();

        $id = $this->post('id') + 0;
        if (!$id) $this->ajax_json(false, '参数错误');

        $mformula = new mFormula();
        $data = $mformula->getFormulaInfo($id, $uinfo['uid']);
        if (!$data) $this->ajax_json(false, $mformula->getError());

        $this->ajax_json(true, '获取成功', $data);
    }

    public function ajax_search() {
        $uinfo = $this->_check_login();

        $content = trim($this->post('content'));
        $content = empty($content) ? '' : $content;

        $page_num = $this->post('page_num') ? $this->post('page_num') : 1;
        $page_size = $this->post('page_size') ? $this->post('page_size') : 20;


        $condition = array();
        $condition['uid'] = array(0,$uinfo['uid']);
        if ($content) $condition['name'] = $content;

        $mformula = new mFormula();
        $list = $mformula->getFormulaList($condition, $page_num, $page_size);
        $total = $mformula->getFormulaTotal($condition);

        $rdata = array(
            'total' => $total,
            'per_page' => $page_size,
            'last_page' => ceil($total / $page_size),
            'current_page' => $page_num,
            'list' => $list,
        );

        $this->ajax_json(true, '获取成功', $rdata);
    }

    public function ajax_formula_detail() {
        $uinfo = $this->_check_login();

        $id = $this->post('id') + 0;
        if (!$id) $this->ajax_json(false, '参数错误');

        $mformula = new mFormula();
        $data = $mformula->getFormulaInfo($id, $uinfo['uid']);
        if (!$data) $this->ajax_json(false, $mformula->getError());

        $this->ajax_json(true, '获取成功', $data);
    }

    public function ajax_save_user_case() {
        $uinfo = $this->_check_login();

        $formula_id = $this->post('formula_id') + 0;

        $data = array(
            'patient_name' => trim($this->post('patient_name')),
            'patient_age' => $this->post('patient_age') + 0,
            'patient_sex' => $this->post('patient_sex') + 0,
            'patient_say' => trim($this->post('patient_say')),
            'first_diagnosis' => trim($this->post('first_diagnosis')),
            'diagnosis' => trim($this->post('diagnosis')),
            'prescribe_num' => $this->post('prescribe_num') + 0,
            'prescribe_herb' => $this->post('prescribe_herb'),
        );

        $m_user_case = new mUserCase();

        //生成唯一id 防止重复请求
        $request_id = md5($uinfo['uid'] . $formula_id . $data['name'] . $data['patient_name'] . $data['prescribe_herb']);
        $request_times = $m_user_case->requestLimit(sprintf(_QR_REQUEST_LIMIT, $request_id), 1, 60);
        if (!$request_times) $this->ajax_json(false, $m_user_case->getError());

        $id = $m_user_case->createUserCase($uinfo['uid'], $formula_id, $data);
        if (!$id) $this->ajax_json(false, $m_user_case->getError());

        $this->ajax_json(true, '保存成功', array('id' => $id));
    }

    public function ajax_update_user_case() {
        $uinfo = $this->_check_login();

        $id = $this->post('id') + 0;
        if (empty($id)) $this->ajax_json(false, '参数错误');

        $data = array(
            'name' => trim($this->post('name')),
            'feedback' => trim($this->post('feedback')),
        );

        $m_user_case = new mUserCase();
        $res = $m_user_case->saveUserCase($uinfo['uid'], $id, $data);
        if (!$res) $this->ajax_json(false, $m_user_case->getError());

        $this->ajax_json(true, '保存成功', array('id' => $id));
    }

    public function ajax_user_case_list() {
        $uinfo = $this->_check_login();

        $page_num = $this->post('page_num') ? $this->post('page_num') : 1;
        $page_size = $this->post('page_size') ? $this->post('page_size') : 100;

        $m_user_case = new mUserCase();
        $data = $m_user_case->getUserCaseList($uinfo['uid'], $page_num, $page_size);
        $total = $m_user_case->getUserCaseListCount($uinfo['uid']);

        $rdata = array(
            'total' => $total,
            'per_page' => $page_size,
            'last_page' => ceil($total / $page_size),
            'current_page' => $page_num,
            'data' => $data
        );

        $this->ajax_json(true, '获取成功', $rdata);
    }

    public function ajax_user_case_detail() {
        $uinfo = $this->_check_login();

        $id = $this->post('id') + 0;
        if (empty($id)) $this->ajax_json(false, '参数错误');

        $m_user_case = new mUserCase();
        $data = $m_user_case->getUserCaseInfo($uinfo['uid'], $id);
        if (!$data) $this->ajax_json(false, $m_user_case->getError());

        $this->ajax_json(true, '获取成功', $data);
    }

    public function ajax_collect_log() {
        $page_num = $this->post('page_num') ? $this->post('page_num') : 1;
        $page_size = $this->post('page_size') ? $this->post('page_size') : 100;

        $mformula = new mFormula();
        $data = $mformula->getCollectLog($page_num, $page_size);
        $total = $mformula->getCollectLogTotal();

        $rdata = array(
            'total' => $total,
            'per_page' => $page_size,
            'last_page' => ceil($total / $page_size),
            'current_page' => $page_num,
            'data' => $data
        );

        $this->ajax_json(true, '获取成功', $rdata);
    }

    public function ajax_login() {
        $code = $this->post('code');
        if (!$code) $this->ajax_json(false, '参数错误');

        $m_user = new mUser();
        $user = $m_user->getUserInfo($code);
        if (!$user) $this->ajax_json(false, $m_user->getError());

        $token = $m_user->getToken($user['uid']);

        $this->ajax_json(true, '登录成功', array(
            'uid' => $user['uid'],
            'identifier' => $user['identifier'],
            'token' => $token
        ));
    }

    public function ajax_get_user() {
        $uinfo = $this->_check_login();

        $this->ajax_json(true, '获取成功', $uinfo);
    }

    public function ajax_contact_us() {
        $this->ajax_json(true, '获取成功', array('img_url' => CONTACT_US_IMG_URL));
    }

    public function export_user_case() {
        $uinfo = $this->_check_login();

        $id = $this->post('id') + 0;

        //导出单个医案
        if ($id > 0) {
            $post_url = USER_CASE_HTML_URL;
            $data = array(
                "uid" => $uinfo['uid'],
                "id" => $id,
            );
        }

        //导出全部医案
        if ($id == 0) {
            $post_url = USER_CASE_LIST_HTML_URL;
            $data = array(
                "uid" => $uinfo['uid'],
                "start_date" => $this->post('start_date'),
                "end_date" => $this->post('end_date'),
            );
        }

        $m_user_case = new mUserCase();
        $return = $m_user_case->postCUrl($post_url, $data);

        $res = json_decode($return, 1);
        if (isset($res['info'])) $this->ajax_json(false, '未查询到可导出的医案记录');

        $pdf_name = md5($uinfo['uid'] . $id) . ".pdf";
        $m_user_case->createPdf($uinfo['uid'], $pdf_name, $return);

        $email = $this->post('email');
        if (!empty($email)) {
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $this->ajax_json(false, '邮箱地址无效');
            $res = $m_user_case->sendMail(array($email), date('Y年m月d日', time()) . '-医案导出', '', sprintf(USER_CASE_PDF_PATH, $uinfo['uid']) . $pdf_name);
            if (!$res) $this->ajax_json(true, '发送失败');
            $this->ajax_json(true, '发送成功');
        }

        $this->ajax_json(true, '获取成功', array('pdf_url' => sprintf(USER_CASE_PDF_URL, $uinfo['uid']) . $pdf_name));
    }

    public function user_case_list() {
        $uid = $this->post('uid') + 0;
        if (empty($uid)) $this->ajax_json(false, '参数错误');

        $start_date = $this->post('start_date');
        if (empty($start_date)) $this->ajax_json(false, '请选择导出开始时间');

        $end_date = $this->post('end_date');
        if (empty($end_date)) $this->ajax_json(false, '请选择导出结束时间');

        $page_num = $this->post('page_num') ? $this->post('page_num') : 1;
        $page_size = $this->post('page_size') ? $this->post('page_size') : 500;

        $m_user_case = new mUserCase();
        $data = $m_user_case->getUserCaseListPdfInfo($uid, $page_num, $page_size, $start_date, $end_date);
        if (!$data) $this->ajax_json(false, $m_user_case->getError());

        $this->view['data'] = $data;
        $this->setViewTpl('index/export_pdf.html');
    }

    public function user_case() {
        $id = $this->post('id') + 0;
        $uid = $this->post('uid') + 0;
        if (empty($uid) || empty($id)) $this->ajax_json(false, '参数错误');

        $m_user_case = new mUserCase();
        $data = $m_user_case->getUserCasePdfInfo($uid, $id);
        if (!$data) $this->ajax_json(false, $m_user_case->getError());

        $this->view['data'] = array($data);
        $this->setViewTpl('index/export_pdf.html');
    }
}