<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\response\Json;
use app\admin\model\Store as StoreModel;
use app\admin\model\store\SyncTask;
use app\admin\service\store\User as StoreUserService;
use app\common\model\Channel;
use app\common\model\Merchant;
use app\store\model\store\User as StoreUserModel;
use app\store\model\store\Role as role;
use think\facade\Db;
use app\store\model\Goods as GoodsModel;
use app\store\model\GoodsCategoryRel;
use app\store\model\GoodsSku;
use app\store\model\GoodsImage;
use app\store\model\Category;
use app\store\model\GoodsSpecRel;

/**
 * 商城管理
 * Class Store
 * @package app\admin\controller
 */
class Store extends Controller
{
    /**
     * 强制验证当前访问的控制器方法method
     * @var array
     */
    protected array $methodRules = [
        'index' => 'GET',
        'recycle' => 'GET',
        'add' => 'POST',
        'move' => 'POST',
        'delete' => 'POST',
    ];

    /**
     * 商城列表
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function index(): Json
    {
        // 商城列表
        $model = new StoreModel;
        $list = $model->getList();
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            foreach ($list['data'] as &$value) {
                $value['store_version'] = $value['store_version'] == 0 ? "单商户" : "多商户";
            }
        }
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 获取商城登录token
     * @param int $storeId
     * @return Json
     */
    public function superLogin(int $storeId): Json
    {
        // 获取指定商城的管理员用户信息
        $userInfo = StoreUserService::getUserInfoByStoreId($storeId);
        if (empty($userInfo)) {
            return $this->renderError('未找到该商城管理员用户');
        }
        // 登录商户后台
        $token = StoreUserService::login($userInfo->toArray());
        return $this->renderSuccess([
            'userId' => $userInfo['store_user_id'],
            'token' => $token
        ]);
    }

