<?php

namespace app\common\model;

use liuniu\BaseModel;
use liuniu\WechatTempleService;
use think\Exception;
use think\Model;


class Sos extends BaseModel
{





    // 表名
    protected $name = 'sos';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];



    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '-1' => __('Status -1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public static function sos_create($where)
    {
        self::beginTrans();
        try {
            if(SosBill::where('id', $where['user_id'])->where('rescuers_id',$where['rescuers_id'])->whereTime('createtime',"today")->where('status',0)->find()) return self::setErrorInfo('已求救，不用重复发起!');
            $where1 = $where;
            unset($where1['from']);
            unset($where1['re_url']);
            $res = self::create($where1);
            $user_phone = User::where('id', $where['user_id'])->value('mobile');
            $rescue_phone = User::where('id', $where['rescuers_user_id'])->value('mobile');
            $rescuers_id = Rescue::where('user_id',$where['rescuers_user_id'])->value('id');
            $res1 = SosBill::income($where['cid'], $where['user_id'], $res['id'], $rescuers_id,$where['rescuers_user_id'], $where['latitude'], $where['longitude'], $user_phone, $rescue_phone,$where['address']);
            //tudo 模板信息
            if($where['from'] == "weixin") {
                $data['first'] = "有人向你发起求救";
                $data['keyword1'] = $where['address'];
                $data['keyword2'] = date("Y-m-d H:i:s");
                $data['keyword3'] = $user_phone;
                $data['remark'] ="详细请点信息";
                $rs =  WechatTempleService::sendTemplate($where['cid'], UserRelation::userIdToOpenId($where['rescuers_user_id']), WechatTempleService::EMERGANCY_RESCUE,$data,$where['re_url']);
            }
            if($res && $res1)
            {
                self::commitTrans();
            }
        }catch (Exception $e)
        {
            return self::setErrorInfo($e->getMessage(),true);
        }

       return  $res;
    }




}
