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

namespace app\plugins\model;

use think\Db;

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

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

    // 获取系统积分规则
    public function getBaseSystemPointsRules()
    {
        // 积分配置信息
        return getUsersConfigData('score');
    }

    // 默认图片处理
    public function getDefaultPic($pic_url = '', $domain = true, $tcp = '')
    {
        $pic_url = get_default_pic($pic_url, $domain);
        $pic_url = str_replace('/public/static/common/images/not_adv.jpg', '/public/static/common/images/default_litpic_1.png', $pic_url);
        if (!empty($tcp) && preg_match('/^\/\/.*$/', $pic_url)) $pic_url = $tcp . ':' . $pic_url;

        return $pic_url;
    }

    // 获取系统商品轮播图
    public function getGoodsImgImageList($litpic = '', $aid = 0, $terminal = '')
    {
        $productImgModel = new \app\home\model\ProductImg;
        $imageList = $productImgModel->getProImg($aid, 'aid, image_url, intro');
        $imageList = !empty($imageList[$aid]) ? $imageList[$aid] : [];
        foreach ($imageList as $key => $value) {
            $value['image_url'] = $this->getDefaultPic($value['image_url']);
            isset($value['intro']) && $value['intro'] = htmlspecialchars_decode($value['intro']);
            $imageList[$key] = $value;
        }
        $provider = input('provider/s', '');
        $provider = strtolower($provider);
        if ('h5' == $terminal || 'h5' == $provider) {
            if (!empty($imageList)) {
                return $imageList;
            } else {
                return [['aid'=>$aid, 'image_url'=>$litpic, 'intro'=>'']];
            }
        } else {
            if (!empty($litpic)) {
                $litpic = [['aid'=>$aid, 'image_url'=>$litpic, 'intro'=>'']];
                return !empty($imageList) ? array_merge($litpic, $imageList) : $litpic;
            } else {
                return $imageList;
            }
        }
    }

    // 获取系统商品内容中的图片
    public function handleGoodsContentPic($content = '', $timeVersion = false)
    {
        $domain = request()->domain();
        if (!empty($content)) {
            $t = '';
            if (true === $timeVersion) $t = '?t='.getTime();

            // 图片远程化
            $pregRule = "/<img(.*?)src(\s*)=(\s*)[\'|\"](\/[\/\w]+)?(\/public\/upload\/|\/uploads\/|\/\/)(.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp|\.ico]))[\'|\"](.*?)[\/]?(\s*)>/i";
            $content  = preg_replace($pregRule, '<img ${1} src="' . $domain . ROOT_DIR . '${5}${6}'.$t.'" ${7} />', $content);
            // 视频远程化
            $pregRule = "/<source(.*?)src(\s*)=(\s*)[\'|\"](\/[\/\w]+)?(\/public\/upload\/|\/uploads\/|\/\/)(.*?(?:[\.mp4|\.mov|\.m4v|\.3gp|\.avi|\.m3u8|\.webm]))[\'|\"](.*?)[\/]?(\s*)>/i";
            $content  = preg_replace($pregRule, '<source ${1} src="' . $domain . ROOT_DIR . '${5}${6}" ${7} />', $content);
            $pregRule = "/<video(.*?)src(\s*)=(\s*)[\'|\"](\/[\/\w]+)?(\/public\/upload\/|\/uploads\/|\/\/)(.*?(?:[\.mp4|\.mov|\.m4v|\.3gp|\.avi|\.m3u8|\.webm]))[\'|\"](.*?)[\/]?(\s*)>/i";
            $content  = preg_replace($pregRule, '<video ${1} src="' . $domain . ROOT_DIR . '${5}${6}" ${7} />', $content);
            $content = str_replace($domain . ROOT_DIR.'//', 'http://', $content);
        }

        return $content;
    }

    // 获取系统商品参数
    public function getSystemGoodsAttr($aid = 0, $attrlist_id = 0, $handle = false)
    {
        // 查询系统商品参数
        $attr_list = [];
        $productAttrModel = new \app\home\model\ProductAttr;
        if (!empty($attrlist_id)) {
            // 新版参数
            $attr_list = $productAttrModel->getProAttrNew($aid, 'a.attr_id, a.attr_name, b.attr_value, b.aid');
        } else {
            // 旧版参数
            $attr_list = $productAttrModel->getProAttr($aid);
        }
        $attr_list = !empty($attr_list[$aid]) ? $attr_list[$aid] : [];
        foreach ($attr_list as $key => $value) {
            $value['attr_value'] = htmlspecialchars_decode($value['attr_value']);
            $attr_list[$key] = $value;
        }
        if (!empty($handle)) {
            $result = '';
            foreach ($attr_list as $value) {
                $result .= $value['attr_name'] . '：' . $value['attr_value'] . '<br/>';
            }
            return $result;
        } else {
            return !empty($attr_list) ? $attr_list : false;
        }
    }

    // 获取系统商品规格
    public function getSystemGoodsSpec($aid = 0, $spec_value_id = 0, $handle = false)
    {
        $spec_value = '';
        if (!empty($spec_value_id)) {
            $spec_value_id = explode('_', $spec_value_id);
            if (!empty($spec_value_id)) {
                $where = [
                    'aid' => $aid,
                    'spec_value_id' => ['IN', $spec_value_id],
                ];
                $spec_list = Db::name("product_spec_data")->field('spec_name, spec_value')->where($where)->select();
                foreach ($spec_list as $value) {
                    $spec_value .= $value['spec_name'] . '：' . $value['spec_value'] . '<br/>';
                }
            }
        }
        return $spec_value;
    }

    // 获取系统商品自定义字段
    public function getSystemCustomField($aid = 0, $channel = 0)
    {
        $field = 'id, aid, content, content_ey_m, add_time, update_time';
        $detailRow = Db::name('product_content')->field($field, true)->where('aid', $aid)->find();
        if (!empty($detailRow)) {
            $fieldLogic = new \app\home\logic\FieldLogic();
            $detailExt = $fieldLogic->getChannelFieldList($detailRow, $channel);
        }
        if (!empty($detailExt)) {
            $where = [
                'name' => ['IN', array_keys($detailExt)],
                'channel_id' => $channel,
                'ifeditable' => 1
            ];
            $customField = Db::name('channelfield')->field('name, title, dtype')->where($where)->getAllWithIndex('name');
            if (!empty($customField)) {
                foreach ($customField as $key => $value) {
                    if ('img' == $value['dtype']) {
                        $customField[$key]['value'] = $this->get_default_pic($detailExt[$key]);
                    } else if ('media' == $value['dtype']) {
                        $customField[$key]['value'] = $this->get_default_pic($detailExt[$key]);
                    } else if ('imgs' == $value['dtype']) {
                        foreach ($detailExt[$key] as $kk => $vv) {
                            $detailExt[$key][$kk]['image_url'] = $this->get_default_pic($vv['image_url']);
                        }
                        $customField[$key]['value'] = $detailExt[$key];
                    } else {
                        $customField[$key]['value'] = $detailExt[$key];
                    }
                }
            }
        }
        return !empty($customField) ? array_values($customField) : false;
    }

    // 返回积分商品下单购买需要存入订单副表的字段数据
    public function getPointsGoodsBuyField($pointsGoods = [])
    {
        return [
            'aid' => !empty($pointsGoods['aid']) ? intval($pointsGoods['aid']) : 0,
            'goods_id' => !empty($pointsGoods['goods_id']) ? intval($pointsGoods['goods_id']) : 0,
            'goods_price' => !empty($pointsGoods['goods_price']) ? floatval($pointsGoods['goods_price']) : 0,
            'goods_points' => !empty($pointsGoods['goods_points']) ? intval($pointsGoods['goods_points']) : 0,
            'goodsSpecID' => !empty($pointsGoods['goodsSpecID']) ? intval($pointsGoods['goodsSpecID']) : 0,
            'goodsSpecNames' => !empty($pointsGoods['goodsSpecNames']) ? $pointsGoods['goodsSpecNames'] : [],
            'goodsSpecKeys' => !empty($pointsGoods['goodsSpecKeys']) ? strval($pointsGoods['goodsSpecKeys']) : '',
            'goodsBuyNumber' => !empty($pointsGoods['goodsBuyNumber']) ? intval($pointsGoods['goodsBuyNumber']) : 0,
            'goodsTotalPrice' => !empty($pointsGoods['goodsTotalPrice']) ? floatval($pointsGoods['goodsTotalPrice']) : 0,
            'goodsTotalPoints' => !empty($pointsGoods['goodsTotalPoints']) ? intval($pointsGoods['goodsTotalPoints']) : 0,
            'goodsSinglePrice' => !empty($pointsGoods['goodsSinglePrice']) ? floatval($pointsGoods['goodsSinglePrice']) : 0,
            'goodsSinglePoints' => !empty($pointsGoods['goodsSinglePoints']) ? intval($pointsGoods['goodsSinglePoints']) : 0,
        ];
    }
}