    /**
     * 回收站列表
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function recycle(): Json
    {
        // 商城列表
        $model = new StoreModel;
        $list = $model->getList(true);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 新增商城
     * @return Json
     */
    public function add(): Json
    {
        // 新增记录
        $model = new StoreModel;
        if ($model->add($this->postForm())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }
    /**
     * 更新商城信息
     * @return Json
     */
    public function edit(int $storeId): Json
    {
        $params = $this->postForm();
        // 商城详情
        $model = StoreModel::detail($storeId);
        // 更新记录
        if (!$model->edit($params)) {
            return $this->renderError($model->getError() ?: '更新失败');
        }
        return $this->renderSuccess('更新成功');
    }
    /**
     * 移入回收站
     * @param int $storeId
     * @return Json
     */
    public function recovery(int $storeId): Json
    {
        // 商城详情
        $model = StoreModel::detail($storeId);
        if (!$model->recycle()) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 移出回收站
     * @param int $storeId
     * @return Json
     */
    public function move(int $storeId): Json
    {
        // 商城详情
        $model = StoreModel::detail($storeId);
        if (!$model->recycle(false)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 删除商城
     * @param int $storeId
     * @return Json
     */
    public function delete(int $storeId): Json
    {
        // 商城详情
        $model = StoreModel::detail($storeId);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 审核商城
     * @param int $storeId
     * @return Json
     */
    public function audit(int $storeId): Json
    {
        // 商城详情
        $model = StoreModel::detail($storeId);
        if (!$model->auditStore($this->request->param())) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }
    /**
     * 审核商城
     * @param int $storeId
     * @return Json
     */
    public function platformList(): Json
    {
        $list = $this->getUserPlatform();
        $platformList = [];
        foreach ($list as $key => $value) {
            $platformList[$value['code']] = $value['name'];
        }
        //$platformList = config('app.platformList');
        return $this->renderSuccess($platformList);
    }
    /**
     * 审核商城
     * @param int $storeId
     * @return Json
     */
    public function getStorePlatform(int $storeId): Json
    {
        $list = SyncTask::where("store_id", $storeId)->order('create_time desc')->select()->toArray();

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

     /**
     * 审核商城
     * @param int $storeId
     * @return Json
     */
    public function auth(int $storeId): Json
    {
        $platformList = $this->request->param('platformList');
        //多商户新增一个商户用户
        $model = StoreModel::detail($storeId);
        $storeUserModel = new StoreUserModel;
        if ($model->store_version == 1) {
            if ($platformList) {
                foreach ($platformList as $value) {
                
                    $channel = Channel::where('code', $value)->where('status',1)->find();
                    if ($channel->isEmpty()) {
                        return $this->renderError('当前渠道不存在');
                    }
                    $user_name = $channel->alias.$storeId;
                    //当前账号是否创建
                    $merchant = Merchant::where('channel_id', $channel->id)->where('store_id', $storeId)->where('is_delete', 0)->find();
                    if ($merchant) {
                        continue;
                    }
                    //创建账号
                    //查出当前店铺的商户角色的id
                    $whererole = [
                        'store_id' => $storeId,
                        'role_name' => "商户"
                    ];
                    $role = role::detail($whererole);
                    if (!$role) {
                        return $this->renderError('当前多商户商城商户角色不存在');
                    }
                    
                    $params = [
                        "real_name" => $channel->name,
                        "user_name" => $user_name,
                        "roles" => [$role->role_id],
                        "password" => "123456",
                        "password_confirm" => "123456",
                        "sort" => 100,
                        'storeId' => $storeId,
                    ];

                    // var_dump($params);
                    // exit();
                    $storeUserModel->addNew($params);
                    //复制商户
                    $merchantData = [
                        "shop_name" => $channel->shop_name,
                        "shop_label" => $channel->shop_label,
                        "channel_id" => $channel->id,
                        "channel" => $channel->code,
                        "store_id" => $storeId,
                        "user_name" => $user_name,
                        "score" => 5,
                        "sale" => 100,
                        "sort" => 100,
                        "license_img_id" => "",
                        "logo_image_id" => 0,
                        "create_time" => time(),
                    ];
                    // var_dump($merchantData);
                    // exit();
                    if ($channel->logo_image_id) {
                        //复制图片
                        $upload_file = Db::name('upload_file')->where('file_id', $channel->logo_image_id)->find();
                        if ($upload_file) {
                            $upload_file['store_id'] = $storeId;
                            $upload_file['create_time'] = time();
                            unset($upload_file['file_id']);
                            $logo_image_id = Db::name('upload_file')->insertGetId($upload_file);
                            $merchantData['logo_image_id'] = $logo_image_id;
                        }
                    }
                    
                    if ($channel->license_img_id) {
                        $arr = explode(",", $channel->license_img_id);
                        $license_img_ids = [];
                        foreach ($arr as $key => $val) {
                            //复制图片
                            $upload_file = Db::name('upload_file')->where('file_id', $val)->find();
                            if ($upload_file) {
                                $upload_file['store_id'] = $storeId;
                                $upload_file['create_time'] = time();
                                unset($upload_file['file_id']);
                                $license_img_id = Db::name('upload_file')->insertGetId($upload_file);
                                $license_img_ids[] = $license_img_id;
                            }
                        }
                        $merchantData['license_img_id'] = implode(",", $license_img_ids);
                    }
                    
                    Merchant::create($merchantData);
                    
                }
            }
            
            
        }

        // var_dump($model->store_version);
        // exit();
        
        $currItems = SyncTask::where('store_id', $storeId)->select()->toArray();
        if ($currItems) {
            $delIds = [];
            foreach ($currItems as $item) {
                if (!in_array($item['channel'], $platformList)) {
                    $delIds[] = $item['id'];
                }
            }
            unset($item);
            //删除
            if ($delIds) {
                SyncTask::whereIn('id', $delIds)->delete();
            }
        }
        $curr_channels = array_column($currItems, "channel");
        $inData = [];
        foreach ($platformList as $platform) {
            if (in_array($platform, $curr_channels)) {
                continue;
            }
            $merchantId = 0;
            if ($model->store_version == 1) {
                $merchant =  Merchant::where('channel', $platform)->where('store_id', $storeId)->find();
                $merchantId = $merchant->merchant_id;
            }
            
            $inData[] = [
                'store_id' => $storeId,
                'channel' => $platform,
                'create_time' => time(),
                'merchant_id' => $merchantId,
            ];
        }
        if ($inData) {
            $model = new SyncTask;
            $model->addAll($inData);
            
        }
        
        return $this->renderSuccess('操作成功');
    }
    /**
     * 多商户初始化
     * [merchant description]
     * @param  int    $storeId [description]
     * @return [type]          [description]
     */
    public function merchant(int $storeId): Json
    {
        $model = StoreModel::detail($storeId);
        if ($model->store_version == 1) {
            $model->addMerchantRoleAndMenu((int)$storeId);
        }
        return $this->renderSuccess();
    }
    
    /**
     * 删除商城的商品和商品分类
     * [merchant description]
     * @param  int    $storeId [description]
     * @return [type]          [description]
     */
    public function deleteGoods(int $storeId): Json
    {
        ini_set('memory_limit', '2024M');
        set_time_limit(0);
        $model = StoreModel::detail($storeId);
        if (!$model || $storeId <= 0) {
            return $this->renderError('商城不存在');
        }

        //删除分类
        Category::where('store_id', $storeId)->delete();
        // GoodsSku::where('store_id', $storeId)->delete();
        // GoodsImage::where('store_id', $storeId)->delete();
        // GoodsSpecRel::where('store_id', $storeId)->delete();
        // GoodsModel::where('store_id', $storeId)->delete();
        $page = 1;
        while (TRUE) {
            $goods_list = GoodsModel::where('store_id', $storeId)->where('channel','<>', 'zy')->field('goods_id')->page($page)->limit(2000)->select();
            if ($goods_list->isEmpty()) {
                return $this->renderSuccess();
            }
            $goods_ids = array_column($goods_list->toArray(), "goods_id");
            //删除商品sku
            GoodsSku::whereIn('goods_id', $goods_ids)->delete();
            //删除商品图片
            GoodsImage::whereIn('goods_id', $goods_ids)->delete();
            //删除商品规格
            GoodsSpecRel::whereIn('goods_id', $goods_ids)->delete();
            //删除商品
            GoodsModel::whereIn('goods_id', $goods_ids)->delete();
            $page++;
        }
        return $this->renderSuccess();
    }






}