<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-06-28
 */

namespace weapp\PointsShop\controller;

use think\Db;
use think\Page;
use think\Cookie;
use app\common\controller\Weapp;
use weapp\PointsShop\model\PointsGoods;
use weapp\PointsShop\model\PointsGoodsSpec;
use weapp\PointsShop\model\PointsShopModel;
use weapp\PointsShop\logic\PointsShopLogic;

/**
 * 插件的控制器
 */
class PointsShop extends Weapp
{
    // 构造方法
    public function __construct()
    {
        parent::__construct();
        // 当前时间戳
        $this->times = getTime();
        // 积分商城插件模型层
        $this->pointsModel = new PointsShopModel;
        // 积分商城插件业务层
        $this->pointsLogic = new PointsShopLogic;
        // 积分商品模型
        $this->pointsGoods = new PointsGoods;
        // 积分商品规格模型
        $this->pointsGoodsSpec = new PointsGoodsSpec;
        // 插件基本信息
        $this->weappInfo = $this->getWeappInfo();
        $this->assign('weappInfo', $this->weappInfo);
        // 获取插件data数据(无数据则默认填装数据)
        $this->data = Db::name('weapp')->where('code', $this->weappInfo['code'])->getField('data');
        if (!empty($this->data)) {
            $this->data = unserialize($this->data);
        } else {
            $this->data = [];
            $this->saveConfig(0, false);
        }
        $this->assign('data', $this->data);
        // 记录当前插件商品操作cookie值(时间戳)
        $this->goodsCookie = Cookie::get('goodsCookie');
        if (empty($this->goodsCookie)) {
            $this->goodsCookie = $this->times;
            Cookie::set('goodsCookie', $this->times, ['expire' => 86400]);
        }
        $this->goodsCookie = intval($this->goodsCookie);
    }

    // 插件安装的后置操作
    public function afterInstall()
    {
        if (!empty($this->weappInfo)) {
            // 会员中心扩展栏处理
            $this->pointsModel->usersMenuHandle('insert');
            // 数据前缀
            $prefix = config('database.prefix');
            // 订单表字段处理
            $this->pointsLogic->addShopOrderTableHandle($prefix);
        }
    }

    // 插件卸载的后置操作
    public function afterUninstall()
    {
        if (!empty($this->weappInfo)) {
            // 会员中心扩展栏处理
            $this->pointsModel->usersMenuHandle('delete');
            // 数据前缀
            $prefix = config('database.prefix');
            // 订单表字段处理
            $this->pointsLogic->delShopOrderTableHandle($prefix);
        }
    }

    // 积分商城功能设置
    public function config()
    {
        if (IS_AJAX_POST) {
            // 保存配置
            $this->saveConfig(input('post.openPoints/d', 0));
        }

        return $this->fetch();
    }

    // 保存配置
    private function saveConfig($openPoints = 0, $return = true)
    {
        // 开启积分商城
        $this->data['openPoints'] = intval($openPoints);
        // 售后规则设置
        $afterSale = input('post.afterSale/d', 1);
        if (isset($afterSale)) $this->data['afterSale'] = intval($afterSale);
        $afterSaleRule = input('post.afterSaleRule/d', 1);
        if (isset($afterSaleRule)) $this->data['afterSaleRule'] = intval($afterSaleRule);
        $afterSaleRuleDays = input('post.afterSaleRuleDays/d', 15);
        if (isset($afterSaleRuleDays)) $this->data['afterSaleRuleDays'] = intval($afterSaleRuleDays);
        // 更新插件设置数据
        $update = [
            'data' => serialize($this->data),
            'update_time' => getTime()
        ];
        $result = Db::name('weapp')->where('code', $this->weappInfo['code'])->update($update);
        if (!empty($return)) {
            if (!empty($result)) {
                // 会员中心扩展栏处理
                $this->pointsModel->usersMenuHandle('update', $openPoints);
                // 返回结束
                $this->success('保存成功');
            }
            $this->error('保存失败');
        }
    }

    // 积分商品列表
    public function index()
    {
        // 搜索项
        $title = input('title/s', '');
        $this->assign('title', $title);
        $stopTime = input('stopTime/s', '');
        $this->assign('stopTime', $stopTime);
        $startTime = input('startTime/s', '');
        $this->assign('startTime', $startTime);
        $goods_status = input('goods_status/d', 0);
        $this->assign('goods_status', $goods_status);

        // 获取积分商品列表
        $result = $this->pointsGoods->getPointsGoodsList($title, $goods_status, $startTime, $stopTime);
        $this->assign($result);

        // 会员中心扩展栏处理
        $this->pointsModel->usersMenuHandle('insert');

        return $this->fetch('index');
    }

