<?php


namespace app\models\system;

use crmeb\traits\ModelTrait;
use crmeb\basic\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 门店自提 model
 * Class SystemStore
 * @package app\model\system
 */
class SystemStore extends BaseModel
{
    use ModelTrait;

    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'system_store';

    public static function merSet($mer_id)
    {
        return $mer_id ? self::where('mer_id', $mer_id) : new self;
    }

    public static function getLatlngAttr($value, $data)
    {
        return $data['latitude'] . ',' . $data['longitude'];
    }

    public static function verificWhere($mer_id = false)
    {
        return self::merSet($mer_id)->where('is_show', 1)->where('is_del', 0);
    }

    /**
     * 获取门店信息
     * @param int $id
     * @param string $felid
     * @param bool $mer_id
     * @return array|mixed|null|string|\think\Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getStoreDispose($id = 0, $felid = '', $mer_id = false)
    {
        if ($id)
            $storeInfo = self::verificWhere($mer_id)->where('id', $id)->find();
        else
            $storeInfo = self::verificWhere($mer_id)->find();
        if ($storeInfo) {
            $storeInfo['latlng'] = self::getLatlngAttr(null, $storeInfo);
            $storeInfo['dataVal'] = $storeInfo['valid_time'] ? explode(' - ', $storeInfo['valid_time']) : [];
            $storeInfo['timeVal'] = $storeInfo['day_time'] ? explode(' - ', $storeInfo['day_time']) : [];
            $storeInfo['address2'] = $storeInfo['address'] ? explode(',', $storeInfo['address']) : [];
            if ($felid) return $storeInfo[$felid] ?? '';
        }
        return $storeInfo;
    }

    /**
     * 获取商品所属的门店
     */
    public static function getProductStore($id)
    {
        $res = SystemProductStore::alias('a')->where('a.product_id', $id)->join('system_store s', 's.id = a.store_id')->where('s.is_del', 0)->where('s.is_show', 1)->field('s.name')->select()->toArray();
        $res = array_column($res, 'name');
        $res = implode('，', $res);
        return $res;
    }

    /**
     * 获取门店详情
     */
    public static function getStoreInfo($id)
    {
        $storeInfo = self::where('id', $id)->find();
        if ($storeInfo) {
            $storeInfo['latlng'] = self::getLatlngAttr(null, $storeInfo);
            $storeInfo['dataVal'] = $storeInfo['valid_time'] ? explode(' - ', $storeInfo['valid_time']) : [];
            $storeInfo['timeVal'] = $storeInfo['day_time'] ? explode(' - ', $storeInfo['day_time']) : [];
            $storeInfo['address2'] = $storeInfo['address'] ? explode(',', $storeInfo['address']) : [];
            $storeInfo['products'] = SystemProductStore::alias('a')->where('store_id', $id)->join('store_product s', 's.id = a.product_id')->column('a.product_id as id, s.image');
        }
        return $storeInfo;
    }

