<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use app\api\service\Store as StoreService;
use app\api\service\User as UserService;
use app\api\validate\store\Store as StoreValidte;
use app\common\model\PriceSet;
use app\common\model\Store as StoreInfoModel;
use app\common\model\UploadFile;
use app\store\model\store\Address as AddressModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;
use app\common\model\successful;

/**
 * 商城基础信息
 * Class Store
 * @package app\api\controller
 */
class Store extends Controller
{
    /**
     * 获取商城基础信息
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function data(): Json
    {
        $service = new StoreService;
        return $this->renderSuccess($service->data());
    }

    public function joinStore(): Json
    {
        // 当前用户信息
        $userInfo = UserService::getCurrentLoginUser(true);
        $params = $this->request->param();
        $validate = new StoreValidte();
        // 表单验证
        if (!$validate->check($params)) {
            return $this->renderError($validate->getError());
        }
        $service = new StoreService;
        $res = $service->joinStore($params, $userInfo->user_id);
        if ($res['code'] == 0) {
            return $this->renderSuccess('申请成功,请耐心等待');
        } else {
            return $this->renderError($res['msg']);
        }

    }

    public function getStoreType(): Json
    {
        return $this->renderSuccess(config('store.store_type'));
    }

    public function joinData(): Json
    {
        // 当前用户信息
        $userInfo = UserService::getCurrentLoginUser(true);
        $service = new StoreService;
        return $this->renderSuccess($service->joinData($userInfo->user_id));
    }

    public function getStore(): Json
    {
        $service = new StoreService;
        $store = $service->getStore();
        $userLatitude = $this->request->param('userLat', 32.919925);   // 用户纬度
        $userLongitude = $this->request->param('userLng', 118.825957); // 用户经度
        foreach ($store as &$row) {
            $distanceInKm = calculateDistance($userLatitude, $userLongitude, $row['latitude'], $row['longitude']);
            $row['distance'] = $distanceInKm . "km";
        }
        return $this->renderSuccess($store);
    }

    public function editStore(): Json
    {
        $params = $this->request->param();
        $storeid = request()->header()['storeid'];
        $upData = [];
        if (isset($params['group_share_img_id']) && $params['group_share_img_id']) {
            $upData['group_share_img_id'] = $params['group_share_img_id'];
        }
        if (isset($params['min_profit']) && $params['min_profit']) {
            $upData['min_profit'] = $params['min_profit'];
        }
        if (isset($params['logo_image_id']) && $params['logo_image_id']) {
            $upData['logo_image_id'] = $params['logo_image_id'];
        }
        if (!$upData) {
            return $this->renderSuccess('ok');
        }
        StoreInfoModel::where('store_id', $storeid)->update($upData);
        return $this->renderSuccess('ok');
    }

    public function getStoreInfo(): Json
    {
        $storeid = request()->header()['storeid'];
        $info = StoreInfoModel::where('store_id', $storeid)->find()->toArray();
        $info['group_share_img'] = "";
        if ($info['group_share_img_id']) {
            $file = UploadFile::where('file_id', '=', $info['group_share_img_id'])->find();
            $info['group_share_img'] = $file->preview_url;
        }
        $info['logo_image'] = "";
        if ($info['logo_image_id']) {
            $file = UploadFile::where('file_id', '=', $info['logo_image_id'])->find();
            $info['logo_image'] = $file->preview_url;
        }
        $info['login_img'] = "";
        if ($info['login_img_id']) {
            $file = UploadFile::where('file_id', '=', $info['login_img_id'])->find();
            $info['login_img'] = $file->preview_url;
        }
        return $this->renderSuccess($info);
    }

    /**
     * 获取商家退货地址
     * @return Json
     * @throws DbException
     */
    public function getAddressList(): Json
    {
        $model = new AddressModel;
        $list = $model->getList(['type' => 20]);
        return $this->renderSuccess($list->toArray());
    }

    public function setStorePrice(): Json
    {
        $params = $this->request->param();
        $storeid = request()->header()['storeid'];
        // var_dump($params);
        // exit();
        //先删除
        PriceSet::where('store_id', $storeid)->where('type', $params['type'] ?? 0)->delete();
        $inDatas = [];
        foreach ($params['list'] as $value) {
            $categorys = explode(",", $value['category']);
            foreach ($categorys as $category) {
                foreach ($value['price_list'] as $price) {
                    $temp = [
                        'category' => $value['category'],
                        'code' => $category,
                        'store_id' => $storeid,
                        'type' => $params['type'],
                        'min' => $price['min'],
                        'max' => $price['max'],
                        'add_price_rate' => $price['add_price_rate'],
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                    $inDatas[] = $temp;
                }
            }


        }
        // echo "<pre>";
        // print_r($inDatas);
        // exit();
        $model = new PriceSet;
        $model->addAll($inDatas);
        return $this->renderSuccess('ok');
    }

    //加个设置回显
    public function getStorePriceInfo(int $type): Json
    {
        $storeid = request()->header()['storeid'];
        $list = PriceSet::where('store_id', $storeid)->where('type', $type)->field('category,code,min,max,add_price_rate')->group("category, min")->select()->toArray();
        $data = [];
        $arr = [];
        foreach ($list as $value) {
            $arr[$value['category']][] = $value;
        }
        foreach ($arr as $key => $item) {
            $data['list'][] = [
                'category' => $key,
                'price_list' => $item,
            ];
        }
        $data['type'] = $type;
        return $this->renderSuccess($data);
    }

    //加个设置回显
    public function test(int $type): Json
    {
        $storeid = request()->header()['storeid'];

        $categoryIds = [1001, 1002];
        $list = PriceSet::distributionPrice(90, 50, $categoryIds);


        return $this->renderSuccess($list);
    }


    public function story(): json
    {
        $page = $this->request->param('page') ?? 1;
        $servers = new successful();
        //$list = $servers->list($page);
        $list = successful:: withoutGlobalScope()->where('status',10)->order('sort','asc')->paginate(10, false, $page);
        $list->each(function ($item, $key) {
            $imageUrl = UploadFile::withoutGlobalScope()->where('file_id', $item['image_id'])->find();
            if ($imageUrl) {
                $item['image_url'] = $imageUrl['preview_url'];
            } else {
                $item['image_url'] = null; // 或者设置默认图片 URL
            }
        });
        return $this->renderSuccess(compact("list"));
    }
}