<?php

namespace console\models;

use chillerlan\QRCode\Data\Number;
use Imagine\Image\Box;
use Yii;
use common\components\PathologyActiveRecord;
use yii\helpers\FileHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\imagine\Image;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
use common\models\SurgicalOperate;
use common\models\PatientWard;


/**
 * This is the model class for table "case_surgical".
 *
 * @property int $id
 * @property int $patient_id
 * @property int $hospital_id
 * @property string $id_case
 * @property string $hos_ref
 * @property string $given_name
 * @property string $surname
 * @property int $title_id
 * @property string $gender
 * @property string $nation
 * @property string $birthdate
 * @property number $age
 * @property string $age_unit
 * @property string $h_n
 * @property string $id_card
 * @property string $a_n
 * @property string $o_n
 * @property string $v_n
 * @property string $v_date
 * @property string $ward
 * @property string $clinician
 * @property string $collected_at
 * @property string $specimen
 * @property string $section_label
 * @property integer $amount
 * @property integer $amount_in
 * @property string $register_at
 * @property integer $register_id
 * @property integer $block_type_id
 * @property string $gross_img
 * @property string $clinical_diagnosis
 * @property string $gross_description
 * @property string $microscopic_description
 * @property integer $is_no_microscopic
 * @property string $diagnosis
 * @property string $additional_diagnosis
 * @property integer $pathologist_id
 * @property integer $is_photograph
 * @property integer $is_museum
 * @property integer $is_provisional
 * @property integer $is_consult
 * @property integer $is_qa
 * @property integer $is_conference
 * @property string $conference_at
 * @property integer $status_id
 * @property integer $is_immuno_staining
 * @property integer $is_histo_staining
 * @property string $report_at
 * @property string $microscopic_img
 * @property string $frozen_id_case
 * @property string $gross_img_at [datetime]
 * @property int $gross_img_update_id [int(11)]
 * @property int $gross_id [bigint(20)]
 * @property string $gross_at [datetime]
 * @property int $gross_edit_by [int(11)]
 * @property string $gross_edit_at [datetime]
 * @property int $resident_id [int(11)]
 * @property string $pathologist_at [datetime]
 * @property string $resident_at [datetime]
 * @property string $files [varchar(300)]
 * @property int $consultant_id [int(11)]
 * @property string $cons_pathologist [varchar(100)]
 * @property int $center_box_open_id [int(11)]
 * @property int $is_critical_diagnosis [int(11)]
 * @property int $decal_block [int(11)]
 * @property int $is_pathologist_ot [int(11)]
 * @property integer $cons_pathologist_id
 * @property string $cons
 * @property string $patho_remark
 * @property int $is_outlab
 * @property int $charge_user_id
 * @property string $outlab_report
 * @property string|null $status_at
 * @property string|null $items
 * @property int|null $ward_id
 * @property int|null $rights_id
 * @property int|null $doctor_id
 * @property int|null $order_point_id
 * @property int|null $order_by_id
 * @property string $verify_date
 * @property int $hospital_import_id
 * @property string $remark
 * @property User $pathologist
 * @property Patient $patient
 * @property ConstStatus $status
 * @property string $lab_order_number
 * @property integer $is_express
 * @property string $express_at
 * @property string $receive_at
 * @property string|null $imed_case เลข LN จาก iMed
 */
