<?php
/**
 *
 */
include_once(SERVER_ROOT . "/model/mBase.php");
include_once(SERVER_ROOT . "/vendor/mpdf/mpdf/mpdf.php");

class mUserCase extends mBase {
    private $obj;
    private $tbl;
    private $user_herb_tbl;

    public function __construct() {
        $this->obj = new dUserCase();
        $this->tbl = 'tcm_user_case';
        $this->user_herb_tbl = 'tcm_user_herb';
    }

    public function updateUserCase($uid, $id, $data) {
        if (empty($data['name'])) {
            $this->setError('药方名称不能为空');
            return false;
        }
        if (empty($data['feedback'])) {
            $this->setError('用药反馈不能为空');
            return false;
        }

        $res = $this->obj->update($this->tbl, $data, array('sql' => '`id`=? and `uid`=?', 'vals' => array($id, $uid)));
        if (!$res) {
            $this->setError('更新失败');
            return false;
        }

        return true;
    }

    public function formatUserCaseHerbs($uid, $prescribe_herb) {
        $mCase = new mCase();

        $prescribe_herb = json_decode($prescribe_herb, true);
        if (empty($prescribe_herb)) {
            $this->setError('开药详情为空');
            return false;
        }

        $data = array();
        foreach ($prescribe_herb as $item) {
            $temp = array();
            $temp['num'] = $item['num'];
            if (isset($item['herb_id'])) {
                $temp['herb_id'] = $item['herb_id'];
                $data[] = $temp;
                continue;
            }

            $herb = $mCase->getHerbByName($item['name']);
            if ($herb) {
                $temp['herb_id'] = $herb['id'];
                $data[] = $temp;
                continue;
            }

            $userherb = $this->obj->select($this->user_herb_tbl, array('sql' => '`name`=?', 'vals' => array($item['name'])));
            if ($userherb) {
                $temp['herb_id'] = 'u_' . $userherb['id'];
                $data[] = $temp;
                continue;
            }

            $user_herb_id = $this->obj->insert($this->user_herb_tbl, array('uid' => $uid, 'name' => $item['name']));
            if (!$user_herb_id) {
                $this->setError('添加自定义药材失败');
                return false;
            }

            $temp['herb_id'] = 'u_' . $user_herb_id;
            $data[] = $temp;
        }

        return json_encode($data);
    }

    public function createUserCase($uid, $case_id, $data) {
        if ($case_id <= 0) {
            $this->setError('找不到相关药方');
            return false;
        }
        if (empty($data['patient_name'])) {
            $this->setError('患者姓名不能为空');
            return false;
        }
        if ($data['patient_age'] <= 0) {
            $this->setError('患者年龄不正确');
            return false;
        }
        if ($data['sex'] < 0) {
            $this->setError('患者性别不能为空');
            return false;
        }
        if ($data['prescribe_num'] <= 0) {
            $this->setError('开药数量不正确');
            return false;
        }
        if (empty($data['prescribe_herb'])) {
            $this->setError('开药详情不能为空');
            return false;
        }
        if (empty($data['patient_say'])) {
            $this->setError('主诉不能为空');
            return false;
        }
        if (empty($data['first_diagnosis'])) {
            $this->setError('舌诊脉诊不能为空');
            return false;
        }
        if (empty($data['diagnosis'])) {
            $this->setError('诊断不能为空');
            return false;
        }

        $m_case = new mCase();
        $case = $m_case->getCaseById($case_id);
        if (!$case) {
            $this->setError('找不到相关药方');
            return false;
        }

        //格式化医案开药详情
        $prescribe_herb = $this->formatUserCaseHerbs($uid, $data['prescribe_herb']);
        if (!$prescribe_herb) {
            $this->setError('医案开药详情不正确');
            return false;
        }

        $data['prescribe_herb'] = $prescribe_herb;
        $data['case_id'] = $case['id'];
        $data['uid'] = $uid;

        $id = $this->obj->insert($this->tbl, $data);
        if (!$id) {
            $this->setError('医案保存失败');
            return false;
        }

        //更新用户药方使用次数
        $m_case->updateCaseUseLog($uid, $case_id);

        return $id;
    }

    public function getUserCaseInfo($uid, $id) {
        $user_case = $this->obj->select($this->tbl, array('sql' => '`id`=? and `uid`=?', 'vals' => array($id, $uid)));
        if (empty($user_case)) {
            $this->setError('找不到相关医案');
            return false;
        }

        $mCase = new mCase();
        $case = $mCase->getCaseInfo($user_case['case_id']);
        if (empty($case)) {
            $this->setError('找不到相关药方');
            return false;
        }

        //格式化医案开药详情
        $prescribe_herb = $this->getUserCaseHerb(array($user_case['id'] => json_decode($user_case['prescribe_herb'], true)));
        $user_case['prescribe_herb'] = $prescribe_herb[$user_case['id']];

        return array(
            'user_case' => $user_case,
            'case_data' => $case,
        );
    }

