<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

class Companys extends Api
{
    protected $noNeedLogin = ['getList','getInfo'];
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = Db::name('company');
    }

    /**
     * 列表
     * @return void
     */
    public function getList()
    {
        try {
            $page = $this->request->param('page',1);
            $limit = $this->request->param('listrow',15);
            $offset = ($page - 1) * $limit;
            //获取门店信息
            $params = [
                'lng' => $this->request->param('lng',''),
                'lat' => $this->request->param('lat',''),
            ];
            $companyList = $this->getCompanySort($params);
            $result = array_slice($companyList['data'],$offset,$limit);
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 获取门店距离排序
     * @return void
     */
    public function getCompanySort($params=[])
    {
        try {
            $result = [
                'status' => true,
                'msg' => '获取成功',
                'data' => [],
            ];
            $lng = isset($params['lng']) ? $params['lng'] : '';
            $lat = isset($params['lat']) ? $params['lat'] : '';

            $field = 'id,name,image,contacts,mobile,full_address,longitude,latitude,is_open,open_hours';
            $where['status'] = 1;
            $data = $this->model->where($where)->field($field)->select();
            if (!empty($data)) {
                foreach ($data as $key => &$value) {
                    $value['image'] = !empty($value['image']) ? cdnurl($value['image']) : '';
                    $value['distance'] = getDistance($lng, $lat, $value['longitude'], $value['latitude'], true, 2);
                    $value['distance_text'] = !empty($value['distance']) ? $value['distance'].'km' : '';
                }
                $n = count($data);
                for($i=1;$i<$n;$i++) { //从第二个元素开始插入
                    for($j=$i-1;$j>=0;$j--) { //与前面的数比较,找到插入的位置
                        if($data[$j]['distance'] > $data[$j+1]['distance']) { //比前面的数小,交换位置
                            $tmp = $data[$j];
                            $data[$j] = $data[$j+1];
                            $data[$j+1] = $tmp;
                        } else { //大于或等于前面的数,表示已找到插入的位置
                            break;
                        }
                    }
                }
            }
            $result['data'] = $data;
            return $result;
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
            return $result;
        }
    }

    /**
     * 详情
     * @return void
     */
    public function getInfo()
    {
        try {
            $id = $this->request->param('id',0);
            $field = 'id,name,image,contacts,mobile,full_address,longitude,latitude,is_open,open_hours';
            $where['status'] = 1;
            $where['id'] = $id;
            $result = $this->model->where($where)->field($field)->find();
            if (!empty($result)) {
                !empty($result['image']) && $result['image'] = cdnurl($result['image']);
            }

            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 绑定门店
     * @return void
     */
    public function bind()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id',0);
            $comeform = $this->request->param('comeform','');
            $where['id'] = $id;
            $where['status'] = 1;
            $time = time();
            $company = $this->model->where($where)->find();
            if (empty($company)) {
                throw new Exception('未找到门店信息');
            }
            $user = $this->auth->getUser();
            $userId = $this->auth->id;
            if ($user['company_id'] != $id) {//更新绑定门店
                $userWhere['id'] = $userId;
                $userData['company_id'] = $id;
                $userRes = model('User')->where($userWhere)->update($userData);
                if (!$userRes) {
                    throw new Exception('绑定门店失败');
                }
            }
            //用户门店钱包
            $walletWhere['user_id'] = $userId;
            $walletWhere['company_id'] = $id;
            $userWallet = model('UserWallet')->where($walletWhere)->find();
            if (empty($userWallet)) {
                $walletData = [
                    'user_id' => $userId,
                    'company_id' => $id,
                    'staff_id' => 0,
                    'money' => 0.00,
                    'address' => '',
                    'createtime' => $time,
                    'updatetime' => $time,
                    'remark' => '',
                    'comefrom' => $comeform,
                ];
                $walletRes = model('UserWallet')->insertGetId($walletData);
                if (!$walletRes) {
                    throw new Exception('绑定失败');
                }
            }
            Db::commit();
            $this->success();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 保存
     * @return void
     */
    public function save()
    {
        try {
            //验证参数
            $id = $this->request->param('id',0);
            $userId = $this->auth->id;
            if (empty($id)) {
                $companyWhere['user_id'] = $userId;
                $company = $this->model->where($companyWhere)->find();
                if (!empty($company)) {
                    $id = $company['id'];
                }
            }
            $scene = !empty($id) ? 'edit' : 'add';
            $validate = validate('Companys');
            if(!$validate->check($this->request->param(),[],$scene)){
                throw new Exception($validate->getError());
            }
            if (!empty($id)) {
                $where['user_id'] = $userId;
                $where['id'] = $id;
                $companyData = $this->model->where($where)->find();
                if (empty($companyData)) {
                    throw new Exception('未找到相关信息');
                }
            } else {
                $where['user_id'] = $userId;
                $where['status'] = 1;//状态:-1=新来的,0=待审核,1=审核通过,2=审核不通过
                $companyData = $this->model->where($where)->find();
                if (!empty($companyData)) {
                    throw new Exception('您已申请过入驻');
                }
            }
            $time = time();
            $areaData = getProvince($this->request->param());
            $fullAddress = $areaData['full_address'];
            $data = [
                'contacts' => $this->request->param('contacts', ''),
                'mobile'  => $this->request->param('mobile', ''),
                'province_id'  => $this->request->param('province_id', 0),
                'city_id'  => $this->request->param('city_id', 0),
                'area_id'  => $this->request->param('area_id', 0),
                'province_name'  => $areaData['province_name'],
                'city_name'  => $areaData['city_name'],
                'area_name'  => $areaData['area_name'],
                'address'  => $this->request->param('address', ''),
                'full_address'  => $fullAddress,
                'aptitude_images'  => $this->request->param('aptitude_images', ''),
                'status' => 0,
            ];
            if (empty($id)) {
                $data['image'] = '/assets/img/avatar.png';//默认头像
                $data['user_id'] = $userId;
                $data['createtime'] = $time;
                $res = $this->model->insertGetId($data);
                if ($res) {//生成门店钱包
                    $companyAddData = [
                        'user_id' => $res,
                        'money' => 0.00,
                    ];
                    $companyRes = Db::name('company_wallet')->insertGetId($companyAddData);
                    if (!$companyRes) {
                        throw new Exception('入驻提交失败');
                    }
                }
            } else {
                $data['updatetime'] = $time;
                $where['id'] = $id;
                $where['user_id'] = $userId;
                $res = $this->model->where($where)->update($data);
            }
            if (!$res) {
                throw new Exception('操作失败');
            }
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 入驻详情
     * @return void
     */
    public function getCompanyInfo()
    {
        try {
            $userId = $this->auth->id;
            $field = 'id,contacts,mobile,province_id,city_id,area_id,province_name,city_name,area_name,address,aptitude_images,status';
            $where['user_id'] = $userId;
            $result = $this->model->where($where)->field($field)->find();
            if (!empty($result)) {
                $statusArr = model('Company')->getStatusList();
                $result['status_text'] = isset($statusArr[$result['status']]) ? $statusArr[$result['status']] : '';
                $result = info_domain_image($result,['aptitude_images']);
            }

            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}