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

namespace weapp\PointsShop\model;

use think\Db;
use think\Page;
use weapp\PointsShop\model\PointsGoods;

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

load_trait('controller/Jump');

class PointsShopModel
{
    use \traits\controller\Jump;

    // 构造方法
    public function __construct() {
        // 支持模型: 2(产品模型)
        $this->channeltype = 2;
        // 当前时间戳
        $this->times = getTime();
        // 积分商品规格模型
        $this->pointsGoods = new PointsGoods;
        // 积分商品表
        $this->archives_db = Db::name('archives');
    }

    // 获取系统商品列表 -- 提供加载设置积分商品规格
    public function getSystemGoodsSpec($aid = 0)
    {
        $where = [
            'aid' => $aid,
            'spec_is_select' => 1,
        ];
        $field = 'spec_mark_id, spec_value_id';
        $order = 'spec_value_id asc, spec_id asc';
        $goodsSpec = Db::name('product_spec_data')->field($field)->where($where)->order($order)->select();
        $goodsSpec = !empty($goodsSpec) ? group_same_key($goodsSpec, 'spec_mark_id') : [];
        foreach ($goodsSpec as $key => $value) {
            for ($i = 0; $i < count($value); $i++) {
                $goodsSpec[$key][$i] = $value[$i]['spec_value_id'];
            }
        }

        return $goodsSpec;
    }

    // 获取系统商品列表 -- 提供加载选择商品
    public function getSystemGoodsList($goodsCookie = 0)
    {
        // 查询处理
        $where = [
            'a.arcrank' => ['EGT', 0],
        ];
        // 关键字查询
        $keywords = input('param.keywords', '');
        if (!empty($keywords)) $where['a.title'] = ['LIKE', "%{$keywords}%"];

        // 栏目查询
        $typeid = input('param.typeid/d', 0);
        $hasRow = model('Arctype')->getHasChildren($typeid);
        $typeids = get_arr_column($hasRow, 'id');
        $stypeid_where = "";
        if (!empty($typeids)) {
            $typeid_arr = array_unique($typeids);
            foreach ($typeid_arr as $_k => $_v) {
                if (!empty($_k)) $stypeid_where .= " OR ";
                $stypeid_where .= "CONCAT(',', a.stypeid, ',') LIKE '%,{$_v},%' ";
            }
            $stypeid_where = Db::raw(" ({$stypeid_where}) ");
        }

        // 合并查询条件
        $where = array_merge($where, ['a.channel' => $this->channeltype, 'a.is_del' => 0]);
        $whereNew = "(a.users_id = 0 OR (a.users_id > 0 AND a.arcrank >= 0))";

        // 自定义排序
        $orderby = input('param.orderby/s');
        $orderway = input('param.orderway/s');
        if (!empty($orderby) && !empty($orderway)) {
            $orderby = "a.{$orderby} {$orderway}, a.aid desc";
        } else {
            $orderby = "a.aid desc";
        }

        // 查询商品数据
        $count = $this->archives_db->alias('a')->where($where)->where($whereNew)->where($stypeid_where)->count('aid');
        $Page = new Page($count, config('paginate.list_rows'));
        $list = [];
        if (!empty($count)) {
            $limit = $count > config('paginate.list_rows') ? $Page->firstRow.','.$Page->listRows : $count;
            $list = $this->archives_db
                ->field("a.aid")
                ->alias('a')
                ->where($where)
                ->where($whereNew)
                ->where($stypeid_where)
                ->order($orderby)
                ->limit($limit)
                ->getAllWithIndex('aid');
            if (!empty($list)) {
                $aids = array_keys($list);
                $fields = "b.*, a.*, a.aid as aid";
                $row = $this->archives_db
                    ->field($fields)
                    ->alias('a')
                    ->join('__ARCTYPE__ b', 'a.typeid = b.id', 'LEFT')
                    ->where('a.aid', 'in', $aids)
                    ->getAllWithIndex('aid');
                $pointsGoods = $this->pointsGoods->getPointsGoods($goodsCookie, $aids);
                foreach ($list as $key => $val) {
                    $row[$val['aid']]['arcurl'] = get_arcurl($row[$val['aid']]);
                    $row[$val['aid']]['litpic'] = get_default_pic($row[$val['aid']]['litpic']);
                    $row[$val['aid']]['goods_save'] = !empty($pointsGoods[$val['aid']]['goods_save']) ? intval($pointsGoods[$val['aid']]['goods_save']) : 0;
                    $list[$key] = $row[$val['aid']];
                }
            }
        }

        $result['list'] = $list;
        $result['pager'] = $Page;
        $result['page'] = $Page->show();
        return $result;
    }

