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

namespace app\plugins\model;

use think\Db;
use app\plugins\model\PointsGoods;
use app\plugins\model\PointsOrder;

/**
 * 积分商城模型
 */

load_trait('controller/Jump');
class PointsShop extends PointsShopBase
{
    use \traits\controller\Jump;

    private $times = 0;
    private $param = [];
    private $users = [];
    private $users_id = 0;

    // 构造函数
    public function __construct($param = [], $users = [])
    {
        // 统一接收参数处理
        $this->times = getTime();
        $this->param = !empty($param) ? $param : [];
        $this->users = !empty($users) ? $users : [];
        $this->users_id = !empty($this->users['users_id']) ? intval($this->users['users_id']) : 0;
        // 系统商城配置信息
        $this->systemShopConfig = getUsersConfigData('shop');
        // 获取积分商城插件信息
        $this->weappInfo = model('ShopPublicHandle')->getWeappPointsShop();
        // 积分商品模型
        $this->pointsGoodsModel = new PointsGoods($this->param, $this->users);
        // 积分商品购买模型
        $this->pointsOrderModel = new PointsOrder($this->param, $this->users);
    }

    // 获取积分商城首页数据
    public function getPointsShopIndex()
    {
        // 获取积分商城商品列表
        $result['goodsList'] = $this->pointsGoodsModel->getPointsGoodsList();
        // 返回数据
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 会员每日签到送积分
    public function usersDailyCheckIns()
    {
        // 执行会员每日签到送积分
        $result = model('ShopPublicHandle')->executeUsersDailyCheckIns($this->users_id);
        if (isset($result['code']) && 1 === intval($result['code'])) {
            $this->success($result['msg'], null, ['scores' => $result['scores'], 'checkInsPoints' => $result['checkInsPoints']]);
        } else {
            $this->error($result['msg']);
        }
    }

    // 获取系统积分规则
    public function getSystemPointsRules()
    {
        // 系统商城订单配置
        $result['systemOrderConfig'] = getUsersConfigData('order');
        // 获取系统积分规则
        $result['systemPointsRules'] = $this->getBaseSystemPointsRules();
        // 返回数据
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 获取会员积分明细数据
    public function getUsersPointsDetails()
    {
        // 获取会员积分明细数据
        $result = model('ShopPublicHandle')->getBaseUsersPointsDetails($this->users_id, $this->param);
        // 返回数据
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 获取积分商城商品详情
    public function getPointsGoodsDetails()
    {
        // 获取积分商城商品详情
        $result = $this->pointsGoodsModel->getPointsGoodsDetails();
        // 返回数据
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 积分商品购买预处理
    public function pointsGoodsBuyPreHandle()
    {
        // 系统商品和积分商品库存是否充足
        $this->pointsGoodsModel->detectPointsGoodsStock();
        // 系统商品和积分商品状态是否上架
        $this->pointsGoodsModel->detectPointsGoodsStatus();
        // 积分商品立即购买处理
        $this->pointsGoodsModel->nowBuyPointsGoods();
    }

    // 提交积分商品购买页面
    public function pointsGoodsBuyPage($loadPage = true)
    {
        // 查询提交的积分商品数据
        $pointsGoods = $this->pointsGoodsModel->getBuyPointsGoods();
        // 查询收货地址和运费计算
        $address = model('ShopPublicHandle')->getSystemAddress($this->users_id, $this->systemShopConfig, $this->param);
        // 虚拟商品则执行
        if (!empty($pointsGoods['prom_type']) && 1 === intval($pointsGoods['prom_type'])) $address['template_money'] = 0;
        // 到店自提商品则执行
        if (!empty($this->param['verifyShow']) || 2 === intval($pointsGoods['logistics_type'])) $address['template_money'] = 0;
        // 积分商品是包邮则执行
        if (!empty($pointsGoods['goods_shipping']) && 2 === intval($pointsGoods['goods_shipping'])) $address['template_money'] = 0;
        // 计算积分商品购买总价
        if (!empty($address) && !empty($address['template_money'])) {
            $pointsGoods['goodsTotalPrice'] = unifyPriceHandle($pointsGoods['goodsTotalPrice'] + $address['template_money']);
        }
        // 自定义字段
        $customField = [
            // 虚拟订单文案
            'virtual_text1' => '1、该产品为虚拟产品，仅支持在线支付且无需选择收货地址及运费计算。',
            'virtual_text2' => '2、若产品是充值类产品，请将您的手机号或需充值的卡号填入留言中。',
        ];

        $weChatPay = !empty($this->param['provider']) && 'h5' == $this->param['provider'] ? false : true;
        // 返回数据
        $result = [
            'customField' => $customField,
            'address' => !empty($address) ? $address : [],
            'pointsGoods' => !empty($pointsGoods) ? $pointsGoods : [],
            'weChatPayOpen' => model('ShopPublicHandle')->getWeChatPayOpen($weChatPay),
            'payBalanceOpen' => model('ShopPublicHandle')->getBalancePayOpen(),
        ];
        if (empty($loadPage)) {
            return $result;
        } else {
            $this->unifyParamSuccess('查询成功', null, $result);
        }
    }

    // 提交积分商品购买提交
    public function pointsGoodsBuySubmit()
    {
        // 查询商品和地址信息
        $result = $this->pointsGoodsBuyPage(false);
        if (empty($result['address'])) $this->error('请选择收货地址');
        // 积分商品订单创建逻辑
        $this->pointsOrderModel->pointsGoodsOrderCreate($result, $this->weappInfo['data']);
        // 下单购买的商品(系统商品and积分商品)库存(减少or增加)处理
        $this->pointsGoodsModel->updatePointsGoodsStock($result['pointsGoods']);
        // 积分商品订单提交支付逻辑
        $this->pointsOrderModel->pointsGoodsOrderBuyPay($result);
    }

    // 统一携带默认参数返回
    private function unifyParamSuccess($msg = '操作成功', $url = null, $result = [])
    {
        // 是否加载显示
        $result['loadShow'] = 1;
        // 会员信息
        $result['users'] = $this->users;
        // 积分商城功能设置
        $result['pointsShopConfig'] = $this->weappInfo['data'];
        // 系统商城配置
        $result['systemShopConfig'] = $this->systemShopConfig;
        // 获取商城店铺设置信息(后台-设置-店铺信息)
        $result['shopConf'] = model('ShopPublicHandle')->getWebShopConfig();
        // 获取商城支付设置信息(后台-设置-支付设置)
        $result['payConfig'] = model('ShopPublicHandle')->getShopPayConfig();
        // 返回结果
        if (model('ShopPublicHandle')->detectH5Terminal($this->param['terminal'])) {
            $pointsShopController = new \app\plugins\controller\PointsShop;
            $paramA = !empty($this->param['a']) ? $this->param['a'] : 'errorMsg';
            $pointsShopController->$paramA($result);
        } else {
            $this->success($msg, $url, $result);
        }
    }
}