<?php

namespace console\models;

use Yii;
use common\components\PathologyActiveRecord;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

/**
 * This is the model class for table "case_pap".
 *
 * @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 $cytotech_id
 * @property string $cytotech_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 $ward
 * @property string $clinician
 * @property string $collected_at
 * @property string $collect_method
 * @property integer $specimen_type_id
 * @property integer $specimen_id
 * @property string $no_slide
 * @property integer $is_stained
 * @property integer $is_restain
 * @property string $last_pregnancy
 * @property string $lmp
 * @property string $para
 * @property string $sterilize
 * @property string $previous_treatment
 * @property string $clinical_finding
 * @property string $clinical_diagnosis
 * @property string $last_pap
 * @property integer $via
 * @property integer $is_ot
 * @property integer $is_pathologist_ot
 * @property integer $specimen_adequacy
 * @property string $specimen_adequacy_1
 * @property string $specimen_adequacy_2
 * @property string $adequacy_other
 * @property integer $general_categorization
 * @property string $general_categorization_1
 * @property string $categorization_other
 * @property string $diagnosis
 * @property string $suggestion
 * @property integer $pathologist_id
 * @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 string $report_at
 * @property integer $is_print
 * @property integer $is_critical_diagnosis
 * @property string $diff_qa
 * @property string $hos_ref
 * @property string $register_at
 * @property string result_at
 * @property integer $register_id
 * @property string $specimen_adequacy_3
 * @property string $general_categorization_2
 * @property string $remark
 * @property string $outlab_report
 * @property ConstStatus $status
 * @property CytoGeneralCategorization $generalCategorization
 * @property CytoSpecimen $specimen
 * @property CytoSpecimenAdequacy $specimenAdequacy
 * @property CytoSpecimenType $specimenType
 * @property Patient $patient
 * @property User $pathologist
 * @property integer $lab_order_number
 * @property integer $is_express
 * @property string $express_at
 * @property string $receive_at
 */
class CasePap extends PathologyActiveRecord
{
    public $autocomplete_patient;
    public $specimen_name;
    public $uploadFile = 'uploads/cyto/pap/files';
    public $uploadMicroFolder = 'uploads/cyto/pap/micro';
    public $uploadReportFolder = 'uploads/cyto/pap/report';

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

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

    /**
     * @param $insert
     * @return bool
     */
    public function beforeSave($insert)
    {

        $this->specimen_adequacy_3 = serialize($this->specimen_adequacy_3);
        $this->specimen_adequacy_4 = serialize($this->specimen_adequacy_4);
        $this->general_categorization_2 = serialize($this->general_categorization_2);

        return parent::beforeSave($insert);
    }

    /**
     * @return void
     */