    // 获取系统商品列表 -- 加载显示页面
    public function getSystemGoodsListShow($goodsCookie = 0, $aidStr = '')
    {
        // 查询商品信息
        $where = [
            'aid' => ['IN', $aidStr]
        ];
        $field = 'aid, title, litpic, users_price, stock_count';
        $goodsList = $this->archives_db->field($field)->where($where)->order('aid desc')->select();
        // 查询商品规格
        $field = 'aid, spec_price, spec_stock';
        $specPrice = Db::name('product_spec_value')->field($field)->where($where)->order('spec_price asc')->select();
        $specPrice = !empty($specPrice) ? group_same_key($specPrice, 'aid') : [];

        // 查询是否已添加到积分商品
        $pointsGoods = $this->pointsGoods->getPointsGoods(0, $aidStr);

        $saveAll = [];
        // 处理商品信息
        foreach ($goodsList as $key => $value) {
            $value['litpic'] = get_default_pic($value['litpic']);
            $value['goods_spec'] = 0;
            $value['spec_price'] = '￥' . $value['users_price'];
            if (!empty($specPrice[$value['aid']])) {
                $value['goods_spec'] = 1;
                $minPrice = min($specPrice[$value['aid']]);
                $maxPrice = max($specPrice[$value['aid']]);
                $value['spec_price'] = '￥' . $minPrice['spec_price'] . '~' . '￥' . $maxPrice['spec_price'];
            }
            $goodsList[$key] = $value;

            // 积分商品数据
            $saveAll[$key] = [
                'goods_id' => 0,
                'aid' => intval($value['aid']),
                'goods_spec' => $value['goods_spec'],
                'goods_cookie' => $goodsCookie,
                'add_time' => $this->times,
                'update_time' => $this->times,
            ];
            if (!empty($pointsGoods[$value['aid']]['goods_id'])) {
                unset($saveAll[$key]['add_time']);
                $saveAll[$key]['goods_id'] = intval($pointsGoods[$value['aid']]['goods_id']);
            } else {
                unset($saveAll[$key]['goods_id']);
            }
        }

        // 同步添加数据并获取积分商品ID
        $result = !empty($saveAll) ? $this->pointsGoods->saveAll($saveAll) : false;
        if (!empty($result)) {
            $pointsGoods = $this->pointsGoods->getPointsGoods($goodsCookie, $aidStr);
        }

        // 将积分商品ID追加到数组
        foreach ($goodsList as $key => $value) {
            $value['goods_id'] = !empty($pointsGoods[$value['aid']]['goods_id']) ? intval($pointsGoods[$value['aid']]['goods_id']) : 0;
            $value['goods_stock'] = !empty($pointsGoods[$value['aid']]['goods_stock']) ? intval($pointsGoods[$value['aid']]['goods_stock']) : 0;
            $value['goods_price'] = !empty($pointsGoods[$value['aid']]['goods_price']) ? intval($pointsGoods[$value['aid']]['goods_price']) : 0;
            $value['goods_points'] = !empty($pointsGoods[$value['aid']]['goods_points']) ? intval($pointsGoods[$value['aid']]['goods_points']) : 0;
            $value['goods_spec_set'] = !empty($pointsGoods[$value['aid']]['goods_spec_set']) ? intval($pointsGoods[$value['aid']]['goods_spec_set']) : 0;
            $goodsList[$key] = $value;
        }

        return $goodsList;
    }

    // 会员中心扩展栏处理
    public function usersMenuHandle($action = '', $openPoints = 0)
    {
        $mca = 'plugins/PointsShop/index';
        $where = [
            'mca' => $mca,
        ];
        // 新增扩展栏
        if ('insert' == $action) {
            $isCount = Db::name('users_menu')->where($where)->count();
            if (empty($isCount)) {
                Db::name('users_menu')->insert([
                    'title'       => '积分商城',
                    'mca'         => $mca,
                    'is_userpage' => 0,
                    'sort_order'  => 100,
                    'status'      => 1,
                    'add_time'    => $this->times,
                    'update_time' => $this->times,
                ]);
            }
        }
        // 更新扩展栏
        else if ('update' == $action) {
            // 开启积分商城则显示会员中心入口，关闭则隐藏
            $status = !empty($openPoints) && 1 === intval($openPoints) ? 1 : 0;
            Db::name('users_menu')->where($where)->update([
                'title' => '积分商城',
                'status' => $status,
                'update_time' => getTime()
            ]);
        }
        // 删除扩展栏
        else if ('delete' == $action) {
            Db::name('users_menu')->where($where)->delete(true);
        }
    }

}