    public function getUserCaseList($uid, $page_num, $page_size) {
        $offset = ($page_num - 1) * $page_size;
        $user_case = $this->obj->selectAll($this->tbl, array('sql' => '`uid`=?', 'vals' => array($uid)), 'case_time desc ', array($offset, $page_size));
        if (empty($user_case)) {
            $this->setError('找不到相关医案');
            return false;
        }

        $case_ids = array_column($user_case, 'case_id');

        $m_case = new mCase();
        $case = $m_case->getCaseByIds($case_ids);
        if (empty($case)) {
            $this->setError('找不到相关药方');
            return false;
        }

        return array(
            'user_case' => $user_case,
            'case_data' => array_column($case, null, 'id')
        );
    }

    public function getUserCaseHerb($prescribe_herb_arr) {
        $herb_ids = $user_herb_ids = array();
        foreach ($prescribe_herb_arr as $prescribe_herb) {
            foreach ($prescribe_herb as $herb_item) {
                if (strpos($herb_item['herb_id'], 'u_') !== false) {
                    $user_herb_ids[] = str_replace('u_', '', $herb_item['herb_id']);
                    continue;
                }
                $herb_ids[] = $herb_item['herb_id'];
            }
        }

        if (empty($herb_ids) && empty($user_herb_ids)) {
            $this->setError('医案开药详情不正确');
            return false;
        }

        $m_case = new mCase();
        $herb = $m_case->getHerbByIds($herb_ids);
        if (!empty($user_herb_ids)) {
            $user_herb = $this->getUserHerbByIds($user_herb_ids);
            if (empty($user_herb)) {
                $this->setError('找不到相关自定义药材');
                return false;
            }

            foreach ($user_herb as &$item) {
                $item['id'] = "u_" . $item['id'];
            }

            $herb = array_merge($herb, $user_herb);
        }
        $herb_list = array_column($herb, null, 'id');

        $return = array();
        foreach ($prescribe_herb_arr as $user_case_id => $prescribe_herb) {
            foreach ($prescribe_herb as $herb_item) {
                $temp = array(
                    'id' => $herb_item['herb_id'],
                    'name' => $herb_list[$herb_item['herb_id']]['name'],
                    'num' => $herb_item['num'],
                    'desc' => $herb_list[$herb_item['herb_id']]['desc']
                );

                $return[$user_case_id][] = $temp;
            }
        }

        return $return;
    }

    public function getUserCaseListCount($uid) {
        return $this->obj->count($this->tbl, array('sql' => '`uid`=?', 'vals' => array($uid)));
    }

    public function getUserHerbByIds($ids) {
        return $this->obj->selectIn($this->user_herb_tbl, array('id' => $ids));
    }

    public function getUserCaseListPdfInfo($uid, $page_num, $page_size) {
        $data = $this->getUserCaseList($uid, $page_num, $page_size);

        $prescribe_herb_arr = array();
        foreach ($data['user_case'] as $value) {
            $prescribe_herb_arr[$value['id']] = json_decode($value['prescribe_herb'], true);
        }

        //格式化医案开药详情
        $prescribe_herb = $this->getUserCaseHerb($prescribe_herb_arr);

        foreach ($data['user_case'] as &$value) {
            $value['prescribe_herb'] = $prescribe_herb[$value['id']];
        }

        return $this->formatUserCaseData($data);
    }

    public function getUserCasePdfInfo($uid, $id) {
        $data = $this->getUserCaseInfo($uid, $id);

        return $this->formatUserCaseData($data);
    }

    public function formatUserCaseData($data) {
        //兼容单个医案导出pdf
        if (isset($data['user_case']['id'])) {
            $data['user_case'] = array($data['user_case']);
            $data['case_data'] = array($data['case_data']['id'] => $data['case_data']);
        }

        foreach ($data['user_case'] as &$item) {
            $item['patient_sex'] = $item['patient_sex'] == 0 ? '男' : '女';
            $item['case_time'] = date('Y年m月d日', strtotime($item['case_time']));

            $case = $data['case_data'][$item['case_id']];
            $item['case_info'] = "选&nbsp;" . $case['source'] . "&nbsp;" . $case['name'] . ":";

            $herb_arr = array();
            foreach ($item['prescribe_herb'] as $herb) {
                $herb_arr[] = $herb['name'] . $herb['num'] . "克";
            }
            $herb_str = implode('、', $herb_arr);

            $item['case_herb_info'] = $herb_str;
        }

        return $data;
    }

    public function createPdf($uid, $pdf_name, $pdf_html) {
        $temp_dir = sprintf(USER_CASE_PDF_PATH, $uid);
        if (!is_dir($temp_dir)) {
            mkdir($temp_dir, 0755, true);
            chown($temp_dir, 'nobody');
            chgrp($temp_dir, 'nobody');
        }

        $mpdf = new mPDF();

        $mpdf->WriteHTML($pdf_html);

        return $mpdf->Output($temp_dir . $pdf_name, 'F');  // D表示下载,I表示在浏览器中查看
    }
}