<?php
namespace app\models\store;
use crmeb\basic\BaseModel;
use crmeb\services\PHPExcelService;
use crmeb\traits\ModelTrait;
use app\admin\model\system\SystemGroupData;

class StoreWholesale extends BaseModel
{
    use ModelTrait;
    protected function getImagesAttr($value)
    {
        return json_decode($value, true) ?: [];
    }

    public function getDescriptionAttr($value)
    {
        return htmlspecialchars_decode($value);
    }
    public static function lst($where)
    {

    }
    public static function getWholeCount()
    {
        $seckillTime = sys_data('Whole_time') ?: [];//秒杀时间段
        $timeInfo = ['time' => 0, 'continued' => 0];
        foreach ($seckillTime as $key => $value) {
            $currentHour = date('H');
            $activityEndHour = bcadd((int)$value['time'], (int)$value['continued'], 0);
            if ($currentHour >= (int)$value['time'] && $currentHour < (int)$activityEndHour && (int)$activityEndHour < 24) {
                $timeInfo = $value;
                break;
            }
        }

        if ($timeInfo['time'] == 0) return 0;
        $activityEndHour = bcadd((int)$timeInfo['time'], (int)$timeInfo['continued'], 0);
        $startTime = bcadd(strtotime(date('Y-m-d')), bcmul($timeInfo['time'], 3600, 0));
        $stopTime = bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
        echo $startTime;
        return self::where('is_del', 0)->where('status', 1)->where('start_time', '<=', $startTime)->where('stop_time', '>=', $stopTime)->count();
    }
    /**
     * 获取批发列表
     * @param $time
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function WholeList($time, $page = 0, $limit = 20)
    {
        if ($page) $list = self::alias('n')->where('n.is_del', 0)->where('n.status', 1)->where('n.start_time', '<=', time())->where('n.stop_time', '>=', time() - 86400)->where('n.time_id', $time)->field('n.*')->order('n.sort desc')->page($page, $limit)->select();
        else $list = self::alias('n')->where('n.is_del', 0)->where('n.status', 1)->where('n.start_time', '<=', time())->where('n.stop_time', '>=', time() - 86400)->where('n.time_id', $time)->field('n.*')->order('sort desc')->select();
        if ($list) return $list->hidden(['cost', 'add_time', 'is_del'])->toArray();
        return [];
    }
    /**
     * 获取所有批发产品
     * @param string $field
     * @return array
     */
    public static function getListAll($offset = 0, $limit = 10, $field = 'id,image,title,price,ot_price,start_time,stop_time,stock,sales')
    {
        $time = time();
        $model = self::where('is_del', 0)->where('status', 1)->where('stock', '>', 0)->field($field)
            ->where('start_time', '<', $time)->where('stop_time', '>', $time)->order('sort DESC,add_time DESC');
        $model = $model->limit($offset, $limit);
        $list = $model->select();
        if ($list) return $list->toArray();
        else return [];
    }
    /**
     * 获取热门推荐的批发产品
     * @param int $limit
     * @param string $field
     * @return array
     */
    public static function getHotList($limit = 0, $field = 'id,image,title,price,ot_price,start_time,stop_time,stock')
    {
        $time = time();
        $model = self::where('is_hot', 1)->where('is_del', 0)->where('status', 1)->where('stock', '>', 0)->field($field)
            ->where('start_time', '<', $time)->where('stop_time', '>', $time)->order('sort DESC,add_time DESC');
        if ($limit) $model->limit($limit);
        $list = $model->select();
        if ($list) return $list->toArray();
        else return [];
    }
    /**
     * 获取批发是否有开启
     * @return bool
     */
    public static function getWholeContStatus()
    {
        $time = time();
        $count = self::where('is_del', 0)->where('status', 1)->where('start_time', '<', $time)->where('stop_time', '>', $time)->count();
        return $count ? true : false;
    }
    /** 获取批发产品库存
     * @param $id
     * @return mixed
     */
    public static function getProductStock($id)
    {
        return self::where('id', $id)->value('stock');
    }
    /**
     * 获取一条产品
     * @param $id
     * @param string $field
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getValidProduct($id, $field = '*',$is_news=0)
    {
        $time = time();
       $model = self::alias('n')->where('n.id', $id)->where('n.is_del', 0)->where('n.status', 1);
        if($is_news==0) $model = $model->where('n.start_time', '<', $time)->where('n.stop_time', '>', $time - 86400);
        $info = $model->field('n.*')->find();

        if ($info['id']) {
            return $info;
        } else {
            return [];
        }
    }
    /**
     * 获取批发是否已结束
     * @param $seckill_id
     * @return bool
     */
    public static function isWholeEnd($seckill_id)
    {
        $time_id = self::where('id', $seckill_id)->value('time_id');
        //秒杀时间段
        $seckillTime = sys_data('Whole_time') ?? [];
        $seckillTimeIndex = 0;
        $activityTime = [];
        if (count($seckillTime)) {
            foreach ($seckillTime as $key => &$value) {
                $currentHour = date('H');
                $activityEndHour = bcadd((int)$value['time'], (int)$value['continued'], 0);
                if ($activityEndHour > 24) {
                    $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                    $value['state'] = '即将开始';
                    $value['status'] = 2;
                    $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                } else {
                    if ($currentHour >= (int)$value['time'] && $currentHour < $activityEndHour) {
                        $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                        $value['state'] = '抢购中';
                        $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                        $value['status'] = 1;
                        if (!$seckillTimeIndex) $seckillTimeIndex = $key;
                    } else if ($currentHour < (int)$value['time']) {
                        $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                        $value['state'] = '即将开始';
                        $value['status'] = 2;
                        $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                    } else if ($currentHour >= $activityEndHour) {
                        $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                        $value['state'] = '已结束';
                        $value['status'] = 0;
                        $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                    }
                }

                if ($value['id'] == $time_id) {
                    $activityTime = $value;
                    break;
                }
            }
        }
        if (time() < $activityTime['stop'])
            return true;
        else
            return false;
    }
    /**
     * 检查批发活动状态
     * @param $seckill_id
     * @return bool
     */
    public static function checkStatus($seckill_id)
    {
        $time_id = self::where('id', $seckill_id)->value('time_id');
        //秒杀时间段
        $seckillTime = sys_data('Whole_time') ?? [];
        $seckillTimeIndex = 0;
        $activityTime = [];
        if (count($seckillTime)) {
            foreach ($seckillTime as $key => &$value) {
                $currentHour = date('H');
                $activityEndHour = bcadd((int)$value['time'], (int)$value['continued'], 0);
                if ($activityEndHour > 24) {
                    $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                    $value['state'] = '即将开始';
                    $value['status'] = 2;
                    $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                } else {
                    if ($currentHour >= (int)$value['time'] && $currentHour < $activityEndHour) {
                        $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                        $value['state'] = '抢购中';
                        $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                        $value['status'] = 1;
                        if (!$seckillTimeIndex) $seckillTimeIndex = $key;
                    } else if ($currentHour < (int)$value['time']) {
                        $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                        $value['state'] = '即将开始';
                        $value['status'] = 2;
                        $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                    } else if ($currentHour >= $activityEndHour) {
                        $value['time'] = strlen((int)$value['time']) == 2 ? (int)$value['time'] . ':00' : '0' . (int)$value['time'] . ':00';
                        $value['state'] = '已结束';
                        $value['status'] = 0;
                        $value['stop'] = (int)bcadd(strtotime(date('Y-m-d')), bcmul($activityEndHour, 3600, 0));
                    }
                }

                if ($value['id'] == $time_id) {
                    $activityTime = $value;
                    break;
                }
            }
        }
        return $activityTime;
    }
    public static function SaveExcel($where)
    {
        $model = new self;
        if ($where['status'] != '') $model = $model->where('status', $where['status']);
        if ($where['store_name'] != '') $model = $model->where('title|id', 'LIKE', "%$where[store_name]%");
        $list = $model->order('id desc')->where('is_del', 0)->select();
        count($list) && $list = $list->toArray();
        $excel = [];
        foreach ($list as $item) {
            if ($item['status']) {
                if ($item['start_time'] > time())
                    $item['start_name'] = '活动未开始';
                else if ($item['stop_time'] < time())
                    $item['start_name'] = '活动已结束';
                else if ($item['stop_time'] > time() && $item['start_time'] < time())
                    $item['start_name'] = '正在进行中';
            } else $item['start_name'] = '关闭';
            $excel[] = [
                $item['id'],
                $item['title'],
                $item['info'],
                $item['ot_price'],
                $item['price'],
                $item['stock'],
                $item['start_name'],
                $item['stop_time'],
                $item['stop_time'],
                $item['status'] ? '开启' : '关闭',
            ];
        }
        PHPExcelService::setExcelHeader(['编号', '活动标题', '活动简介', '原价', '秒杀价', '库存', '秒杀状态', '结束时间', '状态'])
            ->setExcelTile('秒杀产品导出', ' ', ' 生成时间：' . date('Y-m-d H:i:s', time()))
            ->setExcelContent($excel)
            ->ExcelSave();
    }
    /**
     * @param $where
     * @return array
     */
    public static function systemPage($where)
    {
        $model = new self;
        $model = $model->alias('s');
        if ($where['status'] != '') $model = $model->where('s.status', $where['status']);
        if ($where['store_name'] != '') $model = $model->where('s.title|s.id', 'LIKE', "%$where[store_name]%");
        $model = $model->page(bcmul($where['page'], $where['limit'], 0), $where['limit']);
        $model = $model->order('s.id desc');
        $model = $model->where('s.is_del', 0);
        return self::page($model, function ($item) {
            $item['store_name'] = $item['title'];
            if ($item['status']) {
                if (strtotime($item['start_time']) > time())
                    $item['start_name'] = '活动未开始';
                else if (bcadd(strtotime($item['stop_time']), 86400) < time())
                    $item['start_name'] = '活动已结束';
                else if (bcadd(strtotime($item['stop_time']), 86400) > time() && strtotime($item['start_time']) < time()) {
                    $config = SystemGroupData::get($item['time_id']);

                    if ($config) {
                        $arr = json_decode($config->value, true);
                
                        $now_hour = date('H', time());
                        $start_hour = $arr['time']['value'];
                        $continued = $arr['continued']['value'];
                        $end_hour = $start_hour + $continued;
                        if ($start_hour > $now_hour) {
                            $item['start_name'] = '活动未开始';
                        } elseif ($end_hour < $now_hour) {
                            $item['start_name'] = '活动已结束';
                        } else {
                            $item['start_name'] = '正在进行中';
                        }
                        $item['time_id_title'] = $arr['time']['value'];;
                    } else {
                        $item['start_name'] = '正在进行中';
                    }
                }
            } else $item['start_name'] = '关闭';

        }, $where, $where['limit']);
    }
    /**
     * 获取批发产品id
     * @return array
     */
    public static function getWholeIdAll()
    {
        return self::where('is_del', 0)->column('id', 'id');
    }
}