<?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->updateCaseSearchNum($case_id);

        return $id;
    }

    public function getUserCaseInfo($uid, $id, $is_format_data = false) {
        $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'];
        }
        if (empty($herb_ids) && empty($user_herb_ids)) {
            $this->setError('医案开药详情不正确');
            return false;
        }

        $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(
            'data' => $user_case,
            'case_data' => $case,
            'herb_data' => array_column($herb,null,'id'),
            'user_herb_data' => array_column($user_herb,null,'id'),
        );

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

    public function getUserCaseList($uid, $page_num, $page_size, $get_case_herb = false, $is_format_data = false) {
        $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;
        }

        $case = array_column($case,null,'id');

        if (!$get_case_herb)return array('list' => $user_case, 'case_data' => $case);

        //获取医案开药详情
        $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'];
            }
        }
        if (empty($herb_ids) && empty($user_herb_ids)) {
            $this->setError('医案开药详情不正确');
            return false;
        }

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

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

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

    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 formatUserCaseData($data) {
        //兼容单个医案导出pdf
        if (isset($data['data'])) {
            $data['list'][0] = $data['data'];
            unset($data['data']);
            $data['case_data'] =array_column(array($data['case_data']),null,'id');
        }

        foreach ($data['list'] 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) {
                if (strpos($herb['herb_id'],'u_') !== false) {
                    $herb['herb_id'] = str_replace('u_','',$herb['herb_id']);
                    $herb_name = $data['user_herb_data'][$herb['herb_id']]['name'];
                }else{
                    $herb_name = $data['herb_data'][$herb['herb_id']]['name'];
                }
                $herb_arr[] = $herb_name.$herb['num']."克";
            }
            $herb_str = implode('、',$herb_arr);

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

        return $data;
    }

    public function createPdf($uid, $data_key) {
        $mpdf = new mPDF();
        $htmlContent = file_get_contents(sprintf(RQ_USER_CASE_HTML_URL, $data_key));

        $mpdf->WriteHTML($htmlContent);

        $pdf_name = md5($data_key);

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

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