<?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($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, $data['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($info){
        return $this->obj->insert($this->tbl, $info);
    }

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

        $prescribe_herb = json_decode($user_case['prescribe_herb'],true);
        $user_case['prescribe_herb'] = $prescribe_herb;

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

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

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

        $data = array(
            'user_case' => $user_case,
            'case' => $case,
            'herb' => array_column($herb,null,'id'),
            'user_herb' => array_column($user_herb,null,'id'),
        );

        return $data;
    }

    public function getUserCaseList($uid, $start, $pagesize, $get_case_herb = false){
        $user_case = $this->obj->selectAll($this->tbl, array('sql'=>'`uid`=?', 'vals'=>array($uid)), 'case_time desc ', array($start, $pagesize));
        if(empty($user_case)){
            $this->setError('找不到相关医案');
            return false;
        }
        $case_ids = array_column($user_case,'case_id');

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

        if(!$get_case_herb){
            $data = array(
                'user_case_list' => $user_case,
                'case_list' => $case,
            );

            return $data;
        }

        $herb_ids = $user_herb_ids = array();
        foreach ($user_case as &$item){
            $prescribe_herb = json_decode($item['prescribe_herb'],true);
            $item['prescribe_herb'] = $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'];
            }
        }

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

        $data = array(
            'user_case_list' => $user_case,
            'case_list' => $case,
            'herb' => array_column($herb,null,'id'),
            'user_herb' => array_column($user_herb,null,'id'),
        );

        return $data;
    }

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

    public function createUserCasePdf($uid, $data){
        //兼容单个医案导出pdf
        if(isset($data['user_case'])){
            $data['user_case_list'][0] = $data['user_case'];
            unset($data['user_case']);
            $data['case_list'][$data['case']['id']] = $data['case'];
            unset($data['case']);
        }

        // 创建PDF对象
        $mpdf = new mPDF();

        $pdf_name = "";

        $htmlContent = "<p style='text-align: center;font-size: 40px;font-weight: bold'>我的医案</p>";
        foreach ($data['user_case_list'] as $item){
            $pdf_name .= $item['name'];

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

            $htmlContent .= "<p style='border-left:10px solid #DD4B38;font-size: 32px;padding-left: 5px;font-weight: bold;line-height: 37px;'>{$item['name']}</p>";
            $htmlContent .= "<p style='font-size: 26px;line-height: 37px;'>{$item['patient_name']},{$item['patient_sex']},{$item['patient_age']}岁,{$item['case_time']}诊</p>";
            if($item['patient_say']){
                $htmlContent .= "<p style='font-size: 26px;line-height: 37px;'>{$item['patient_say']}</p>";
            }
            if($item['first_diagnosis']){
                $htmlContent .= "<p style='font-size: 26px;line-height: 37px;'>{$item['first_diagnosis']}</p>";
            }
            if($item['diagnosis']){
                $htmlContent .= "<p style='font-size: 26px;line-height: 37px;'>{$item['diagnosis']}</p>";
            }
            $htmlContent .= "<div style='background-color: #FDF9F2;font-size: 26px;line-height: 37px;padding:0 37px'>";
            $htmlContent .= "<p><span style='color: #955239;'>处方</span>&nbsp;&nbsp;&nbsp;&nbsp;共{$item['prescribe_num']}付</p>";

            $case = $data['case_list'][$item['case_id']];
            $case_str = "选&nbsp;".$case['source']."&nbsp;".$case['name'];

            $herb_arr = array();
            foreach ($item['prescribe_herb'] as $herb){
                if(strpos($herb['herb_id'],'u_')!==false){
                    $herb['herb_id'] = str_replace('u_','',$herb['herb_id']);
                    $herb_name = $data['user_herb'][$herb['herb_id']]['name'];
                }else{
                    $herb_name = $data['herb'][$herb['herb_id']]['name'];
                }
                $herb_arr[] = $herb_name.$herb['num']."克";
            }
            $herb_str = implode('、',$herb_arr);

            $htmlContent .= "<p>{$case_str}:&nbsp;{$herb_str}</p>";

            $htmlContent .= "</div>";
            if($data['feedback']){
                $htmlContent .= "<p style='font-size: 26px;line-height: 37px;'>{$item['feedback']}</p>";
            }
        }

        $pdf_name = md5($pdf_name);

        $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->WriteHTML($htmlContent);

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

        return sprintf(USER_CASE_PDF_URL, $uid, $pdf_name);
    }
}