    /**
     * 获取排序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;
    }

    /**
     * 门店列表
     * @param $latitude
     * @param $longitude
     * @param $page
     * @param $limit
     * @param string $keywords
     * @param int $type
     * @param bool $mer_id
     * @return mixed
     */
    public static function lst($latitude, $longitude, $page, $limit, $keywords = '', $type = 0, $mer_id = false, $product_id = false)
    {
        if(!$product_id){
            $model = self::merSet($mer_id);
            if ($type == 0) {
                $model = $model->where(['is_del' => 0, 'is_show' => 1]);
            } elseif ($type == 1) {
                $model = $model->where('is_show', 0);
            } else {
                $model = $model->where('is_del', 1);
            }
            if (isset($keywords) && $keywords != '') {
                $model = $model->where('id|name|introduction', 'like', '%' . $keywords . '%');
            }
            if ($latitude && $longitude) {
                $model = $model->field(['*', self::distanceSql($latitude, $longitude)]);
            }
            $count = $model->count('id');
            $list = $model->page((int)$page, (int)$limit)->select()->toArray();
            if ($latitude && $longitude) {
                foreach ($list as &$value) {
                    //计算距离
                    $value['distance'] = sqrt((pow((($latitude - $value['latitude']) * 111000), 2)) + (pow((($longitude - $value['longitude']) * 111000), 2)));
                    //转换单位
                    $value['range'] = bcdiv($value['distance'], 1000, 1);
                    $value['total_address'] = $value['address']. $value['detailed_address'];
                }
            }else {
                foreach ($list as &$value) {
                    $value['total_address'] = $value['address']. $value['detailed_address'];
                }
            }
            return compact('list', 'count');
        }else{
            $product_id = explode(',', $product_id);
            $model = self::merSet($mer_id);
            if ($type == 0) {
                $model = $model->where(['is_del' => 0, 'is_show' => 1]);
            } elseif ($type == 1) {
                $model = $model->where('is_show', 0);
            } else {
                $model = $model->where('is_del', 1);
            }
            if (isset($keywords) && $keywords != '') {
                $model = $model->where('id|name|introduction', 'like', '%' . $keywords . '%');
            }
            if ($latitude && $longitude) {
                $model = $model->field(['*', self::distanceSql($latitude, $longitude)]);
            }
            $list = $model->select()->toArray();
            $result = SystemProductStore::alias('a')->where('a.product_id', 'in', $product_id)->where('s.is_del', 0)->where('s.is_show', 1)->join('system_store s', 's.id = a.store_id')->field('s.*')->select()->toArray();
            $list = $result ? $result : $list;
            $count = count($list);
            if ($latitude && $longitude) {
                foreach ($list as &$value) {
                    //计算距离
                    $value['distance'] = sqrt((pow((($latitude - $value['latitude']) * 111000), 2)) + (pow((($longitude - $value['longitude']) * 111000), 2)));
                    //转换单位
                    $value['range'] = bcdiv($value['distance'], 1000, 1);
                    $value['total_address'] = $value['address']. $value['detailed_address'];
                }
            }else {
                foreach ($list as &$value) {
                    $value['total_address'] = $value['address']. $value['detailed_address'];
                }
            }
            return compact('list', 'count');
        }
    }

    /**
     * 获取门店下的商品
     */
    public static function getStoreProduct($page, $limit, $mer_id = false)
    {
        $list = self::merSet($mer_id)->where('is_del', 0)->where('is_show', 1)->page((int)$page, (int)$limit)->select()->each(function ($item) {
            $item['productList'] = SystemProductStore::alias('a')->where('a.store_id', $item['id'])->where('p.is_del', 0)->where('p.is_show', 1)->join('store_product p', 'p.id = a.product_id', 'right')->field('p.*')->page(1, 10)->select();
        })->toArray();
        return $list;
    }

    /**
     * 导出数据
     * @return mixed
     */
    public static function exportData($where)
    {
        $model = new self();
        if ($where['type'] == 0) {
            $model = $model->where(['is_del' => 0, 'is_show' => 1]);
        } elseif ($where['type'] == 1) {
            $model = $model->where('is_show', 0);
        } else {
            $model = $model->where('is_del', 1);
        }
        if (isset($where['mer_id']) && $where['mer_id'] != '') {
            $model = $model->where('mer_id', $where['mer_id']);
        }
        if (isset($where['keywords']) && $where['keywords'] != '') {
            $model = $model->where('id|name|introduction', 'like', '%' . $where['keywords'] . '%');
        }
        $list = $model->select()->toArray();

        return $list;
    }

    /**
     * 店员添加门店列表
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function dropList($mer_id = '')
    {
        return self::where(['is_show' => 1, 'is_del' => 0, 'mer_id' => $mer_id])->select()->toArray();
    }

    function array_unique_fb($array2D){
        foreach ($array2D as $v){
            $v=join(',',$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            $temp[]=$v;
        }
        $temp=array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
        foreach ($temp as $k => $v){
            $temp[$k]=explode(',',$v); //再将拆开的数组重新组装
        }
        return $temp;
    }
}