<?php
namespace Application\Service\DB\Item;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use Interop\Container\ContainerInterface;
use Application\Service\Extension\Laminas;
use Laminas\Db\Sql\Expression;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Stdlib\ArrayUtils;
use PHPUnit\Exception;

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


    public const FORM_FIELD_TYPE_TEXT = '1';
    public const FORM_FIELD_TYPE_DATE_UK = '2';
    public const FORM_FIELD_TYPE_DATE = '3';
    public const FORM_FIELD_TYPE_DATE_SECOND = '4';
    public const FORM_FIELD_TYPE_DATETIME = '5';
    public const FORM_FIELD_TYPE_INTEGER = '6';
//    public const FORM_FIELD_TYPE_FLOAT_1 = '7';
//    public const FORM_FIELD_TYPE_FLOAT_2 = '8';
//    public const FORM_FIELD_TYPE_FLOAT_3 = '9';
    public const FORM_FIELD_TYPE_RADIO = '10';
    public const FORM_FIELD_TYPE_CHECKBOX = '11';
    public const FORM_FIELD_TYPE_DROPDOWN = '12';
//    public const FORM_FIELD_TYPE_UPLOAD_FILE = '13';
    public const FORM_FIELD_TYPE_UPLOAD_IMAGE = '14';
//    public const FORM_FIELD_TYPE_EDITOR = '15';
    public const FORM_FIELD_TYPE_TEXTAREA = '16';