class CaseSurgical extends PathologyActiveRecord
{
    public $autocomplete_hospital;
    public $autocomplete_patient;
    public $autocomplete_ward;
    public $items;
    public $slides;
    public $uploadFile = 'uploads/surgical/file';
    public $uploadGross = 'uploads/surgical/gross';
    public $uploadMicroFolder = 'uploads/surgical/micro';
    public $uploadImgFolder = 'uploads/surgical/img';
    public $uploadReportFolder = 'uploads/surgical/report';
    public $uploadConsultReportFolder = 'uploads/surgical/consult-report';
    public $is_re_reference = false;
    public $finance_histo;
    public $finance_immuno;
    public $finance_dish;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'case_surgical';
    }

    public static function getDb()
    {
        return Yii::$app->get('patho');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_case', 'hospital_id', 'given_name',  'title_id'], 'required'],
            [['id_case', 'hospital_id'], 'required', 'on' => 'register'],
            [['pathologist_id'], 'required', 'on' => 'update'],
            [['is_stat_flesh'], 'required', 'on' => 'gross'],
            [['id_case'], 'unique'],
            [['autocomplete_hospital', 'autocomplete_patient', 'autocomplete_ward', /*'frozen_id_case', 'cons_pathologist',*/ 'hos_ref' /*'case_reference'*/, 'house', 'moo', 'soy', 'road', 'phone', 'email', /*'review_remark'*/], 'string'],
            [['patient_id', 'title_id', 'is_immuno_staining', 'is_histo_staining', 'register_id', 'amount', 'block_type_id', 'pathologist_id',  'is_consult', 'status_id', 'hospital_id', 'gross_id', /*'cons_pathologist_id', 'consultant_id', 'center_box_open_id',*/ 'is_critical_diagnosis', 'is_pathologist_ot', 'gross_img_update_id', 'is_no_microscopic', 'is_outlab', 'is_consult_outlab', 'charge_user_id', 'bone', 'is_kidney', 'note_id', 'cut_id', 'is_express', 'ward_id', 'rights_id', 'doctor_id', 'organ_id', 'order_point_id', 'order_by_id', 'hospital_import_id', 'amount_in', 'const_rights_id', 'is_molecular', 'is_dish', 'is_frozen', 'is_necropsy', 'tambon', 'amphur', 'province', 'postcode', 'marriage', 'occupation', 'religious', 'race', 'citizenship', 'is_flesh', 'bag', 'is_conference', 'is_review', 'is_smc', 'is_stat_smc', 'is_provincial_hospital', /*'block_no', 'slide_no',*/ 'is_slide_review', 'is_pathologist_review'], 'integer'],
            [['id_case', 'hos_ref', 'given_name', 'surname', 'gender', 'nation', 'id_card', 'age_unit', 'h_n', 'a_n', 'ward', 'clinician', 'specimen', 'section_label', 'clinical_diagnosis', 'clinical_diagnosis_his', 'gross_description', 'microscopic_description', 'patho_remark', 'diagnosis', 'additional_diagnosis', /*'cons',*/ 'patho_remark', 'bone_note', 'lab_order_number', 'remark', 'remark_outlab', 'remark_consult_outlab', 'remark_report', 'post_review_diagnosis'], 'string'],
            [['his_ln', 'verify_date'], 'string', 'max' => 100],
            [['register_at', 'birthdate', 'collected_at', 'conference_at', 'report_at', 'id_case', 'gross_at', 'decal_end_date', 'items'/*, 'slides'*/, 'additional_at', 'status_at', 'cut_at', 'receive_at', 'express_at', 'finance_immuno', 'finance_histo', 'outlab_report', 'decal_block', 'finance_dish'], 'safe'],
            [['files'], 'file', 'extensions' => 'pdf,jpg,png,gif,doc,docx,xls,xlsx,ppt,pptx,jpeg'],
            [['gross_img', 'microscopic_img'], 'file', 'extensions' => 'jpeg,jpg,png,gif,tif,tiff', 'skipOnEmpty' => true, 'maxFiles' => 10],
            [['diagnosis', 'gross_description'], 'required', 'on' => 'pathologist'],
            [['microscopic_description', 'gross_description'], 'required', 'on' => 'additional'],
            [['cut_id', 'note_id', 'is_flesh'], 'required', 'on' => 'new'],
            [['is_re_reference', 'v_date', 'express_day', 'review_at'], 'safe'],
            [['outlab_report'], 'file', 'extensions' => 'pdf'],
            [['consult_outlab_report'], 'file', 'extensions' => 'pdf'],
            [['age'], 'number'],
            [['slides'], 'string', 'max' => 30],
            [['o_n', 'v_n', 'a_n', 'express'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'patient_id' => 'Patient Id',
            'patient' => 'Patient',
            'hospital_id' => 'หน่วยงาน',
            'hospital' => 'หน่วยงาน',
            'id_case' => 'ID CASE',
            'case_reference' => 'Case Reference',
            'hos_ref' => 'Hospital Reference NO.',
            'title_id' => 'คำนำหน้า',
            'given_name' => 'ชื่อ',
            'surname' => 'นามสกุล',
            'gender' => 'เพศ',
            'nation' => 'เชื้อชาติ',
            'id_card' => 'หมายเลขบัตรประชาชน',
            'birthdate' => 'วัน/เดือน/ปี เกิด',
            'age' => 'อายุ',
            'age_unit' => 'หน่วยอายุ',
            'h_n' => 'H N',
            'a_n' => 'A N',
            'ward' => 'Ward',
            'ward_id' => 'Ward',
            'clinician' => 'Physician',
            'collected_at' => 'วันที่เก็บสิ่งส่งตรวจ',
            'receive_at' => 'วันที่รับสิ่งส่งตรวจ',
            'specimen' => 'Specimen',
            'section_label' => 'Section Label',
            'amount' => 'จำนวน Block',
            'amount_in' => 'ช่องจำนวนชิ้นเนื้อ',
            'cut_at' => 'วันตัดเนื้อ',
            'note_id' => 'ผู้จด',
            'cut_id' => 'ผู้ตัด',
            'bone' => 'bone',
            'bone_note' => 'bone_note',
            'block_type_id' => 'Block Type ID',
            'gross_img' => 'Gross Img',
            'clinical_diagnosis' => 'Clinical Information',
            'gross_description' => 'Gross Description',
            'gross_id' => 'ผู้พิมพ์ Gross',
            'gross_at' => 'พิมพ์ Gross เมื่อ',
            'microscopic_description' => 'Microscopic Description',
            'is_no_microscopic' => 'ไม่รายงาน Microscopic',
            'diagnosis' => 'Diagnosis',
            'additional_diagnosis' => 'Additional Report',
            'additional_at',
            'pathologist_id' => 'พยาธิแพทย์',
            //'is_photograph' => 'Is Photograph',
            //'is_museum' => 'Is Museum',
            //'is_provisional' => 'Is Provisional',
            'is_consult' => 'Is Consult',
            //'is_qa' => 'Is Qa',
            'is_conference' => 'Conference',
            'conference_at' => 'Conference At',
            'is_review' => 'Review',
            'status_id' => 'สถานะ',
            'doctor_id' => 'Clinician',
            'organ_id' => 'Organ',
            'report_at' => 'วันที่ออกผล',
            'decal_end_date' => 'วันสิ้นสุดการ Decal',
            'microscopic_img' => 'Microscopic Img',
            'register_id' => 'ผู้ลงทะเบียน',
            'register_at' => 'วันที่ลงทะเบียน',
            'autocomplete_hospital' => 'โรงพยาบาล',
            'autocomplete_patient' => 'ชื่อ นามสกุล',
            'autocomplete_ward' => 'Ward',
            //'frozen_id_case' => 'Frozen ID Case',
            'is_immuno_staining' => 'ส่งย้อม Immuno',
            'is_histo_staining' => 'ส่งย้อม Histo',
            //'center_box_open_id' => 'รายการเปิดกล่อง',
            'is_critical_diagnosis' => 'แจ้งแพทย์ด่วน Critical Diagnosis',
            /*'consultant_id' => 'Consultant',
            'cons_pathologist_id' => 'Pathologist',
            'cons_pathologist' => 'Pathologist (ภายนอก)',*/
            'is_re_reference' => 'ดึงข้อมูลผลการตรวจเดิมอีกครั้ง',
            'is_outlab' => 'Case Outlab',
            'outlab_report' => 'Outlab Report File (PDF)',
            'is_consult_outlab' => 'Case Consult Outlab',
            'consult_outlab_report' => 'Consult Outlab Report File (PDF)',
            'charge_user_id' => 'ผู้ให้ราคา',
            'lab_order_number' => 'Lab order Number',
            'is_express' => 'ขอผลด่วน?',
            'express_at' => 'วันที่ขอผลด่วน',
            'express_day' => 'เลือกวันขอผลด่วน',
            'remark' => 'Remark',
            'rights_id' => 'สิทธิ์การรักษา',
            'is_molecular' => 'Molecular',
            'is_dish' => 'DISH',
            'is_frozen' => 'Frozen',
            'is_necropsy' => 'Necropsy',
            'remark_outlab' => 'Remark Outlab',
            'his_ln' => 'Lab Number',
            'house' => 'เลขที่บ้าน',
            'moo' => 'เลขที่หมู่/ชุมชน',
            'soy' => 'ชื่อตรอก/ซอย',
            'road' => 'ถนน',
            'tambon' => 'ตำบล',
            'amphur' => 'อำเภอ',
            'province' => 'จังหวัด',
            'postcode' => 'รหัสไปรษณีย์',
            'phone' => 'หมายเลขโทรศัพท์คนไข้',
            'email' => 'ที่อยู่จดหมายอิเลคทรอนิค',
            'marriage' => 'สภาพสมรส',
            'occupation' => 'อาชีพ',
            'religious' => 'ศาสนา',
            'race' => 'เชิ้อชาติ',
            'citizenship' => 'สัญชาติ',
            'is_flesh' => 'สถิติประกันชันสูตร',
            'is_stat_flesh' => 'ขนาดชิ้นเนื้อ',
            'bag' => 'จำนวนถุงชิ้นเนื้อ',
            'is_provincial_hospital' => 'รพช',
        ];
    }

    public function attributeHints()
    {
        return [
            'collected_at' => 'วัน/เดือน/ปี ค.ศ. เช่น ' . date('d/m/Y H:i:s'),
            'receive_at' => 'วัน/เดือน/ปี ค.ศ. เช่น ' . date('d/m/Y H:i:s'),
            'cut_at' => 'วัน/เดือน/ปี ค.ศ. เช่น ' . date('d/m/Y H:i:s'),
            'birthdate' => 'วัน/เดือน/ปี ค.ศ. เช่น 22/05/' . date('Y'),
            'conference_at' => 'วัน/เดือน/ปี ค.ศ. เช่น' . date('d/m/Y'),
            'decal_end_date' => 'วัน/เดือน/ปี ค.ศ เช่น  22/05/' . (date('Y')) . ' 09:10:07',
        ];
    }

    public static function getNewTask()
    {
        return self::find()->where(['status_id' => 1])->count();
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getConstWard()
    {
        return $this->hasOne(ConstWard::class, ['id' => 'ward_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getConstDoctor()
    {
        return $this->hasOne(ConstDoctor::class, ['id' => 'doctor_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getConstRights()
    {
        return $this->hasOne(ConstRights::class, ['id' => 'rights_id']);
    }

    /**
     * @return string
     */
    public function getFullname()
    {
        return Html::encode($this->given_name . ' ' . $this->surname);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRegister()
    {
        return $this->hasOne(User::class, ['id' => 'register_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getChangUser()
    {
        return $this->hasOne(User::class, ['id' => 'charge_user_id']);
    }


    /**
     * @return \yii\db\ActiveQuery
     */
    public function getGender()
    {
        return $this->hasOne(User::class, ['id' => 'gender_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPathologist()
    {
        return $this->hasOne(User::class, ['id' => 'pathologist_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRegisterBy()
    {
        return $this->hasOne(User::class, ['id' => 'register_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRepotType()
    {
        return $this->hasOne(ConstStatusReport::class, ['id' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTitle()
    {
        return $this->hasOne(PatientTitle::class, ['id' => 'title_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getLookUp()
    {
        return $this->hasOne(ConstLookup::class, ['lookuptypeid' => 'marriage']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPatient()
    {
        return $this->hasOne(Patient::class, ['id' => 'patient_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getStatus()
    {
        return $this->hasOne(ConstStatus::class, ['id' => 'status_id']);
    }

    public function getWard()
    {
        return $this->hasOne(PatientWard::class, ['id' => 'ward']);
    }

    public function getGross()
    {
        return $this->hasOne(User::class, ['id' => 'gross_id']);
    }

    public function getSurgicalOperate()
    {
        return $this->hasOne(SurgicalOperate::class, ['id_case' => 'id_case']);
    }

    public function getSurgicalDiscard()
    {
        return $this->hasOne(SurgicalDiscard::class, ['id_case' => 'id_case']);
    }

    public function getHospital()
    {
        return $this->hasOne(ConstHospital::class, ['id' => 'hospital_id']);
    }

    public function getGrossEditBy()
    {
        return $this->hasOne(User::class, ['id' => 'gross_edit_by']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getChargeUser()
    {
        return $this->hasOne(User::class, ['id' => 'charge_user_id']);
    }

    public function getHospitals()
    {
        return $this->hasOne(ConstHospital::class, ['id' => 'hospital_id']);
    }


    /**
     * @param $model
     * @return false|string
     * @throws \ImagickException
     */
    public function uploadMicro($model)
    {
        $files = UploadedFile::getInstances($model, 'microscopic_img');
        if ($files) {
            $file_names = [];

            foreach ($files as $file) {
                if ($file->extension == 'tiff' || $file->extension == 'tif') {
                    $file_name = $model->id_case . '_' . $file->baseName . '.' . $file->extension;
                    $file->saveAs(Yii::getAlias('@webroot') . '/' . $this->uploadMicroFolder . '/' . $file_name);

                    $image = new common\models\Imagick(Yii::getAlias('@webroot') . '/' . $this->uploadMicroFolder . '/' . $file_name);

                    @unlink(Yii::getAlias('@webroot') . '/' . $this->uploadMicroFolder . '/' . $file_name);

                    $file_name = $model->id_case . '_' . $file->baseName . '.png';
                    $image->setImageFormat('png');
                    $image->thumbnailImage(1024, 0);
                    $image->writeImage(Yii::getAlias('@webroot') . '/' . $this->uploadMicroFolder . '/' . $file_name);
                } else {
                    $file_name = $model->id_case . '_' . $file->baseName . '.' . $file->extension;

                    if ($file->saveAs(Yii::getAlias('@webroot') . '/' . $this->uploadMicroFolder . '/' . $file_name)) {
                        Image::getImagine()->open(Yii::getAlias('@webroot') . '/' . $this->uploadMicroFolder . '/' . $file_name)->thumbnail(new Box(1024, 1024))->save(Yii::getAlias('@webroot') . '/' . $this->uploadMicroFolder . '/' . $file_name, ['quality' => 100]);
                    }
                }

                $file_names[] = $file_name;
            }
            return implode(',', (ArrayHelper::merge($file_names, $this->getMicroImageToArray())));
        }

        return $model->isNewRecord ? false : $model->getOldAttribute('microscopic_img');
    }


    /**
     * @return array|false|string[]
     */
    public function getMicroImageToArray()
    {
        return !empty($this->getOldAttribute('microscopic_img')) ? explode(',', $this->getOldAttribute('microscopic_img')) : [];
    }


    /**
     * @return string
     */
    public function getMicroImage()
    {
        return !empty($this->microscopic_img) ? Yii::getAlias('@web') . '/' . $this->uploadMicroFolder . '/' . $this->microscopic_img : '';
    }


    /*
     * upload Files
     */
    public function uploadFile($model, $attribute)
    {
        $files = UploadedFile::getInstances($model, $attribute);
        if (!empty($files)) {
            $files_name = [];
            foreach ($files as $file) {
                $file_name = time() . '_' . $file->baseName . '.' . $file->extension;
                $file->saveAs(Yii::getAlias('@webroot') . '/' . $this->uploadFile . '/' . $file_name);
                $files_name[] = $file_name;
            }

            if ($model->isNewRecord) {
                return implode(',', $files_name);
            } else {
                return implode(',', (ArrayHelper::merge($files_name, $this->getFileToArray())));
            }
        }
        return $model->isNewRecord ? false : $model->getOldAttribute($attribute);
    }


    /**
     * ขอชื่อไฟล์ทั้งหมด
     */
    public function getFiles()
    {
        if (empty($this->files) && !isset($this->files)) {
            return [];
        } else {
            return !is_array($this->files) ? explode(',', $this->files) : [];
        }
    }

    /**
     * Get files with html link function
     *
     * @return string
     */
    public function getFileLink()
    {
        $rt = '';
        if (!empty($this->files)) {
            foreach ($this->getFiles() as $key => $val) {
                $rt .= Html::a($val, Yii::getAlias('@web') . '/' . $this->uploadFile . '/' . $val, ['target' => '_blank', 'class' => 'linksWithTarget']) . '  ';
            }
        }
        return $rt;
    }

    /**
     * Get files with html link function
     *
     * @return string
     */
    public function getFileLinkImg()
    {
        $rt = '';
        if (!empty($this->files)) {
            foreach ($this->getFiles() as $key => $val) {
                $rt .= Html::a(Html::img(Yii::getAlias('@web') . '/' . $this->uploadFile . '/' . $val, ['class' => 'img-fluid']), Yii::getAlias('@web') . '/' . $this->uploadFile . '/' . $val, ['target' => '_blank', 'class' => 'linksWithTarget']);
            }
        }
        return $rt;
    }


    /**
     * นำไฟล์มาใส่ใน Array
     */
    public function getFileToArray()
    {
        return $this->getOldAttribute('files') ? @explode(',', $this->getOldAttribute('files')) : [];
    }

    /**
     * @param $id_case
     * @return array|mixed|\yii\db\ActiveRecord|null
     */
    public static function getNext($id_case)
    {
        $model = CaseSurgical::findOne(['id_case' => $id_case]);
        $surgical = CaseSurgical::find()->where(['>', 'id', $model->id])->andWhere(['status_id' => 1])->orderBy(['id' => SORT_ASC])->one();
        if ($surgical) {
            return $surgical->id_case;
        } else {
            return null;
        }
    }

    /**
     * @param null $id_case
     * @return array|mixed|\yii\db\ActiveRecord|null
     */
    public static function getPrev($id_case = null)
    {
        $model = CaseSurgical::findOne(['id_case' => $id_case]);
        $surgical = CaseSurgical::find()->where(['<', 'id', $model->id])->andWhere(['status_id' => 1])->orderBy(['id' => SORT_DESC])->one();
        if ($surgical) {
            return $surgical->id_case;
        } else {
            return null;
        }
    }

    /**
     * @param $model
     * @param $attribute
     * @return bool|mixed|string|null
     * @throws \yii\base\Exception
     */
    public function uploadGross($model, $attribute)
    {
        $grosses = UploadedFile::getInstances($model, $attribute);
        FileHelper::createDirectory($this->getPath());
        if ($grosses) {
            $file_names = [];
            foreach ($grosses as $gross) {
                $file_name = $this->id_case . '_' . $gross->baseName . '.' . $gross->extension;
                $gross->saveAs(Yii::getAlias('@webroot') . '/' . $this->uploadGross . '/' . $file_name);
                $file_names[] = $file_name;
            }
            if ($this->isNewRecord) { //ถ้าเป็นการเพิ่ม Record ใหม่ให้บันทึกไฟล์ aaa.aaa,bbb.bbb ....
                return implode(',', $file_names);
            } else { //ถ้าเป็นการปรับปรุงให้เพิ่มจากของเดิม
                return implode(',', ArrayHelper::merge($file_names, $this->getOldAttribute($attribute) ? explode(',', $this->getOldAttribute($attribute)) : []));
            }
        } //end files upload

        return $this->isNewRecord ? false : $this->getOldAttribute($attribute); //ถ้าไม่มีการ upload ให้ใช้ข้อมูลเดิม
    }


    /**
     * @return string
     */
    public function getPath()
    {
        return Yii::getAlias('@webroot') . '/' . $this->uploadGross;
    }

    /**
     * @return string
     */
    public function getFileUrl()
    {
        return Yii::getAlias('@web') . '/' . $this->uploadGross;
    }


    /**
     * @return false|string[]
     */
    public function getGrosses()
    {
        return !is_array($this->gross_img) ? explode(',', $this->gross_img) : [];
    }


    /**
     * @return string
     */
    public function getGrossImgs()
    {
        $img = '';
        if (!empty($this->gross_img)) {
            foreach ($this->getGrosses() as $gross) {
                $img .= Html::a(Html::img(Yii::getAlias('@web') . '/' . $this->uploadGross . '/' . $gross, ['class' => 'img-fluid']), Url::to(Yii::getAlias('@web') . '/' . $this->uploadGross . '/' . $gross, true), ['target' => '_blank']);
            }
        }
        return $img;
    }

    /**
     * @return string
     */
    public function getGrossImgsForGross()
    {
        $img = '';
        if (!empty($this->gross_img)) {
            foreach ($this->getGrosses() as $gross) {
                $img .= Html::a(Html::img(Yii::getAlias('@web') . '/' . $this->uploadGross . '/' . $gross, ['width' => 200, 'class' => '']), ['/surgical/gross/view-gross', 'id_case' => $this->id_case, 'gross_img' => $gross], ['target' => '_blank']);
            }
        }
        return $img;
    }


    /**
     * @return string
     */
    public function getGrossDelImgs()
    {
        $img = '';
        if (!empty($this->gross_img)) {
            foreach ($this->getGrosses() as $gross) {
                $img .= '<div class="img-thumbnail">' . Html::a(Html::img(Yii::getAlias('@web') . '/' . $this->uploadGross . '/' . $gross, ['width' => 200, 'class' => 'img-fluid']), Url::to(Yii::getAlias('@web') . '/' . $this->uploadGross . '/' . $gross, true), ['target' => '_blank']) . '<br />' .
                    Html::a('Delete', ['delete-gross-img', 'img' => $gross, 'id_case' => $this->id_case], ['class' => 'btn btn-xs btn-danger', 'data' => ['confirm' => 'แน่ใจนะว่าต้องการลบรูปนี้?']])
                    . '</div>';
            }
        }
        return $img;
    }

    /**
     * @return string
     */
    public function getGrossCameraDelImgs()
    {
        $img = '';
        $directoryPath = Yii::getAlias('@webroot') . '/uploads/surgical/gross/' . $this->id_case;

        if (is_dir($directoryPath)) {
            $files = \yii\helpers\FileHelper::findFiles($directoryPath);

            if (!empty($files)) {
                foreach ($files as $index => $file) {
                    $nameFicheiro = basename($file);
                    $filePath = Yii::getAlias('@web') . '/uploads/surgical/gross/' . $this->id_case . '/' . $nameFicheiro;
                    $img .= '<div class="col-md-3">' . Html::a(Html::img($filePath, ['class' => 'img-fluid']), $filePath, ['target' => '_blank']) .
                        Html::a('Delete', ['delete-gross-img', 'img' => $nameFicheiro, 'id_case' => $this->id_case], ['class' => 'btn btn-xs btn-danger'])
                        . '</div>';
                }
            }
            return $img;
        }
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCaseRef()
    {
        return $this->hasOne(CaseSurgical::class, ['id_case' => 'id_case']);
    }


    /**
     * @param $model
     * @param $attribute
     * @return false|string
     */
    public function uploadReport($model, $attribute)
    {
        $files = UploadedFile::getInstances($model, $attribute);
        if (!empty($files)) {
            $files_name = [];
            foreach ($files as $file) {
                $file_name = $file->baseName . '.' . $file->extension;
                $file->saveAs(Yii::getAlias('@webroot') . '/' . $this->uploadReportFolder . '/' . $file_name);
                $files_name[] = $file_name;
            }

            if ($model->isNewRecord) {
                return implode(',', $files_name);
            } else {
                return implode(',', (ArrayHelper::merge($files_name, $this->getReportToArray())));
            }
        }
        return $model->isNewRecord ? false : $model->getOldAttribute($attribute);
    }

    /**
     * @return array|false|string[]
     */
    public function getReportToArray()
    {
        return $this->getOldAttribute('outlab_report') ? @explode(',', $this->getOldAttribute('outlab_report')) : [];
    }

    /**
     * @return array|false|string[]
     */
    public function getReport()
    {
        if (empty($this->outlab_report) || !isset($this->outlab_report)) {
            return [];
        } else {
            return !is_array($this->outlab_report) ? explode(',', $this->outlab_report) : [];
        }
    }


    /**
     * @param $model
     * @param $attribute
     * @return false|string
     */
    public function uploadConsultReport($model, $attribute)
    {
        $files = UploadedFile::getInstances($model, $attribute);
        if (!empty($files)) {
            $files_name = [];
            foreach ($files as $file) {
                $file_name = $file->baseName . '.' . $file->extension;
                $file->saveAs(Yii::getAlias('@webroot') . '/' . $this->uploadConsultReportFolder . '/' . $file_name);
                $files_name[] = $file_name;
            }

            if ($model->isNewRecord) {
                return implode(',', $files_name);
            } else {
                return implode(',', (ArrayHelper::merge($files_name, $this->getConsultReportToArray())));
            }
        }
        return $model->isNewRecord ? false : $model->getOldAttribute($attribute);
    }

    /**
     * @return array|false|string[]
     */
    public function getConsultReportToArray()
    {
        return $this->getOldAttribute('consult_outlab_report') ? @explode(',', $this->getOldAttribute('consult_outlab_report')) : [];
    }

    /**
     * @return array|false|string[]
     */
    public function getConsultReport()
    {
        if (empty($this->consult_outlab_report) || !isset($this->consult_outlab_report)) {
            return [];
        } else {
            return !is_array($this->consult_outlab_report) ? explode(',', $this->consult_outlab_report) : [];
        }
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCut()
    {
        return $this->hasOne(User::class, ['id' => 'cut_id']);
    }
    public function getIsExpress()
    {
        return $this->hasOne(CaseSurgical::class, ['id' => 'is_express']);
    }
}
