<?php

namespace console\models;

use Imagick;
use Imagine\Image\Box;
use Yii;
use common\components\PathologyActiveRecord;
use yii\imagine\Image;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\helpers\Html;
use yii\helpers\Url;

/**
 * This is the model class for table "case_non_gyn".
 *
 * @property string $id
 * @property string $patient_id
 * @property string $hospital_id
 * @property string $id_case
 * @property string $given_name
 * @property string $surname
 * @property int $title_id
 * @property string $gender
 * @property int $cytotech1_id
 * @property string $cytotech1_at
 * @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 $v_n
 * @property string $o_n
 * @property string $ward
 * @property string $clinician
 * @property string $collected_at
 * @property string $collect_method
 * @property integer $specimen_type_id
 * @property integer $specimen_id
 * @property string $organ_and_location
 * @property string $side_of_specimen
 * @property string $no_slide
 * @property string $no_slide_dry_smear
 * @property string $fluid_volume
 * @property string $fluid_appearance
 * @property string $fluid_colour
 * @property integer $is_stained
 * @property integer $is_restain
 * @property string $clinical_diagnosis
 * @property integer $is_pathologist_ot
 * @property integer $specimen_adequacy
 * @property string $specimen_adequacy_1
 * @property string $specimen_adequacy_2
 * @property string $adequacy_other
 * @property string $finding
 * @property string $screener_diagnosis
 * @property string $microscopic
 * @property string $microscopic_img
 * @property string $gross_description
 * @property string $diagnosis
 * @property string $additional_diagnosis
 * @property string $suggestion
 * @property integer $pathologist_id
 * @property string $is_provisional
 * @property string $is_consult
 * @property string $is_qa
 * @property string $is_conference
 * @property string $conference_at
 * @property integer $status_id
 * @property integer $is_histo_staining
 * @property string $report_at
 * @property integer $is_print
 * @property string $hos_ref
 * @property string $outlab_report
 * @property string $register_at
 * @property integer $register_id
 * @property string $remark
 * @property string $files [varchar(300)]
 * @property CytoSpecimenType $specimenType
 * @property ConstStatus $status
 * @property CytoSpecimen $specimen
 * @property CytoSpecimenAdequacy $specimenAdequacy
 * @property Patient $patient
 * @property User $pathologist
 * @property integer $lab_order_number
 * @property integer $is_no_microscopic
 * @property integer $is_express
 * @property string $express_at
 * @property string $receive_at
 * @property integer $is_cell_block
 * @property integer $cell_block_at
 */