//    public const FORM_FIELD_TYPE_LABEL = '17';
//    public const FORM_FIELD_TYPE_SPAN = '18';

    public function getPatientattrTemplate($patientattrData=[],$type = 0){
        //属性类型
//        $fieldArr = [self::FORM_FIELD_TYPE_TEXT,self::FORM_FIELD_TYPE_DATETIME,self::FORM_FIELD_TYPE_INTEGER,self::FORM_FIELD_TYPE_RADIO,self::FORM_FIELD_TYPE_CHECKBOX,self::FORM_FIELD_TYPE_DROPDOWN,self::FORM_FIELD_TYPE_UPLOAD_IMAGE,self::FORM_FIELD_TYPE_TEXTAREA];
        $fieldArr = $this->getFieldData();
        $dictionaryFormtypeData = $this->LocalService()->dictionaryFormtype->fetchCol('type_code','is_del = 0 and id in('.implode(',',$fieldArr).')' );
        $fieldTypeData = [
            'Input'=>['text'],
            'Number'=>['integer','decimal_one','decimal_two','decimal_three'],
            'Radio'=>['radio'],
            'Checkbox'=>['checkbox'],
            'Uk'=>['date_uk'],
            'Select'=>['select'],
            'UploadImg'=>['upload_img'],
//            'UploadFile'=>['upload_file'],
            'Date'=>['date_ymd'],
            'DateTimeSecond'=>['date_ymd_hi'],
            'DateTime'=>['date_ymd_his'],
            'Textarea'=>['textarea'],

        ];
        foreach($dictionaryFormtypeData as $dictionaryFormtypeDataK=>&$dictionaryFormtypeDataV){
            foreach($fieldTypeData as $fieldTypeDataK=>&$fieldTypeDataV){
                if  (in_array($dictionaryFormtypeDataV,$fieldTypeDataV)){
                    $dictionaryFormtypeDataV = $fieldTypeDataK;
                }
            }
        }
//        $dictionaryFormtypeData = array_flip($dictionaryFormtypeData);

//        echo '<pre>';print_r($dictionaryFormtypeData);die;

        $patientattr = [];
        if (!empty($patientattrData)){
            foreach ($patientattrData as $k=>&$v){
                if (!empty($v['type'])){
                    $v['type'] = isset($dictionaryFormtypeData[$v['type']])?$dictionaryFormtypeData[$v['type']]:'Input';
                }
                $k = $v['var_name'];
                $required = false;
                if(!empty($type)){
                    $required = $v['is_required']?true:false;
                }
                $patientattr[$k] = [
                    'type'=>$v['type'],
                    'label'=>$v['name'],
                    'placeholder'=>'请输入'.$v['name'],
                    'prop'=>$v['id'], //$v['var_name'],
                    'id'=>$v['id'],
                    'field_type'=>1,
                    'rules'=>[
                        [
                            'required'=>$required,
                            'message'=>$v['name'].'不能为空',
                            'trigger'=>'blur'
                        ]
                    ]
                ];
                switch ($v['type']){
                    case 'Radio':
                        $radios = [];
                        if (!empty($v['children'])){
                            foreach ($v['children'] as $kc =>$vc){
                                $radios[] = ['label'=>$vc['name'],'value'=>$vc['id']];
                            }

                        }
                        $patientattr[$k]['radios'] = $radios;

                        break;
                    case 'Checkbox':
                        $checkboxs = [];
                        if (!empty($v['children'])){

                            foreach ($v['children'] as $kc =>$vc){
                                $checkboxs[] = ['label'=>$vc['name'],'value'=>$vc['id']];
                            }


                        }
                        $patientattr[$k]['checkboxs'] = $checkboxs;
                        break;

                    case 'Select':
                        $options = [];
                        if (!empty($v['children'])){
                            foreach ($v['children'] as $kc =>$vc){
                                $options[] = ['label'=>$vc['name'],'value'=>$vc['id']];
                            }
                        }
                        $patientattr[$k]['options'] = $options;

                        break;
                    case 'UploadImg':
                        $patientattr[$k]['fileListImg'] = [];
                        $patientattr[$k]['action'] = "/common/uploadImg";
                        break;
                    case 'UploadFile':
                        $patientattr[$k]['fileList'] = [];
                        break;
                }
            }
        }
        return $patientattr;
    }

    public function getFieldData(){
        $fieldArr = [self::FORM_FIELD_TYPE_TEXT,self::FORM_FIELD_TYPE_DATETIME,self::FORM_FIELD_TYPE_INTEGER,self::FORM_FIELD_TYPE_RADIO,self::FORM_FIELD_TYPE_CHECKBOX,self::FORM_FIELD_TYPE_DROPDOWN,self::FORM_FIELD_TYPE_UPLOAD_IMAGE,self::FORM_FIELD_TYPE_TEXTAREA];
        return $fieldArr;
    }

    public function getTypeCode($data = []){
        $dictionaryFormtypeData = [];
        $where  = [
            'is_del' => 0,
        ];
        if  (isset($data['dictionaryFormtypes']) && !empty($data['dictionaryFormtypes'])){
            $where['id'] = explode(',', $data['dictionaryFormtypes']);
        }
        if  (isset($data['type']) && !empty($data['type'])){
            $type_codes = ['"integer"','"decimal_one"','"decimal_two"','"decimal_three"'];
            $where['type_code'] = $type_codes;
        }
        $dictionaryFormtypeData = $this->LocalService()->dictionaryFormtype->fetchCol('type_code', $where);

        $whereField['where'] = [
            'is_del' => 0,
            'item_id' => $data['item_id'],
            'type' => array_keys($dictionaryFormtypeData),
        ];
        $whereField['columns'] = ['id','type'];
        $itemMessageFieldData = $this->LocalService()->itemMessageField->fetchAll($whereField);
        $checkData = [];
        if (!empty($itemMessageFieldData)){
            foreach ($itemMessageFieldData as $key=>$value){
                if (isset($dictionaryFormtypeData[$value['type']])){
                    if  (isset($data['type']) && !empty($data['type'])){
                        $checkData['id']['type'] = $dictionaryFormtypeData[$value['type']];
//                        $checkData['id'][''] = 'Number';
                    }else{
                        $checkData[$value['id']] = $dictionaryFormtypeData[$value['type']];

                    }
                }
            }
        }

        return $checkData;
    }


    public function getSendRate($k = ''){
        $send_rate = ['1'=>'每天'];//,'2'=>'每周三','3'=>'每周末'
        if (isset($send_rate[$k])){
            return $send_rate[$k];
        }
        return $send_rate;
    }
    public function getChaseType($k = '',$type = 0){
        $chase_type = ['1'=>'一次跟踪','2'=>'二次跟踪','3'=>'失访'];
        if (isset($chase_type[$k])){
            return $chase_type[$k];
        }
        if (!empty($type)){
            $chase_type = array_flip($chase_type);
            if (isset($chase_type[$k])){
                return $chase_type[$k];
            }else{
                return 1;
            }
        }
        return $chase_type;
    }

    /**
     * @throws InvalidArgumentException
     * @throws RuntimeException
     * @throws \RedisException
     */
    public function template($data=[], $app=[], array $patientSendData=[]){
        if (empty($data)) return false;
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(13)->getRedisInstance();
        $keyErr = 'sendTempMsgPatientErr:'.$data['item_id'].':'.$data['itemsig_id'].':'.$data['patient_tel'].':'.date('Y-m-d');
        $keySuccess = 'sendTempMsgPatientSuc:'.$data['item_id'].':'.$data['itemsig_id'].':'.$data['patient_tel'].':'.date('Y-m-d');

        $senResult = [
            'errcode'=>0,
            'errmsg'=>'已发送',
            'msgid'=>'',
        ];
        $sendUrl = $this->LocalService()->config['sendUrl'];

        empty($app) && $app = $this->LocalService()->wechat->getPatientH5App();
        $msgLink = $sendUrl.'/#/patientH5?date='.time();
        if ($patientSendData['patient_h5_wechat']) {
            $msgLink .= "&type=" . $patientSendData['patient_h5_wechat'];
        }
        $senResult =$app->template_message->send([
            'touser' => $data['openid'],
            'template_id' => $this->LocalService()->config['sendMsgTmpId'][$patientSendData['patient_h5_wechat'] ?: 'default'],
            'url' => $msgLink,
            "topcolor" => "#FF0000",
            'data' => [
                'thing13' => ['value' => $data['item_name']],
                'time1' => ['value' => date('Y年m月d日 H:i')],
            ],
        ]);

        $success['data'] = $err['data'] = $data;
        $success['senResult'] = $err['senResult'] = $senResult;
        if ($senResult['errcode'] > 0){
            $redisData = json_encode($err);
            $redis->set($keyErr,$redisData);

        }else if(empty($senResult['errcode'])){
            $redisData = json_encode($success);
            $redis->set($keySuccess,$redisData);
        }
        return $senResult;
    }
    public function sendTemplateMessage($cond = []){
        if(empty($this->LocalService()->config['sendMsgTmpId'] ?? '')) return false;

        $where = [
            'is_del' => 0,
        ];
        $temp_id = [];
        if  (isset($cond['item_id']) && !empty($cond['item_id'])){
            $where['item_id'] = $cond['item_id'];
        }
        if  (isset($cond['patient_id']) && !empty($cond['patient_id'])){
            $temp_id['id'] = $cond['patient_id'];
        }

        $sendMsg =[
            'where'=> $where,
        ];
        $itemMessageSendData = $this->LocalService()->itemMessageSend->fetchAll($sendMsg);
        if  (empty($itemMessageSendData)) return false;
        $itemMessageSendDatas = array_column($itemMessageSendData,null,'item_id');

        $send_type = 0;
        //发送时间判断
        if  (!isset($cond['type']) && empty($cond['type'])){
            //自动发送
            foreach($itemMessageSendDatas as $itemMessageSendDatasK=>&$itemMessageSendDatasV){
                $weekday = date('w');

                $send_time = $itemMessageSendDatasV['send_time'];
                $current_time = date('G');

                if  ($send_time != $current_time){
                    unset($itemMessageSendDatas[$itemMessageSendDatasK]);
                    continue;
                }
                if  ($itemMessageSendDatasV['send_rate'] == 3 && $weekday != 0){
                    unset($itemMessageSendDatas[$itemMessageSendDatasK]);
                }else if($itemMessageSendDatasV['send_rate'] == 2 && $weekday != 3){
                    unset($itemMessageSendDatas[$itemMessageSendDatasK]);
                }
            }
        }else{
            //手动发送
            if (!isset($cond['item_id']) || empty($cond['item_id'])) return false;

            if  (!isset($cond['all_type']) || empty($cond['all_type'])){
                $send_type = 1;
                //单受试者发送
                if (!isset($cond['patient_id']) || empty($cond['patient_id'])) return false;
            }else{
                //批量受试者发送
                $send_type = 2;
            }
        }

        if  (empty($itemMessageSendDatas)) return false;

        //受试者发送条件
        $wherePatientArr['where'] = ArrayUtils::merge([
            'is_del' => 0,
            'is_send_msg' => 1,
            'item_id' => array_keys($itemMessageSendDatas),
        ], $temp_id);
        $wherePatientArr['columns'] = ['id','patient_name','patient_number','item_id','itemsig_id','patient_tel','patient_status','patient_check_id','random_number','random_id'];//,'openid'
        $patientData = $this->LocalService()->patient->isShowMaskingField(true)->fetchAll($wherePatientArr);

        if (empty($patientData)) return false;

        $adminUserWhere =[
            'where'=> [
                'is_del' => 0,
                'patient_status' => 0,
                new Operator('patient_openid', Operator::OP_NE, ''),
                new Operator('mobile', Operator::OP_GT, 0),
            ],
            'columns'=>['id','patient_openid','mobile'],
        ];
        $adminUserData = $this->LocalService()->adminUser->isShowMaskingField(true)->fetchAll($adminUserWhere);

        if (empty($adminUserData)) return false;
        $adminUserDatas = array_column($adminUserData,null,'mobile');
        $itemMessageSendPatientWhere =[
            'where'=> [
                'is_del' => 0,
                'item_id' => array_keys($itemMessageSendDatas),
                'FROM_UNIXTIME(create_time, "%Y-%m-%d")=?' => date('Y-m-d'),
            ],
            'columns'=>['id','item_id','itemsig_id','patient_id','is_write','is_complete'],
            'group'=>['patient_id'],
            'order'=>['create_time DESC'],
        ];
        $itemMessageSendPatientDatas = [];
        $itemMessageSendPatientData = $this->LocalService()->itemMessageSendPatient->fetchAll($itemMessageSendPatientWhere);
        if (!empty($itemMessageSendPatientData)) $itemMessageSendPatientDatas = array_column($itemMessageSendPatientData,null,'patient_id');

        $itemInfoName = $this->LocalService()->itemInfo->fetchCol('name',[
            'is_del' => 0,
            'id' => array_keys($itemMessageSendDatas),
        ]);
        $itemInfoVarName = $this->LocalService()->itemInfo->fetchCol('var_name',[
            'is_del' => 0,
            'id' => array_keys($itemMessageSendDatas),
        ]);

        foreach($patientData as $patientDatasKey =>&$patientDatasValue){
            $patientDatasValue['drug_way'] = '填写用药情况';
            $patientDatasValue['itemsig_name'] = '';
            $patientDatasValue['send_patent_type'] = 0;
            $patientDatasValue['item_name'] = $itemInfoName[$patientDatasValue['item_id']] ?? '';
            $patientDatasValue['item_var_name'] = $itemInfoVarName[$patientDatasValue['item_id']] ?? '';

            if (isset($itemMessageSendPatientDatas[$patientDatasValue['id']]) && !empty($itemMessageSendPatientDatas[$patientDatasValue['id']]['is_write'])){
                unset($patientData[$patientDatasKey]);
                continue;
            }

            if (!isset($adminUserDatas[$patientDatasValue['patient_tel']])){
                unset($patientData[$patientDatasKey]);
                continue;
            }

            $patientDatasValue['openid'] =$adminUserDatas[$patientDatasValue['patient_tel']]['patient_openid'];
            $patientDatasValue['user_id'] =$adminUserDatas[$patientDatasValue['patient_tel']]['id'];

            if (!isset($itemMessageSendDatas[$patientDatasValue['item_id']])){
                unset($patientData[$patientDatasKey]);
                continue;
            }

            $patientDatasValue['itemMessageSendData'] =$itemMessageSendDatas[$patientDatasValue['item_id']];

            $app = $this->LocalService()->wechat->getPatientH5App($itemMessageSendDatas[$patientDatasValue['item_id']]['patient_h5_wechat'] ?: 'default');
            $senResult = $this->template($patientDatasValue,$app, $itemMessageSendDatas[$patientDatasValue['item_id']]);

            $insertSend = $arr = [
                'patient_id' => $patientDatasValue['id'],
                'openid' => $patientDatasValue['openid']?:'',
                'item_id' => $patientDatasValue['item_id']?:0,
                'itemsig_id' => $patientDatasValue['itemsig_id']?:0,
                'itemsig_name' => $patientDatasValue['itemsig_name']?:'',
                'item_name' => $patientDatasValue['item_name']?:'',
                'patient_tel' => $patientDatasValue['patient_tel']?:'',
                'patient_name' => $patientDatasValue['patient_name']?:'',
                'patient_number' => $patientDatasValue['patient_number']?:'',
                'patient_status' => $patientDatasValue['patient_status']?:9,
                'send_type' => $send_type,
                'create_user_id' => 0,
                'update_user_id' => 0,
                'send_time' => $patientDatasValue['itemMessageSendData']['send_time']?:0,
                'send_rate' => $patientDatasValue['itemMessageSendData']['send_rate']?:1,
                'content' => $patientDatasValue['itemMessageSendData']['content']?:'',
            ];
            if (!isset($itemMessageSendPatientDatas[$patientDatasValue['id']])){
                unset($insertSend['openid']);
                unset($insertSend['itemsig_name']);
                unset($insertSend['item_name']);
                unset($insertSend['send_rate']);
                unset($insertSend['send_time']);
                unset($insertSend['send_type']);
                unset($insertSend['patient_status']);
                unset($insertSend['patient_number']);
                unset($insertSend['patient_name']);
                unset($insertSend['patient_tel']);
                $this->LocalService()->itemMessageSendPatient->save($insertSend);
            }
            if (!empty($senResult['errcode'])){
                $patientDatasValue['send_patent_type'] = 1;

                $this->LocalService()->itemMessageSendLog->save($arr);
            }
        }

        return true;
    }


    public function checkSend($wheres = []){
        $whereMess['where'] = [
            'is_del' => 0,
            'item_id' => $wheres['item_id'],
        ];
        $whereMess['columns'] = ['item_id','content'];
        $itemMessageSendInfo = $this->LocalService()->itemMessageSend->fetchOne($whereMess);
        $sendIdData = [];
        if (!empty($itemMessageSendInfo['content'])){
            $content = json_decode($itemMessageSendInfo['content'],true);
            foreach ($content as $contentK=>$contentV){
                if (!empty($contentV['value']) || $contentV['value'] != 0){
                    $sendIdData[] = $contentV['id'];
                }
            }
        }
        if (empty($itemMessageSendInfo['content'])) return false;

        if (isset($wheres['sendPatientData']) && !empty($wheres['sendPatientData'])){
            $contentPatient = json_decode($wheres['sendPatientData'],true);
            foreach ($contentPatient as $contentPatientK=>$contentPatientV){
                if (!in_array($contentPatientV['id'],$sendIdData)){
                    if (!empty($contentPatientV['value']) || $contentPatientV['value'] != 0){
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

