<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\coupon;


use app\adminapi\lists\BaseAdminDataLists;
use app\common\model\coupon\CouponCategory;
use app\common\model\coupon\CouponRules;
use app\common\lists\ListsSearchInterface;
use app\common\model\goods\Goods;
use think\db\Query;


/**
 * CouponRules列表
 * Class CouponRulesLists
 * @package app\adminapi\listscoupon
 */
class CouponRulesLists extends BaseAdminDataLists implements ListsSearchInterface
{


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/07/18 10:11
     */
    public function setSearch(): array
    {
        return [
            '=' => ['amount',  'amount_require',  'max_deductible_price', 'mold_type', 'server_category_name', 'coupon_type','voucher_status','coupon_target'],
            '%like%' => ['event_name','code'],
        ];
    }

    public function queryWhere()
    {
        $where = [];
        if(isset($this->params['min_expire_time']) && is_numeric($this->params['min_expire_time'])){
            $where[] = ['expire_time', '>=', $this->params['min_expire_time']];
        }
        if(isset($this->params['max_expire_time']) && is_numeric($this->params['min_expire_time'])){
            $where[] = ['expire_time', '<=', $this->params['min_expire_time']];
        }
        if(isset($this->params['min_expire_time']) && is_numeric($this->params['min_expire_time'])){
            $where[] = ['expire_time', '>=', $this->params['min_expire_time']];
        }
        if(isset($this->params['min_voucher_count']) && is_numeric($this->params['min_voucher_count'])){
            $where[] = ['voucher_count', '>=', $this->params['min_voucher_count']];
        }
        if (isset($this->params['labels']) && !empty($this->params['labels'])) {
            $sqls = [];
            foreach ($this->params['labels'] as $item) {
                $sqls[] = "FIND_IN_SET({$item}, labels) > 0";
            }
            $query_sql = implode(' OR ', $sqls);
            $period_ids = CouponRules::where('labels','<>', '')->whereRaw($query_sql)->column('id');
            $where[] = [ 'id','IN',$period_ids?:[0]];
        }
        if(isset($this->params['max_voucher_count']) && is_numeric($this->params['max_voucher_count'])){
            $where[] = ['voucher_count', '<=', $this->params['max_voucher_count']];
        }
        if(isset($this->params['min_remaining_count']) && is_numeric($this->params['min_remaining_count'])){
            $where[] = ['remaining_count', '>=', $this->params['min_remaining_count']];
        }
        if(isset($this->params['max_remaining_count']) && is_numeric($this->params['max_remaining_count'])){
            $where[] = ['remaining_count', '<=', $this->params['max_remaining_count']];
        }
        if(isset($this->params['goods_category_ids']) && !empty($this->params['goods_category_ids'])){
           $categoryIds =[];
            foreach($this->params['goods_category_ids'] as $v){
                $v = json_decode($v,true)?? (array)$v;
                $categoryIds[] = end($v);
            }
            $ids = CouponRules::alias('cr')
                ->join('coupon_category cc','cr.id = cc.coupon_id')
                ->whereIn('cc.goods_category_id',$categoryIds)->distinct(true)->field('cc.coupon_id')->column('cc.coupon_id');
            if(empty($ids)){
                $ids = [0];
            }
            $where[] = ['id','IN',$ids];
        }
        if (isset($this->params['property_activity_id']) && !empty($this->params['property_activity_id'])) {
            // 筛选已选过的
            $where[] = ['id','>' ,0];//100000
        }
        return $where;
    }
    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/07/18 10:11
     */
    public function lists(): array
    {
        $data =  CouponRules::with(['couponWithCategory'=>function(Query $query){
            $query->field('id,name');
        },'couponWithGoods'=>function(Query $query){
            $query->field('id,goods_name');
        }])->where($this->searchWhere)
            ->where($this->queryWhere())
            ->limit($this->limitOffset, $this->limitLength)
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
        foreach($data as $k => $v){
            $v['goods_category_ids'] = array_column($v['couponWithCategory'],'id');
            $v['goods'] = $v['couponWithGoods'];
            $v['goods_id'] = array_column($v['couponWithGoods'],'id');
            $data[$k] = $v;
        }
        return $data;
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/07/18 10:11
     */
    public function count(): int
    {
        return CouponRules::where($this->searchWhere)->where($this->queryWhere())->count();
    }

}