<?php

namespace console\models;

use Yii;
use common\models\ConstHospital;
use common\components\PathologyActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\UploadedFile;

/**
 * This is the model class for table "patient_case".
 *
 * @property string $id_case
 * @property string $title
 * @property string $given_name
 * @property string $surname
 * @property integer $gender
 * @property string $birthdate
 * @property string $age
 * @property string $age_unit
 * @property integer $hospital_id
 * @property string $hospital
 * @property string $collect_at
 * @property string $register_at
 * @property string $cut_at
 * @property integer $status_id
 * @property string $status
 * @property integer $pathologist_id
 * @property string $pathologist
 * @property string $report_at
 * @property string $diagnosis
 * @property string $center_out_at
 * @property int $is_outlab
 * @property int $is_critical_diagnosis
 */
class PatientCase extends \yii\db\ActiveRecord
{
    public $bex;
    public $bin;
    public $submit_no;
    public $postal_no;
    public $uploadGross = 'uploads/surgical/gross';
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'patient_case';
    }

    public static function primaryKey()
    {
        return ['id_case'];
    }

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_case', 'title', 'given_name', 'surname', 'gender', 'age', 'hospital_id', 'hospital', 'status_id', 'status'], 'required'],
            [['id_case', 'title', 'given_name', 'surname', 'age_unit', 'hospital_name', 'status', 'pathologist', 'diagnosis', 'additional_diagnosis', 'gross_img'], 'string'],
            [['gender', 'hospital_id', 'status_id', 'pathologist_id', 'is_outlab', 'cnt_critical'], 'integer'],
            [['birthdate', 'collect_at', 'register_at', 'cut_at', 'report_at', 'center_out_at', 'id_case', 'bex', 'bin', 'additional_at', 'h_n', 'his_ln'], 'safe'],
            [['age'], 'number']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_case' => 'Case',
            'title' => 'คำนำหน้า',
            'patient_name' => 'ชื่อ นามสกุล',
            //'patient' => 'ชื่อ - นามสกุล',
            //'name' => 'ชื่อ นามสกุล',
            'gender' => 'เพศ',
            'birthdate' => 'วดป เกิด',
            'age' => 'อายุ',
            'age_unit' => 'หน่วยอายุ',
            'hospital_id' => 'Hospital ID',
            'hospital_name' => 'หน่วยงาน',
            'collect_at' => 'Collect At',
            'register_at' => 'วันที่ลงทะเบียน',
            'cut_at' => 'Cut At',
            'status_id' => 'สถานะ',
            'status' => 'สถานะ',
            'pathologist_id' => 'Pathologist ID',
            'pathologist' => 'พยาธิแพทย์',
            'report_at' => 'วันที่ออกผล',
            'diagnosis' => 'Diagnosis',
            'center_out_at' => 'Center Out At',
            'bex' => 'Block Ex',
            'bin' => 'Block In',
            'is_outlab' => 'Case Outlab',
            'cnt_critical' => 'Is Critical Diagnosis',
            'h_n' => 'H N',
            'his_ln' => 'Lab Number'
        ];
    }


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


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

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

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


    /**
     * @return array|false|string[]
     */
    public function getReport()
    {
        $case = false;
        $case_type = Yii::$app->pathology->getCaseType($this->id_case);
        if ($case_type == 'surgical') {
            $case = CaseSurgical::findOne(['id_case' => $this->id_case]);
        }
        if ($case_type == 'non-gyn') {
            $case = CaseNonGyn::findOne(['id_case' => $this->id_case]);
        }
        if ($case_type == 'pap') {
            $case = CasePap::findOne(['id_case' => $this->id_case]);
        }

        return $case;
    }

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

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



    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;
    }

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

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

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

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

    public function getGynApprove()
    {
        return $this->hasOne(CenterApprove::class, ['id_case' => 'id_case']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCytotech1()
    {
        return $this->hasOne(User::className(), ['id' => 'cytotech1_id']);
    }
}
