<?php

namespace Application\Service\DB\Item;

use Interop\Container\ContainerInterface;

class Formpatientsign extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $this->tableName = 'yikeen_item_form_patientsignannex';
        parent::__construct($dbAdapter, $container);
    }

    public function pdf($patient_id,$item_id,$form_id,$checktime_id){
        //表单名称
        $formWhere['where'] = [
            'id' => $form_id,
            'is_del' => 0,
        ];
        $formWhere['columns'] = ['id','name'];
        $formInfo = $this->LocalService()->itemForm->fetchOne($formWhere);

        //检查点名称
        $checktimeWhere['where'] = [
            'id' => $checktime_id,
            'is_del' => 0,
        ];
        $checktimeWhere['columns'] = ['id','check_name'];
        $checktimeInfo = $this->LocalService()->itemChecktime->fetchOne($checktimeWhere);

        //受试者姓名/编号
        $patientWhere['where']   = [
            'id' => $patient_id,
            'is_del' => 0,
        ];
        $patientWhere['columns'] = ['patient_name','patient_number'];
        $patientdata = $this->LocalService()->patient->fetchOne($patientWhere);

        //受试者姓名/编号
        $patientName = '';
        if(!empty($patientdata['patient_name'])){
            $patientName .= $patientdata['patient_name'];
            if(!empty($patientdata['patient_number'])){
                $patientName .= '-'.$patientdata['patient_number'];
            }
        }else{
            $patientName .= $patientdata['patient_number'];
        }

        //查询签名图片、时间
        $signWhere['where'] = [
            'patient_id' => $patient_id,
            'form_id' => $form_id,
            'checktime_id' => $checktime_id,
            'is_del' => 0,
        ];
        $signWhere['columns'] = ['id','annex_path','create_time'];
        $signInfo = $this->fetchOne($signWhere);
        //签名时间

        $signtime = date('Y-m-d',$signInfo['create_time']);

        //表单字段
        $formfieldDatas = $this->LocalService()->itemExport->getformfield($item_id,$form_id);

        //表单填写结果
        $patientcontentWhere['where']   = [
            'patient_id' => $patient_id,
            'form_id' => $form_id,
            'checktime_id' => $checktime_id,
            'is_del' => 0,
        ];
        $patientcontentWhere['columns'] = ['id','data'];
        $patientcontentData = $this->LocalService()->patientFormContent->fetchOne($patientcontentWhere);

        //数据主题
        $patientformContent = json_decode($patientcontentData['data'],true);

        //获取表单字段类型为单选/多选的数据
        $optionDatas =$this->LocalService()->itemExport->getformoptions($item_id,$form_id);

        //处理数据含有“-”符号，截取符号前的ID
        foreach($patientformContent as $contentK => $contentV){
            if(count(explode('-',$contentK)) >1){
                $arr = explode('-',$contentK);
                $arrCount = count($arr);
                $unsetNumber = $arrCount-ceil($arrCount/2)+1;

                for($i=1;$i<$unsetNumber;$i++){
                    unset($arr[count($arr)-1]);
                }

                $str = implode('-',$arr);

                $patientformContent[$str] = $contentV;
            }
        }

        $FileUploader = $this->LocalService()->imageUploader;

        //附件地址
        $filepath = $signInfo['annex_path'];

        //文件名称
        $fileName = $patientName.'-'.$checktimeInfo['check_name'].'-'.$formInfo['name'].'.pdf';

        $imgdownpath = $patientName.'-'.$checktimeInfo['check_name'].'-'.$formInfo['name'];

        $FileUploader->downOssFile($filepath,APP_PATH . '/data/signimg/'.$imgdownpath.'.png');//把oss的图片下载到本地服务器

//        $sign_filepath = APP_PATH . '/data/signimg/'.$imgdownpath.'.png';

        $sign_filepath =  $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'] . '/data/signimg/' .$imgdownpath.'.png';

        $file_path = APP_PATH.'/vendor/tecnickcom/tcpdf/tcpdf.php';

        // Include the main TCPDF library (search for installation path).
        require_once($file_path);
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // set document information
        $pdf->SetCreator("创建者");
        $pdf->SetAuthor('作者');
        $pdf->SetTitle('标题');
        $pdf->SetSubject('项目名');
        $pdf->SetKeywords('关键字');
        // set header and footer fonts
        // remove default header/footer
        //关闭头尾输出
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

        // set default monospaced font
        //$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->SetDefaultMonospacedFont('courier');

        // set margins
        $pdf->SetMargins(10, 35, 10);
        //$pdf->SetHeaderMargin(500);
        //$pdf->SetFooterMargin(200);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, 5);

        // set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        // set font
        $pdf->SetFont('droidsansfallback', '', 12);

        $pdf->AddPage();
        // writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='')
        // writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true)

        $html = '<link rel="stylesheet" type="text/css" href="'.APP_PATH.'/public/img/layui.css'.'">';

        $html .= '<p style="font-size: 25px;text-align:center;">'.$formInfo['name'].'</p>';
        $html .= '<div style="font-size: 15px; text-align:center;">受试者:'.$patientName.'</div>
                  <div style="font-size: 15px; text-align:center;">检查点:'.$checktimeInfo['check_name'].'</div>
                  <div style="font-size: 15px; text-align:center;">签署时间:'.$signtime.'</div>';

        foreach($formfieldDatas[$form_id]['data'] as $key=>$value)
        {
            $resultKey = $value['id'];
            if(isset($value['patents'])) $resultKey .= '-'.$value['patents'];

            if(empty($patientformContent[$resultKey])){
                $result = '';
            } else{
                if($value['type'] == 10 || $value['type'] == 12){
                    $result = $optionDatas[$value['id']][$patientformContent[$resultKey]];
                }elseif($value['type'] == 11){
                    $options = explode(',',$patientformContent[$resultKey]);
                    $optionResult = [];
                    foreach($options as $optionKey => $optionVal){
                        $optionResult[] = $optionDatas[$value['id']][$optionVal];
                    }
                    $result = implode(',',$optionResult);
                }else{
                    $result = $patientformContent[$resultKey];
                }
            }

            $html .='<div>
                        <div>'.$value['name'].' : <span style="color: #008800">'.$result.'</span></div>
                    </div>';
        }

        // create some HTML content
        $str = '<div style="width:100%;height: 100%;display: flex;align-items: center;margin:0 auto">
                    <img style="width:300px;height:300px;margin:0 auto;" src="'.$sign_filepath.'">
                </div>';

        $html .= ''.$str.'';

        $html .='<div style="font-size: 15px;">签署时间:'.$signtime.'</div>';

        //logo 226*60
//        $pdf->Image('http://'.K_PATH_IMAGES.'/img/page_logo.png',10,10,37.5,10,'PNG','','',false,300,'',false,false,0,false,false,false);

//        $pdf->lastPage();

        $pdf->writeHTML($html, true, false, true, false, '');

        // ---------------------------------------------------------
        //保存PDF到本地
        ob_clean();
//        $res = $pdf->Output($fileName, 'I');die;
        $res = $pdf->Output(APP_PATH . '/data/sign/'.$fileName, 'F');
        //============================================================+
        // END OF FILE
        //============================================================+
        return $fileName;
    }
}