<?php

namespace app\home\controller;

use think\facade\View;
use think\facade\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Sellerpromotionbooth extends BaseSeller {

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'home/lang/' . config('lang.default_lang') . '/sellerpromotionbooth.lang.php');

        if (intval(config('ds_config.promotion_allow')) !== 1) {
            $this->error(lang('promotion_unavailable'), (string) url('Seller/index'));
        }
    }

    /**
     * 套餐商品列表
     */
    public function index() {
        $pbooth_model = model('pbooth');
        // 更新套餐状态
        $where = array();
        $where[] = array('store_id', '=', session('store_id'));
        $where[] = array('boothquota_endtime', '<', TIMESTAMP);
        $pbooth_model->editBoothClose($where);

        $isPlatformStore = check_platform_store() ? true : false;
        View::assign('isPlatformStore', $isPlatformStore);
        $hasList = $isPlatformStore;
        if (!$isPlatformStore) {
            // 检查是否已购买套餐
            $where = array();
            $where[] = array('store_id', '=', session('store_id'));
            $booth_quota = $pbooth_model->getBoothquotaInfo($where);
            View::assign('booth_quota', $booth_quota);
            if (!empty($booth_quota)) {
                $hasList = true;
            } elseif (intval(config('ds_config.promotion_booth_price')) == 0) {
                $hasList = true;
            } else {
                $update = array('boothgoods_state' => $pbooth_model::STATE0);
                $pbooth_model->editBooth($update, $where);
            }
        }

        if ($hasList) {
            // 查询已选择商品
            $boothgoods_list = $pbooth_model->getBoothgoodsList(array(array('store_id' ,'=', session('store_id'))), 'goods_id');
            if (!empty($boothgoods_list)) {
                $goodsid_array = array();
                foreach ($boothgoods_list as $val) {
                    $goodsid_array[] = $val['goods_id'];
                }
                $goods_list = model('goods')->getGoodsList(array(array('goods_id', 'in', $goodsid_array)), 'goods_id,goods_name,goods_image,goods_price,store_id,gc_id');
                if (!empty($goods_list)) {
                    $gcid_array = array();  // 商品分类id
                    foreach ($goods_list as $key => $val) {
                        $gcid_array[] = $val['gc_id'];
                        $goods_list[$key]['goods_image'] = goods_thumb($val);
                        $goods_list[$key]['url'] = (string) url('Goods/index', array('goods_id' => $val['goods_id']));
                    }
                    $goodsclass_list = model('goodsclass')->getGoodsclassListByIds($gcid_array);
                    $goodsclass_list = array_under_reset($goodsclass_list, 'gc_id');
                    View::assign('goods_list', $goods_list);
                    View::assign('goodsclass_list', $goodsclass_list);
                }
            }
        }
        $this->setSellerCurMenu('Sellerpromotionbooth');
        $this->setSellerCurItem('index');
        return View::fetch($this->template_dir . 'index');
    }

    /**
     * 选择商品
     */
    public function booth_select_goods() {
        $goods_model = model('goods');
        $condition = array();
        $condition[] = array('store_id', '=', session('store_id'));
        $goods_name = input('post.goods_name');
        if ($goods_name != '') {
            $condition[] = array('goods_name', 'like', '%' . $goods_name . '%');
        }
        $goods_list = $goods_model->getGoodsOnlineList($condition, '*', 10);

        View::assign('goods_list', $goods_list);
        View::assign('show_page', $goods_model->page_info->render());
        echo View::fetch($this->template_dir . 'select_goods');
    }

    /**
     * 购买套餐
     */
    public function booth_quota_add() {
        if (request()->isPost()) {
            if (intval(config('ds_config.promotion_booth_price')) == 0) {
                ds_json_encode(10001, lang('param_error'));
            }
            $quantity = intval(input('post.booth_quota_quantity')); // 购买的数量（月）
            $price_quantity = $quantity * intval(config('ds_config.promotion_booth_price')); // 扣款数
            if ($quantity <= 0 || $quantity > 12) {
                ds_json_encode(10001, lang('param_error'));
            }
            // 实例化模型
            $pbooth_model = model('pbooth');

            $data = array();
            $data['store_id'] = session('store_id');
            $data['store_name'] = session('store_name');
            $data['boothquota_starttime'] = TIMESTAMP;
            $data['boothquota_endtime'] = TIMESTAMP + 60 * 60 * 24 * 30 * $quantity;
            $data['boothquota_state'] = 1;

            $return = $pbooth_model->addBoothquota($data);
            if ($return) {
                // 添加店铺费用记录
                $this->recordStorecost($price_quantity, '购买推荐展位');

                // 添加任务队列
                $end_time = TIMESTAMP + 60 * 60 * 24 * 30 * $quantity;
                $this->addcron(array('exetime' => $end_time, 'exeid' => session('store_id'), 'type' => 4), true);
                $this->recordSellerlog('购买' . $quantity . '套推荐展位，单位元');
                ds_json_encode(10000, lang('ds_common_op_succ'));
            } else {
                ds_json_encode(10001, lang('ds_common_op_fail'));
            }
        }
        // 输出导航
        $this->setSellerCurMenu('Sellerpromotionbooth');
        $this->setSellerCurItem('booth_quota_add');
        return View::fetch($this->template_dir . 'quota_add');
    }

    /**
     * 套餐续费
     */
    public function booth_renew() {
        if (request()->isPost()) {
            if (intval(config('ds_config.promotion_booth_price')) == 0) {
                ds_json_encode(10001, lang('param_error'));
            }
            $pbooth_model = model('pbooth');
            $quantity = intval(input('post.booth_quota_quantity')); // 购买数量（月）
            $price_quantity = $quantity * intval(config('ds_config.promotion_booth_price')); // 扣款数
            if ($quantity <= 0 || $quantity > 12) {
                ds_json_encode(10001, lang('param_error'));
            }
            $condition = array();
            $condition[] = array('store_id','=',session('store_id'));
            $booth_quota = $pbooth_model->getBoothquotaInfo($condition);
            if ($booth_quota['boothquota_endtime'] > TIMESTAMP) {
                // 套餐未超时(结束时间+购买时间)
                $update['boothquota_endtime'] = intval($booth_quota['boothquota_endtime']) + 60 * 60 * 24 * 30 * $quantity;
            } else {
                // 套餐已超时(当前时间+购买时间)
                $update['boothquota_endtime'] = TIMESTAMP + 60 * 60 * 24 * 30 * $quantity;
            }
            $return = $pbooth_model->editBoothquotaOpen($update, $condition);

            if ($return) {
                // 添加店铺费用记录
                $this->recordStorecost($price_quantity, '购买推荐展位');

                // 添加任务队列
                $end_time = TIMESTAMP + 60 * 60 * 24 * 30 * $quantity;
                $this->addcron(array('exetime' => $end_time, 'exeid' => session('store_id'), 'type' => 4), true);
                $this->recordSellerlog('续费' . $quantity . '套推荐展位，单位元');
                ds_json_encode(10000, lang('ds_common_op_succ'));
            } else {
                ds_json_encode(10001, lang('ds_common_op_fail'));
            }
        }
        $this->setSellerCurMenu('Sellerpromotionbooth');
        $this->setSellerCurItem('booth_renew');
        return View::fetch($this->template_dir . 'quota_add');
    }

    /**
     * 选择商品
     */
    public function choosed_goods() {
        $gid = input('param.gid');
        if ($gid <= 0) {
            $data = array('result' => 'false', 'msg' => lang('param_error'));
            $this->_echoJson($data);
        }

        // 验证商品是否存在
        $goods_info = model('goods')->getGoodsInfoByID($gid);
        if (empty($goods_info) || $goods_info['store_id'] != session('store_id')) {
            $data = array('result' => 'false', 'msg' => lang('param_error'));
            $this->_echoJson($data);
        }

        $pbooth_model = model('pbooth');

        if (!check_platform_store()) {
            // 验证套餐时候过期
            $booth_info = $pbooth_model->getBoothquotaInfo(array(
                array('store_id', '=', session('store_id')),
                array('boothquota_endtime', '>', TIMESTAMP)
                    ), 'boothquota_id');
            if (empty($booth_info)) {
                if (intval(config('ds_config.promotion_booth_price')) != 0) {
                    $data = array('result' => 'false', 'msg' => lang('boothquota_expire'));
                    $this->_echoJson($data);
                }
            }
        }

        // 验证已添加商品数量，及选择商品是否已经被添加过
        $bootgoods_info = $pbooth_model->getBoothgoodsList(array(array('store_id' ,'=', session('store_id'))), 'goods_id');
        // 已添加商品总数
        if (count($bootgoods_info) >= config('ds_config.promotion_booth_goods_sum')) {
            $data = array('result' => 'false', 'msg' => sprintf(lang('promotion_booth_goods_sum_error'), config('ds_config.promotion_booth_goods_sum')));
            $this->_echoJson($data);
        }
        // 商品是否已经被添加
        $bootgoods_info = array_under_reset($bootgoods_info, 'goods_id');
        if (isset($bootgoods_info[$gid])) {
            $data = array('result' => 'false', 'msg' => lang('goods_already_add'));
            $this->_echoJson($data);
        }

        // 保存到推荐展位商品表
        $insert = array();
        $insert['store_id'] = session('store_id');
        $insert['goods_id'] = $goods_info['goods_id'];
        $insert['gc_id'] = $goods_info['gc_id'];
        $pbooth_model->addBoothgoods($insert);

        $this->recordSellerlog('添加推荐展位商品，商品id：' . $goods_info['goods_id']);

        // 输出商品信息
        $goods_info['goods_image'] = goods_thumb($goods_info);
        $goods_info['url'] = (string) url('Goods/index', array('goods_id' => $goods_info['goods_id']));
        $goods_class = model('goodsclass')->getGoodsclassInfoById($goods_info['gc_id']);
        $goods_info['gc_name'] = $goods_class['gc_name'];
        $goods_info['result'] = 'true';
        $this->_echoJson($goods_info);
    }

    /**
     * 删除选择商品
     */
    public function del_choosed_goods() {
        $gid = input('param.gid');
        if ($gid <= 0) {
            $data = array('result' => 'false', 'msg' => lang('param_error'));
            $this->_echoJson($data);
        }

        $result = model('pbooth')->delBoothgoods(array('goods_id' => $gid, 'store_id' => session('store_id')));
        if ($result) {
            $this->recordSellerlog('删除推荐展位商品，商品id：' . $gid);
            $data = array('result' => 'true');
        } else {
            $data = array('result' => 'false', 'msg' => lang('ds_common_del_fail'));
        }
        $this->_echoJson($data);
    }

    /**
     * 输出JSON
     * @param array $data
     */
    private function _echoJson($data) {
        echo json_encode($data);
        exit();
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string $menu_type 导航类型
     * @param string $name 当前导航的name
     * @return
     */
    protected function getSellerItemList() {
        $menu_array = array();
        switch (request()->action()) {
            case 'index':
                $menu_array = array(
                    array(
                        'name' => 'index', 'text' => lang('recommended_stand'),
                        'url' => (string) url('Sellerpromotionbooth/index')
                    )
                );
                break;
            case 'booth_quota_add':
                $menu_array = array(
                    array(
                        'name' => 'index', 'text' => lang('recommended_stand'),
                        'url' => (string) url('Sellerpromotionbooth/index')
                    ), array(
                        'name' => 'booth_quota_add', 'text' => lang('purchased_packages'),
                        'url' => (string) url('Sellerpromotionbooth/booth_quota_add')
                    )
                );
                break;
            case 'booth_renew':
                $menu_array = array(
                    array(
                        'name' => 'index', 'text' => lang('recommended_stand'),
                        'url' => (string) url('Sellerpromotionbooth/index')
                    ), array(
                        'name' => 'booth_renew', 'text' => lang('subscription_fee'), 'url' => (string) url('Sellerpromotionbooth/booth_renew')
                    )
                );
                break;
        }
        return $menu_array;
    }

}