    // 查询系统商品
    public function selectGoods()
    {
        $result = $this->pointsModel->getSystemGoodsList();
        $this->assign($result);
        $typeid = input('typeid/d', 0);
        $this->assign('typeid', $typeid);
        $arctype_html = allow_release_arctype($typeid, [2]);
        $this->assign('arctype_html', $arctype_html);
        return $this->fetch('select_goods');
    }

    // 加载显示商品
    public function showGoods($aidStr = '')
    {
        if (IS_AJAX_POST || !empty($aidStr)) {
            $aidStr = !empty($aidStr) ? $aidStr : input('post.aidStr/s', '');
            // empty($aidStr) && $this->error('请选择商品');
            $goodsList = $this->pointsModel->getSystemGoodsListShow($this->goodsCookie, explode(',', $aidStr));
            $this->assign('goodsList', $goodsList);
            return $this->fetch('show_goods');
        }
    }

    // 设置商品规格信息
    public function setGoodsSpec()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            // 设置商品规格信息
            $this->pointsGoodsSpec->setGoodsSpec($post);
        }

        $aid = input('param.aid/d', 0);
        $goods_id = input('param.goods_id/d', 0);
        if (empty($aid) || empty($goods_id)) $this->error('请选择商品');
        $this->assign('aid', $aid);
        $this->assign('goods_id', $goods_id);

        // 查询商品已选的规格值ID数组
        $goodsSpec = $this->pointsModel->getSystemGoodsSpec($aid);

        // 获取商品规格组合Html
        $goodsSpecCombi = $this->pointsLogic->getGoodsSpecCombi($goodsSpec, $aid, $goods_id);
        $this->assign('goodsSpecCombi', $goodsSpecCombi);

        return $this->fetch('set_goods_spec');
    }

    // 新增积分商品
    public function add()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            // 保存指定积分商品
            $this->pointsGoods->savePointsGoods($post);
        }

        // 删除指定积分商品(非手动保存商品)
        $this->pointsGoods->delPointsGoods($this->goodsCookie);

        return $this->fetch('add');
    }
    
    /**
     * 插件后台管理 - 编辑
     */
    public function edit()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            // 保存指定积分商品
            $this->pointsGoods->savePointsGoods($post);
        }

        $goods_id = input('param.goods_id/d', 0);
        empty($goods_id) && $this->error('请选择编辑的积分商品');
        $this->assign('goods_id', $goods_id);

        $pointsGoods = $this->pointsGoods->getPointsGoodsDetails($goods_id);
        $this->assign('pointsGoods', $pointsGoods);

        $showGoods = $this->showGoods($pointsGoods['aid']);
        $this->assign('showGoods', $showGoods);
        return $this->fetch('edit');
    }

    // 搜索指定积分商品
    public function goodsSearch()
    {
        if (IS_AJAX_POST) {
            $title = input('title/s', '');
            // empty($title) && $this->error('请输入商品名称');
            // 返回加载页面
            $this->success("操作成功", null, ['goodsList' => $this->loadGoodsList()]);
        }
        $this->error("操作失败");
    }

    // 更新指定积分商品
    public function goodsStatus()
    {
        $goods_id = input('goods_id/d', 0);
        $goods_status = input('goods_status/d', 0);
        if (IS_AJAX_POST && !empty($goods_id) && !empty($goods_status)) {
            // 更新指定积分商品
            $result = $this->pointsGoods->updatePointsGoods($goods_id, $goods_status);
            // 返回加载页面
            if (!empty($result)) $this->success("操作成功", null, ['goodsList' => $this->loadGoodsList()]);
        }
        $this->error("操作失败");
    }
    
    // 删除指定积分商品
    public function goodsDelete()
    {
        $goods_id = input('goods_id/a', []);
        $goods_id = eyIntval($goods_id);
        if (!empty($goods_id) && IS_AJAX_POST) {
            // 删除指定积分商品
            $result = $this->pointsGoods->delPointsGoods(0, $goods_id);
            // 返回加载页面
            if (!empty($result)) {
                $load = input('load/d', 1);
                $goodsList = !empty($load) ? $this->loadGoodsList() : [];
                $this->success("操作成功", null, ['goodsList' => $goodsList]);
            }
        }
        $this->error("操作失败");
    }

    // 加载商品列表数据
    private function loadGoodsList()
    {
        $result = $this->pointsGoods->getPointsGoodsList();
        $this->assign($result);
        return $this->fetch('goods_list');
    }
}