<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\User;

class TongueDiagnosis extends Model
{
    public static $config = [];
    public static function getSet(){
        $uniacid = UNIACID;

        if(!empty(self::$config)){
            return self::$config;
        }

        $config = Db::name("bbfx_tongue_diagnosis")->where(["uniacid"=>$uniacid])->find();
        if(empty($config)){
            Db::name("bbfx_tongue_diagnosis")->insert(['uniacid'=>$uniacid]);
            $config = Db::name("bbfx_tongue_diagnosis")->where(["uniacid"=>$uniacid])->find();
        }

        if(empty($config['huoqu_num_method'])){
            $config['huoqu_num_method'] = [];
        }
        else{
            $config['huoqu_num_method'] = explode(',',$config['huoqu_num_method']);
            foreach($config['huoqu_num_method'] as $key => $val){
                $config['huoqu_num_method'][$key] = intval($val);
            }
        }

        if(empty($config['buy_rule'])){
            $config['buy_rule'] = [];
        }
        else{
            $config['buy_rule'] = iunserializer($config['buy_rule']);
        }

        self::$config = $config;
        
        return $config;
    }
    
    public static function jiesuanNum($order_id){
        $config = self::getSet();
        if($config['status'] != 1){
            return __json(0,"未开启");
        }

        if(!in_array(1,$config['huoqu_num_method'])){
            return __json(0,"未开启购买商品获取次数");
        }

        $order = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'id'=>$order_id,'is_pay'=>1,'refund_status'=>['in',[-1,2]]])->find();
        if(empty($order)){
            return __json(0,"订单信息错误");
        }

        $order_goods = Db::name("bbfx_order_goods")->where(['order_id'=>$order['id']])->select();
        foreach($order_goods as $key => $val){
            $total = max(1,$val['total']);
            $goods = iunserializer($val['goods_info']);
            $plugin = iunserializer($goods['plugin']);
            if($plugin['tongue_diagnosis']['status'] == 1){ 
                $num = intval($plugin['tongue_diagnosis']['num']) * $total;
                if($num > 0){
                    $log = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'type'=>12,'item_type'=>49,'item_id'=>$val['id']])->find();
                    if(empty($log)){
                        User::setUserMoney($order['user_id'],$num,12,49,"购买赠送",$val);
                    }
                }
            }
        }

        return __json(1,"操作成功");
    }

    public static function payResult($order_no,$paytype){
        $log = Db::name("bbfx_tongue_diagnosis_buy_record")->where(['uniacid'=>UNIACID,'order_no'=>$order_no])->find();
        if(empty($log)){
            return __json(0,"购买记录不存在");
        }
        
        if($log['status'] != 0){
            return __json(0,"已支付");
        }
        
        $res = Db::name("bbfx_tongue_diagnosis_buy_record")->where(['id'=>$log['id'],'status'=>0])->update(['status'=>1,'paytime'=>time(),'paytype'=>$paytype]);
        if(empty($res)){
            return __json(0,"已支付");
        }
        
        User::setUserMoney($log['user_id'],$log['num'],12,70,"购买舌诊次数",$log);
        
        return __json(1,"操作成功");
    }

    public function diagnose($scene,$user_id,$tf_image="",$ff_image="",$tb_image="",$gender=""){
        $config = self::getSet();
        if($config['status'] != 1){
            return __json(0,"未开启");
        }
        if(empty($config['appcode'])){
            return __json(0,"未配置AppCode");
        }

        if(!in_array($scene,[1,2])){
            return __json(0,"场景值错误");
        }

        $user = User::getInfo($user_id);
        if(empty($user)){
            return __json(0,"用户信息错误");
        }

        if($scene == 1){
            $num = 2;
        }
        else{
            $num = 1;
        }

        if($user['tongue_diagnosis_num'] < $num){
            return __json(0,"诊断次数不足");
        }

        if(empty($tf_image) && empty($ff_image) && empty($tb_image)){
            return __json(0,"舌照图片、面照图片、舌下脉络图片这三张图片至少要上传一张");
        }

        try {
            Db::startTrans();

            $data = array(
                "uniacid"=>UNIACID,
                "user_id"=>$user['id'],
                "scene"=>$scene,
                "tf_image"=>replaceSiteroot($tf_image),
                "ff_image"=>replaceSiteroot($ff_image),
                "tb_image"=>replaceSiteroot($tb_image),
                "gender"=>$gender,
                "status"=>0,
                "createtime"=>time()
            );
            
            $id = Db::name("bbfx_tongue_diagnosis_record")->insertGetId($data);
            $data['id'] = $id;
            $params = [
                "scene"=>$scene,
            ];
            if(!empty($data['ff_image'])){
                $params['ff_image'] = cdnurl($data['ff_image']);
            }
            if(!empty($data['tf_image'])){
                $params['tf_image'] = cdnurl($data['tf_image']);
            }
            if(!empty($data['tb_image'])){
                $params['tb_image'] = cdnurl($data['tb_image']); 
            }
            if(!empty($data['gender'])){
                $params['gender'] = $data['gender'];
            }

            
            $res = User::setUserMoney($user['id'],-$num,12,48,"AI舌诊诊断",$data);
            if(empty($res)){
                throw new \Exception("诊断次数不足");
            }

            $result = $this->request("/diagnose/face-tongue/result/","POST",$params);
            addFileLog("td111",json_encode($params));
            if(empty($result['success'])){
                if(empty($result['msg'])){
                    throw new \Exception("接口错误");
                }
                else{
                    throw new \Exception($result['msg']);
                }
            }

            $udata = ['status'=>1,'stime'=>time()];
            $inquiry_questions = [];
            $report = [];
            if($params['scene'] == 2){
                $report = $result['data'];
                $udata['status'] = 2;
                $udata['ctime'] = time();
                $udata['report'] = iserializer($report);
                $udata['score'] = $report['score'];
            }
            else{
                $udata['result'] = iserializer($result['data']);
                $inquiry_questions = $result['data']['inquiry_questions'];
            }

            Db::name("bbfx_tongue_diagnosis_record")->where(['id'=>$id])->update($udata);
            
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
            return __json(0,$e->getMessage());
        }

        return __json(1,"操作成功",['id'=>$id,'inquiry_questions'=>$inquiry_questions,'report'=>$report]);
    }

    // 获取报告
    public function getReport($id,$index){
        
        $log = Db::name("bbfx_tongue_diagnosis_record")->where(['id'=>$id])->find();
        if(empty($log)){
            return __json(0,"诊断记录不存在");
        }

        if($log['status'] == 2){
            return __json(0,"已获取报告");
        }
        if($log['scene'] != 1){
            return __json(0,"不是舌诊会话场景");
        }
        $result = iunserializer($log['result']);
        if(empty($result)){
            return __json(0,"症状信息错误");
        }
        $inquiry_questions = $result['inquiry_questions'];
        $answers = [];
        foreach($index as $k => $v){
            if(!empty($inquiry_questions[$v])){
                $answers[] = $inquiry_questions[$v];
            }
        }

        if(empty($answers)){
            // return __json(0,"选择的症状信息错误");
        }
        
        $params = [
            'session_id'=>$result['session_id'],
            'answers'=>$answers
        ];
        $result = $this->request("/diagnose/face-tongue/report/","POST",$params);
        addFileLog("td222",json_encode($result));
        if(empty($result['success'])){
            if(empty($result['msg'])){
                return __json(0,"接口错误");
            }
            else{
                return __json(0,$result['msg']);
            }
        }

        $report = $result['data'];

        $udata = ['status'=>2,'ctime'=>time(),'score'=>$report['score'],'report'=>iserializer($report)];
            
        Db::name("bbfx_tongue_diagnosis_record")->where(['id'=>$id])->update($udata);

        return __json(1,"操作成功",['report'=>$result['data']]);
    }

    public function request($url,$method,$data){
        $host = "https://ali-market-tongue-detect-v2.macrocura.com";

        $config = self::getSet();

        $appcode = $config['appcode'];

        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = "";
        $bodys = toJsonen($data);
        $url = $host . $url;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        
        // 执行cURL会话
        $response = curl_exec($curl);
        // 检查是否有错误发生
        if (curl_errno($curl)) {
            return ['code'=>curl_error($curl),'msg'=>'Curl error: ' . curl_error($curl)];
        }
        // 关闭cURL资源
        curl_close($curl);
        if(is_string($response) && !empty($response)){
            $response1 = json_decode($response,true);
            if(!empty($response1)){
                $response = $response1;
            }
        }

        return $response;
    }
}