class CaseNonGyn extends PathologyActiveRecord
{
    public $autocomplete_patient;
    public $autocomplete_hospital;
    public $cyto_side_of_specimen;
    public $uploadFile = 'uploads/cyto/non-gyn/files';
    public $uploadMicroFolder = 'uploads/cyto/non-gyn/micro';
    public $uploadReportFolder = 'uploads/cyto/non-gyn/report';
    public $uploadImgFolder = 'uploads/cyto/non-gyn/img';
    public $uploadGross = 'uploads/cyto/non-gyn/img';
    public $uploadConsultReportFolder = 'uploads/cyto/non-gyn/consult-report';
    //public $uploadGross = 'uploads/surgical/gross';

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

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_case', 'hospital_id', 'given_name',  'title_id'], 'required', 'on' => 'register'],
            [['pathologist_id'], 'required', 'on' => 'update'],
            [['is_type_specimen'], 'required', 'on' => 'cyto'],
            [['autocomplete_patient', 'hos_ref', 'house', 'moo', 'soy', 'road', 'phone', 'email', 'post_review_diagnosis'], 'string'],
            [['id_case'], 'unique'],
            [['diagnosis'], 'required', 'on' => 'pathologist'],
            [['title_id', 'is_histo_staining', 'specimen_type_id', 'specimen_id', 'is_stained', 'register_id', 'is_restain', 'is_pathologist_ot', 'specimen_adequacy', 'specimen_adequacy_1', 'specimen_adequacy_2', 'pathologist_id', 'status_id', 'is_print', 'is_critical_diagnosis', 'is_outlab', 'is_consult_outlab', 'cytotech1_id', 'hospital_id', 'lab_order_number', 'is_no_microscopic', 'is_express', 'ward_id', 'rights_id', 'doctor_id', 'organ_id', 'order_point_id', 'hospital_import_id', 'order_by_id'/*, 'smears_receive', 'smears_processed', 'is_effusion', 'is_non_gyn_direction', 'is_fna', 'is_fna_direction'*/, 'const_rights_id', 'specimen_img_update_id', 'tambon', 'amphur', 'province', 'postcode', 'marriage', 'occupation', 'religious', 'race', 'citizenship', 'is_cell_block', 'is_molecular', 'is_conference', 'is_type_specimen', 'is_provincial_hospital', 'is_review'], 'integer'],
            [['id_case', 'given_name', 'surname', 'gender', 'nation', 'id_card', 'age_unit', 'h_n', 'a_n', 'v_n', 'o_n', 'ward', 'clinician', 'collect_method', 'organ_and_location', 'side_of_specimen', 'fluid_volume', 'fluid_appearance', 'fluid_colour', 'fluid_description', 'clinical_diagnosis', 'clinical_diagnosis_his', 'adequacy_other', 'finding', 'screener_diagnosis', 'diagnosis', 'suggestion', 'cyto_side_of_specimen', 'additional_diagnosis', 'microscopic', 'gross_description', 'cytotech1_at', 'remark', 'non_gyn_specimen_other', 'cell_block_at'/*'fna_quantity', 'fna_slide', 'non_gyn_bal', 'non_gyn_other', 'fna_neck', 'fna_lymph_node', 'fna_salivary_gland', 'fna_other'*/, 'remark_consult_outlab', 'remark_report'], 'string'],
            [['register_at', 'birthdate', 'collected_at', 'conference_at', 'report_at', 'patient_id', 'additional_at', 'receive_at', 'express_at'/*, 'non_gyn_type', 'fna_type'*/, 'express_day', 'specimen_img_at', 'review_at'], 'safe'],
            [['age', 'no_slide', 'no_bottle', 'no_slide_dry_smear', 'is_provisional', 'is_consult', 'is_qa'], 'number'],
            [['his_ln', 'v_date', 'verify_date'], 'string', 'max' => 100],
            [['express'], 'string', 'max' => 50],
            [['outlab_report'], 'file', 'extensions' => 'pdf'],
            [['consult_outlab_report'], 'file', 'extensions' => 'pdf'],
            [['files'], 'file', 'extensions' => 'pdf,jpg,png,gif,doc,docx,xls,xlsx,ppt,pptx,jpeg'],
            [['microscopic_img'], 'file', 'extensions' => 'jpeg,jpg,png,gif'],
            [['specimen_img'], 'file', 'extensions' => 'jpeg,jpg,png,gif,tif,tiff', 'skipOnEmpty' => true, 'maxFiles' => 10],
            [['specimen_type_id'], 'exist', 'skipOnError' => true, 'targetClass' => CytoSpecimenType::class, 'targetAttribute' => ['specimen_type_id' => 'id']],
            [['status_id'], 'exist', 'skipOnError' => true, 'targetClass' => ConstStatus::class, 'targetAttribute' => ['status_id' => 'id']],
            [['specimen_id'], 'exist', 'skipOnError' => true, 'targetClass' => CytoSpecimen::class, 'targetAttribute' => ['specimen_id' => 'id']],
            [['specimen_adequacy'], 'exist', 'skipOnError' => true, 'targetClass' => CytoSpecimenAdequacy::class, 'targetAttribute' => ['specimen_adequacy' => 'id']],
            //[['patient_id'], 'exist', 'skipOnError' => true, 'targetClass' => Patient::class, 'targetAttribute' => ['patient_id' => 'id']],
            [['pathologist_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::class, 'targetAttribute' => ['pathologist_id' => 'id']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['register'] = [
            'hospital_id',
            'patient_id',
            'id_case',
            'a_n',
            'ward',
            'clinician',
            'collected_at',
            'collect_method',
            'specimen_type_id',
            'specimen_id',
            'organ_and_location',
            'side_of_specimen',
            'no_slide',
            'is_stained',
            'is_restain',
            //'clinical_diagnosis',
            'is_pathologist_ot',
            'no_slide_dry_smear',
            'fluid_volume',
            'fluid_appearance',
            'fluid_colour',
            'cyto_side_of_specimen'
        ];
        $scenarios['process'] = [
            'patient_id',
            'id_case',
            'no_slide',
            'sterilize',
            'previous_treatment',
            'specimen_adequacy',
            'specimen_adequacy_1',
            'specimen_adequacy_2',
            'general_categorization',
            'general_categorization_1',
            'pathologist_id',
            'is_provisional',
            'is_consult',
            'is_qa',
            'is_conference',
            'status_id',
            'is_print',
            'finding',
            'clinical_finding',
            //'clinical_diagnosis',
            'last_pap',
            'last_pregnancy',
            'adequacy_other',
            'categorization_other',
            'screener_diagnosis',
            'suggestion',
            'diff_qa',
            'hospital_id',
        ];
        return $scenarios;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'hospital_id' => 'หน่วยงาน',
            //'patient_id' => 'ผู้ป่วย',
            'hospital' => 'หน่วยงาน',
            'patient' => 'ชื่อ - นามสกุล',
            'pathologist' => 'พยาธิแพทย์',
            'pathologist_id' => 'พยาธิแพทย์',
            'autocomplete_patient' => 'ผู้ป่วย',
            'id_case' => 'ID CASE',
            'title_id' => 'คำนำหน้า',
            'given_name' => 'ชื่อ',
            'surname' => 'นามสกุล',
            'gender' => 'เพศ',
            'nation' => 'เชื้อชาติ',
            'id_card' => 'หมายเลขบัตรประชาชน',
            'birthdate' => 'วัน/เดือน/ปี เกิด',
            'age' => 'อายุ',
            'age_unit' => 'หน่วยอายุ',
            'h_n' => 'HN',
            'a_n' => 'AN',
            'v_n' => 'VN',
            'o_n' => 'Order Number',
            'ward' => 'Ward',
            'ward_id' => 'Ward',
            'clinician' => 'Physician',
            'doctor_id' => 'Clinician',
            'organ_id' => 'Organ',
            'collected_at' => 'วันที่เก็บสิ่งส่งตรวจ',
            'receive_at' => 'วันที่รับสิ่งส่งตรวจ',
            'collect_method' => 'Collect Method',
            'specimen_type_id' => 'Specimen Type',
            'specimen_id' => 'Specimen',
            'organ_and_location' => 'Specimen', //Organ And Location
            'cyto_side_of_specimen' => 'Side Of Specimen',
            'cytotech1_id' => 'Cytotech',
            'side_of_specimen' => 'Side Of Specimen',
            'no_slide' => 'จำนวน Slide',
            'no_bottle' => 'จำนวน ขวด',
            'quantity' => 'quantity',
            'no_slide_dry_smear' => 'Slide Dry Smear',
            'fluid_volume' => 'Amount',
            'fluid_appearance' => 'Turbidity',
            'fluid_colour' => 'Colour',
            'fluid_description' => 'Description',
            'is_stained' => 'Stained',
            'is_restain' => 'Restain',
            'is_critical_diagnosis' => 'แจ้งแพทย์ด่วน Critical Diagnosis',
            'clinical_diagnosis' => 'Clinical Diagnosis',
            'clinical_diagnosis_his' => 'Clinical Diagnosis',
            'specimen_adequacy' => 'Specimen Adequacy',
            'specimen_adequacy_1' => 'Specimen Adequacy 1',
            'specimen_adequacy_2' => 'Specimen Adequacy 2',
            'adequacy_other' => 'Adequacy Other',
            'gross_description' => 'Gross Description',
            'microscopic' => 'MICROSCOPIC FINDINGS',
            'is_no_microscopic' => 'ไม่รายงาน Microscopic Description',
            'diagnosis' => 'CYTOLOGIC DIAGNOSIS',
            'additional_diagnosis' => 'Additional Diagnosis',
            'suggestion' => 'Suggestion',
            'pathologist_id' => 'Pathologist',
            'status_id' => 'Status',
            'report_at' => 'Report At',
            'register_at' => 'วันที่ลงทะเบียน',
            'register_id' => 'ผู้ลงทะเบียน',
            'lab_order_number' => 'Lab Order Number',
            'is_express' => 'ขอผลด่วน?',
            'express_day' => 'เลือกวันขอผลด่วน',
            'express_at' => 'วันที่ขอผลด่วน',
            'smears_receive' => 'Receive',
            'smears_processed' => 'Processed',
            'smears_remark' => 'Description',
            'remark' => 'Remark',
            'rights_id' => 'สิทธิ์การรักษา',
            'is_cell_block' => 'สั่ง Cell block',
            'cell_block_at' => 'ส่ง Cell block เมื่อ',
            'specimen_img' => 'Specimen Image',
            'is_outlab' => 'Case Outlab',
            'his_ln' => 'Lab Number',
            'house' => 'บ้านเลขที่',
            'moo' => 'หมู่ที่/ชุมชน',
            'soy' => 'ตรอก/ซอย',
            'road' => 'ถนน',
            'tambon' => 'ตำบล',
            'amphur' => 'อำเภอ',
            'province' => 'จังหวัด',
            'postcode' => 'รหัสไปรษณีย์',
            'phone' => 'หมายเลขโทรศัพท์คนไข้',
            'email' => 'Email',
            'marriage' => 'สถานภาพสมรส',
            'occupation' => 'อาชีพ',
            'religious' => 'ศาสนา',
            'race' => 'เชิ้อชาติ',
            'citizenship' => 'สัญชาติ',
            'is_type_specimen' => 'รายงานผล',
            'is_provincial_hospital' => 'รพช',
            'is_review' => 'Review',
            'is_molecular' => 'Molecular',
        ];
    }

    /**
     * @return string[]
     */
    public function attributeHints()
    {
        return [
            'collected_at' => 'วัน/เดือน/ปี ค.ศ. เช่น ' . date('d/m/Y H:i:s'),
            'receive_at' => 'วัน/เดือน/ปี ค.ศ. เช่น ' . date('d/m/Y H:i:s'),
            'birthdate' => 'วัน/เดือน/ปี ค.ศ. เช่น ' . date('d/m/Y'),
            'conference_at' => 'วัน/เดือน/ปี ค.ศ. เช่น' . date('d/m/Y'),
            'no_slide' => 'กรอกเฉพาะตัวเลขเท่านั้น',
            'no_slide_dry_smear' => 'กรอกเฉพาะตัวเลขเท่านั้น',
        ];
    }

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

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

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

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getOrgan()
    {
        return $this->hasOne(ConstOrgan::class, ['id' => 'organ_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']);
    }

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

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

    public function getTitle()
    {
        return $this->hasOne(PatientTitle::class, ['id' => 'title_id']);
    }

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

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

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

    public function getSideOfSpecimen()
    {
        return $this->hasOne(CytoSideOfSpecimen::class, ['id' => 'side_of_specimen']);
    }

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

    public function getSpecimenAdequacy1()
    {
        return $this->hasOne(CytoSpecimenAdequacy1::class, ['id' => 'specimen_adequacy_1']);
    }

    public function getSpecimenAdequacy2()
    {
        return $this->hasOne(CytoSpecimenAdequacy2::class, ['id' => 'specimen_adequacy_2']);
    }

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

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

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

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

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

    /**
     * นับจำนวน Case ใหม่
     * @return number|string
     */
    public static function getNewCase()
    {
        return CaseNonGyn::find()->where(['status_id' => 1])->count();
    }

    /**
     * นับจำนวน Case ใหม่
     * @return number|string
     */
    public static function getNewCytoCase()
    {
        return CaseNonGyn::find()->where(['status_id' => 6])->count();
    }

    /**
     * นับจำนวน Case ของตัวเอง
     * @return number|string
     */
    public static function getMyCase()
    {
        return CaseNonGyn::find()->with('')
            ->where(['cytotech1_id' => Yii::$app->user->getId(), 'status_id' => 5])
            ->count();
    }

    /**
     * นับจำนวน Case ที่ทำเสร็จแล้ว
     * @return number|string
     */
    public static function getMyFinishCase()
    {
        return CaseNonGyn::find()
            ->with('')
            ->where(['cytotech1_id' => Yii::$app->user->getId(), 'status_id' => 12])->count();
    }

    /*
     * 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 getFileToArray()
    {
        return !empty($this->files) ? explode(',', $this->getOldAttribute('files')) : [];
    }*/

    public function getFileToArray()
    {
        return $this->getOldAttribute('files') ? @explode(',', $this->getOldAttribute('files')) : [];
    }

    /**
     * @return array|false|string[]
     */
    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;
    }


    /**
     * @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 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 : '';
    }


    /**
     * @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 $id_case
     * @return array|mixed|\yii\db\ActiveRecord|null
     */
    public static function getNext($id_case)
    {
        $model = CaseNonGyn::findOne(['id_case' => $id_case]);
        $surgical = CaseNonGyn::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 = CaseNonGyn::findOne(['id_case' => $id_case]);
        $surgical = CaseNonGyn::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->specimen_img) ? explode(',', $this->specimen_img) : [];
    }


    /**
     * @return string
     */
    public function getGrossImgs()
    {
        $img = '';
        if (!empty($this->specimen_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->specimen_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, 'specimen_img' => $gross], ['target' => '_blank']);
            }
        }
        return $img;
    }


    /**
     * @return string
     */
    public function getGrossDelImgs()
    {
        $img = '';
        if (!empty($this->specimen_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;
    }

    /*********************** */

    /**
     * @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) : [];
        }
    }
}
