<?php

namespace app\common\model;

use app\admin\model\user\UserExt;
use liuniu\BaseModel;
use think\Exception;
use think\Model;


class Rescue extends BaseModel
{





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

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

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

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



    public function getWorkWeekList()
    {
        return ['1' => __('Work_week 1'), '2' => __('Work_week 2'), '3' => __('Work_week 3'), '4' => __('Work_week 4'), '5' => __('Work_week 5'), '6' => __('Work_week 6'), '7' => __('Work_week 7')];
    }

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


    public function getWorkWeekTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['work_week']) ? $data['work_week'] : '');
        $valueArr = explode(',', $value);
        $list = $this->getWorkWeekList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setWorkWeekAttr($value)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    /**
     * 获取排序sql
     * @param $latitude
     * @param $longitude
     * @return mixed
     */
    public static function distanceSql($latitude, $longitude)
    {
        $field = "(round(6367000 * 2 * asin(sqrt(pow(sin(((latitude * pi()) / 180 - ({$latitude} * pi()) / 180) / 2), 2) + cos(({$latitude} * pi()) / 180) * cos((latitude * pi()) / 180) * pow(sin(((longitude * pi()) / 180 - ({$longitude} * pi()) / 180) / 2), 2))))) AS distance";
        return $field;
    }
    /**
     * 门店列表
     * @return mixed
     */
    public static function lst($cid,$latitude, $longitude, $page, $limit,$user_id=0,$status=1,$type=0)
    {
        $model = new self();
        if($status>-2) $model = $model->where('status', $status);
        $model = $model->where('cid',$cid);
        if($type==0) {
            if ($user_id > 0) $model = $model->where('user_id', $user_id);
        }else{
            $model = $model->where('user_id','<>', $user_id);
        }
        if ($latitude && $longitude) {
            $model = $model->field(['*', self::distanceSql($latitude, $longitude)])->order('distance asc');
        }
        $list = $model->page((int)$page, (int)$limit)
            ->select();
        if ($latitude && $longitude) {
            foreach ($list as &$value) {
                //计算距离
                $value['distance'] = self::getDistance($latitude, $longitude, $value['latitude'], $value['longitude']);
                //转换单位
                $value['range'] = bcdiv($value['distance'], 1000, 1);
                $sp = SosBill::where('user_id',$user_id)->where('rescuers_id',$value['id'])->whereTime('createtime',"today")->find();
                $value['is_create'] =$sp?1:0;
            }
        }
        return $list;
    }
    public static function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000; //approximate radius of earth in meters
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }
    public static function create1($data)
    {
        self::startTrans();
        try {
            $user = UserExt::where('user_id', $data['user_id'])->find();
            if (!$user) {
                UserExt::create(['full_name' => $data['name'], 'cid' => $data['cid'], 'address' => $data['address'], 'user_id' => $data['user_id']]);
            } else {
                $ext = null;
                if (!$user['full_name']) $ext['full_name'] = $data['name'];
                if (!$user['address']) $ext['address'] = $data['address'];
                if ($ext) UserExt::where('user_id')->update($ext);
            }
            $rs = self::create($data);
            self::commit();
            return $rs;
        }catch (Exception $e)
        {
            return self::setErrorInfo($e->getMessage(),true);
        }
    }
    public static function getuserId($id)
    {
        return self::where('id',$id)->value('user_id');
    }


}