    public function afterFind()
    {
        $this->specimen_adequacy_3 = unserialize($this->specimen_adequacy_3);
        $this->specimen_adequacy_4 = unserialize($this->specimen_adequacy_4);
        $this->general_categorization_2 = unserialize($this->general_categorization_2);

        parent::afterFind();
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[/*'patient_id'*/'id_case', 'hospital_id', 'given_name', 'title_id'], 'required', 'on' => 'register'],
            [['is_specimen'], 'required', 'on' => 'cyto'],
            [[/*'patient_id'*/'id_case', 'hospital_id', 'gender', 'given_name', 'surname', 'title_id', 'pathologist_id'], 'required', 'on' => 'approve'],
            [['autocomplete_patient', 'hos_ref', 'cyto_type', 'case_reference', 'house', 'moo', 'soy', 'road', 'phone', 'email', 'post_review_diagnosis'], 'string'],
            //[['pathologist_id'], 'required', 'on' => 'update'],
            [['id_case'], 'unique'],
            [['title_id', 'specimen_type_id', 'cytotech1_id', 'cytotech2_id', 'specimen_id', 'is_stained', 'is_restain', 'via', 'is_ot', 'is_pathologist_ot', 'specimen_adequacy', 'register_id', 'specimen_adequacy_1', 'general_categorization', 'general_categorization_1', 'pathologist_id', 'is_provisional', 'is_consult', 'is_qa', 'is_conference', 'status_id', 'is_print', 'suggestion_list', 'is_critical_diagnosis', 'class_id', 'adequacy_id', 'result_id', 'hm_id', 'suggest_id', 'is_outlab', 'is_no_comment', 'lab_order_number', 'is_express', 'ward_id', 'rights_id', 'doctor_id', 'organ_id', 'order_point_id', 'order_by_id', 'screener_qa_id', 'qa_list_id', 'const_rights_id', 'tambon', 'amphur', 'province', 'postcode', 'marriage', 'occupation', 'religious', 'race', 'citizenship', 'specimen_adequacy_2', 'is_hpv', 'is_provincial_hospital', 'is_review', 'is_specimen'], 'integer'],
            [['id_case', 'given_name', 'surname', 'gender', 'nation', 'id_card', 'age_unit', 'h_n', 'a_n', 'ward', 'clinician', 'collect_method', 'lmp', 'para', 'sterilize', 'previous_treatment', 'clinical_finding', 'clinical_diagnosis', 'clinical_diagnosis_his', 'last_pap', 'last_pregnancy', 'adequacy_other', 'categorization_other', 'diagnosis', 'suggestion', 'diff_qa', 'adequacy_comment', 'result_comment', 'hm_comment', 'suggest_comment', /*'quantity',*/ 'specimen', 'remark', 'gyn_specimen_other', 'remark_report', 'remark_consult_outlab'], 'string'],
            [['register_at', 'birthdate', 'collected_at', 'conference_at', 'report_at', 'patient_id', 'cytotech1_at', 'cytotech2_at', 'specimen_adequacy_3', 'specimen_adequacy_4', 'general_categorization_2', 'result_at', 'receive_at', 'express_at', 'express_day', 'review_at'], 'safe'],
            [['no_slide', 'pathologist_id', 'hospital_id'], 'number'],
            [['id_case'], 'required', 'on' => 'process'],
            [['his_ln', 'v_date', 'verify_date'], 'string', 'max' => 100],
            [['express'], 'string', 'max' => 50],
            [['files'], 'file', 'extensions' => 'pdf,jpg,png,jpeg,gif,doc,docx,xls,xlsx,ppt,pptx'],
            [['outlab_report'], 'file', 'extensions' => 'pdf,jpg,png,gif,doc,docx,xls,xlsx,ppt,pptx,jpeg'],
            [['age'], 'number'],
            [['hospital_id'], 'exist', 'skipOnError' => true, 'targetClass' => ConstHospital::class, 'targetAttribute' => ['hospital_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_type_id'], 'exist', 'skipOnError' => true, 'targetClass' => CytoSpecimenType::class, 'targetAttribute' => ['specimen_type_id' => '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']],
        ];
    }


    /**
     * @inheritdoc
     */

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            //'autocomplete_patient' => '',
            //'patient_id' => 'ชื่อ นามสกุล',
            'hospital_id' => 'หน่วยงาน',
            'patient' => 'ชื่อ นามสกุล',
            'pathologist' => 'พยาธิแพทย์',
            'hospital' => 'โรงพยาบาล',
            'id_case' => 'ID CASE',
            'cyto_type' => 'Type',
            'cytotech1_id' => 'Cytotech1',
            'cytotech1_at' => 'Cytotech1 At',
            'cytotech2_id' => 'Cytotech2',
            'cytotech2_at' => 'Cytotech2 At',
            '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',
            'doctor_id' => 'Clinician',
            'organ_id' => 'Organ',
            'collected_at' => 'วันที่เก็บสิ่งส่งตรวจ',
            'receive_at' => 'วันที่รับสิ่งส่งตรวจ',
            'collect_method' => 'Collect Method', //Specimen Type ตอนนี้คือ Collect Method
            'specimen_type_id' => 'Collect Method',
            'specimen_id' => 'Specimen',
            'specimen_name' => 'Specimen',
            'no_slide' => 'จำนวนสไลด์',
            'quantity' => 'Quantity',
            'is_stained' => 'Stained',
            'is_restain' => 'Restain',
            'last_pregnancy' => 'Last',
            'lmp' => 'LMP',
            'para' => 'Para',
            'sterilize' => 'Sterilize',
            'previous_treatment' => 'Previous Treatment',
            'clinical_finding' => 'Clinical Finding',
            'clinical_diagnosis' => 'Clinical Information',
            'clinical_diagnosis_his' => 'Clinical Diagnosis',
            'last_pap' => 'Last Pap',
            'via' => 'VIA',
            'is_ot' => 'OT',
            'is_pathologist_ot' => 'Pathologist OT',
            'specimen_adequacy' => 'Specimen Adequacy',
            'specimen_adequacy_1' => 'Specimen Adequacy 1',
            'specimen_adequacy_2' => 'Specimen Adequacy 2',
            'specimen_adequacy_4' => 'Specimen Adequacy 4',
            'adequacy_other' => 'Adequacy Other',
            'general_categorization' => 'General Categorization',
            'general_categorization_1' => 'General Categorization 1',
            'categorization_other' => 'Categorization Other',
            'diagnosis' => 'Diagnosis',
            'additional_diagnosis' => 'Additional Diagnosis',
            'microscopic' => 'Microscopic',
            'gross_description' => 'Gross Description',
            'microscopic_img' => 'Microscopic Image',
            'suggestion' => 'Educational Notes And Suggestions',
            'pathologist_id' => 'พยาธิแพทย์',
            'is_provisional' => 'Provisional',
            'is_consult' => 'Consult',
            'is_qa' => 'QA',
            'is_conference' => 'Conference',
            'conference_at' => 'Conference At',
            'is_review' => 'Review',
            'status_id' => 'Status',
            'report_at' => 'Report At',
            'is_print' => 'Is Print',
            'diff_qa' => 'Diff Qa',
            'is_critical_diagnosis' => 'Critical Report',
            'is_first_cancer' => 'First Cancer',
            'files' => 'Request File',
            'class_id' => 'GENERAL CATEGORIZATION',
            'adequacy_id' => 'ADEQUACY',
            'adequacy_comment' => 'ADEQUACY OTHER',
            'result_id' => 'INTERPRETATION/ RESULT',
            'result_comment' => 'INTERPRETATION/RESULT OTHER',
            'hm_id' => 'HORMONAL EVALUATION',
            'hm_comment' => 'HORMONAL EVALUATION OTHER',
            'suggest_id' => 'SUGGESTION',
            'suggest_comment' => 'SUGGESTION OTHER',
            'register_at' => 'วันที่ลงทะเบียน',
            'register_id' => 'ผู้ลงทะเบียน',
            'is_no_comment' => 'ไม่รายงาน Comment',
            'lab_order_number' => 'Lab Order Number',
            'specimen' => 'Specimen',
            'is_express' => 'ขอผลด่วน?',
            'express_day' => 'เลือกวันขอผลด่วน',
            'express_at' => 'วันที่ขอผลด่วน',
            'remark' => 'Remark',
            'rights_id' => 'สิทธิ์การรักษา',
            'gyn_specimen_other' => 'Specimen Other',
            'is_outlab' => 'Case Outlab',
            'his_ln' => 'Lab Number',
            'house' => 'เลขที่บ้าน',
            'moo' => 'เลขที่หมู่/ชุมชน',
            'soy' => 'ชื่อตรอก/ซอย',
            'road' => 'ถนน',
            'tambon' => 'ตำบล',
            'amphur' => 'อำเภอ',
            'province' => 'จังหวัด',
            'postcode' => 'รหัสไปรษณีย์',
            'phone' => 'หมายเลขโทรศัพท์คนไข้',
            'email' => 'ที่อยู่จดหมายอิเลคทรอนิค',
            'marriage' => 'สภาพสมรส',
            'occupation' => 'อาชีพ',
            'religious' => 'ศาสนา',
            'race' => 'เชิ้อชาติ',
            'citizenship' => 'สัญชาติ',
            'is_hpv' => 'HPV',
            'is_provincial_hospital' => 'รพช',
            'is_specimen' => 'รายงานผล'
        ];
    }
    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'),
        ];
    }

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

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

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

    /**
     * @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 getTitle()
    {
        return $this->hasOne(PatientTitle::class, ['id' => 'title_id']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRegister()
    {
        return $this->hasOne(User::class, ['id' => 'register_id']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRegisterBy()
    {
        return $this->hasOne(User::class, ['id' => 'register_id']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getGeneralCategorization()
    {
        return $this->hasOne(CytoGeneralCategorization::class, ['id' => 'general_categorization']);
    }

    public function getGeneralCategorization1()
    {
        return $this->hasOne(CytoGeneralCategorization1::class, ['id' => 'general_categorization_1']);
    }

    public function getGeneralCategorization2()
    {
        return $this->hasOne(CytoGeneralCategorization2::class, ['id' => 'general_categorization_2']);
    }

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

    /**
     * @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']);
    }
    public function getSpecimenAdequacy3()
    {
        return $this->hasMany(CytoSpecimenAdequacyByCase::class, ['id_case' => 'id_case']);
    }

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

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

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

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

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

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

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

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

    public function getClass()
    {
        return $this->hasOne(CytoPapDiagnosis::class, ['id' => 'class_id']);
    }

    public function getAdequacy()
    {
        return $this->hasOne(CytoPapDiagnosis::class, ['id' => 'adequacy_id']);
    }
    public function getResult()
    {
        return $this->hasOne(CytoPapDiagnosis::class, ['id' => 'result_id']);
    }
    public function getHm()
    {
        return $this->hasOne(CytoPapDiagnosis::class, ['id' => 'hm_id']);
    }
    public function getSuggest()
    {
        return $this->hasOne(CytoPapDiagnosis::class, ['id' => 'suggest_id']);
    }


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

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

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

    public function getCollectMethod()
    {
        return $this->hasOne(CytoCollectMethod::class, ['id' => 'collect_method']);
    }

    /*
     * 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);
    }

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

    /**
     * @return array|false|string[]
     */
    public function getFileToArray()
    {
        return $this->getOldAttribute('files') ? @explode(',', $this->getOldAttribute('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 string
     */
    public function uploadMicro($model)
    {
        $file = UploadedFile::getInstance($model, 'microscopic_img');
        if ($file) {
            $file_name = $model->id_case . '.' . $file->extension;
            $file->saveAs(Yii::getAlias('@webroot') . '/' . $this->uploadMicroFolder . '/' . $file_name);
            return $file_name;
        }

        return $model->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 !empty($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) : [];
        }
    }

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

    public function getTitleFullname()
    {
        return Html::encode(((!empty($this->title_id) ? $this->title->name : '') . $this->given_name . ' ' . $this->surname));
    }
}
