<?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\logic\coupon;


use app\common\model\coupon\CouponCategory;
use app\common\model\coupon\CouponGoods;
use app\common\model\coupon\CouponRules;
use app\common\logic\BaseLogic;
use app\common\model\goods\Goods;
use think\db\Query;
use think\facade\Db;


/**
 * CouponRules逻辑
 * Class CouponRulesLogic
 * @package app\adminapi\logic\coupon
 */
class CouponRulesLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/18 10:11
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            $model = CouponRules::create([
                'coupon_type'=> $params['coupon_type'],
                'coupon_target'=>!empty($params['coupon_target'])?$params['coupon_target']:'category',
                'code' => generate_sn(CouponRules::class,'code'),
                'amount' => $params['amount'],
                'amount_require' => $params['amount_require'],
                'discount_ratio' => $params['discount_ratio'],
                'event_name' => $params['event_name'],
                'expire_time' =>  $params['expire_time']  ?$params['expire_time']*86400: 0,
                'max_deductible_price' => $params['max_deductible_price'],
                'mold_type' => $params['mold_type'],
                'server_category_name' => $params['server_category_name'],
                'voucher_status' => $params['voucher_status'],
                'voucher_count' => $params['voucher_count'],
                'remaining_count' => $params['voucher_count'],
                'property_activity_id' => $params['property_activity_id']??0,
                'labels' => (isset($params['labels']) && $params['labels'])?implode(',',$params['labels']):'',
            ]);
            if(!empty($params['goods_category_ids'])){
                $categoryArr = [];
                foreach($params['goods_category_ids'] as $v){
                    $categoryArr[] = end($v);
                }
                $model->couponWithCategory()->saveAll($categoryArr);
            }
            if(!empty($params['goods_id'])){
                $goodsArr = [];
                foreach($params['goods_id'] as $v){
                    $goodsArr[] = $v;
                }
                $model->couponWithGoods()->saveAll($goodsArr);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/18 10:11
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            CouponRules::where('id', $params['id'])->update([
                'coupon_type'=> $params['coupon_type'],
                'coupon_target'=>!empty($params['coupon_target'])?$params['coupon_target']:'category',
                'amount' => $params['amount'],
                'amount_require' => $params['amount_require'],
                'discount_ratio' => $params['discount_ratio'],
                'event_name' => $params['event_name'],
                'expire_time' => $params['expire_time']  ?$params['expire_time']*86400: 0,
                'max_deductible_price' => $params['max_deductible_price'],
                'mold_type' => $params['mold_type'],
                'server_category_name' => $params['server_category_name'],
                'voucher_status' => $params['voucher_status'],
                'voucher_count' => $params['voucher_count'],
                'remaining_count' => $params['remaining_count'],
                'property_activity_id' => $params['property_activity_id']??0,
                'labels' => (isset($params['labels']) && $params['labels'])?implode(',',$params['labels']):'',
            ]);
            CouponCategory::where('coupon_id',$params['id'])->delete();
            if(!empty($params['goods_category_ids'])){
                $categoryArr = [];
                foreach($params['goods_category_ids'] as $v){
                    if(!is_array($v)){
                        $categoryArr[] = $v;
                        continue;
                    }
                    $categoryArr[] = end($v);
                }
                $model = CouponRules::find($params['id']);
                $model->couponWithCategory()->saveAll($categoryArr);
            }
            CouponGoods::where('coupon_id',$params['id'])->delete();
            if(!empty($params['goods_id'])){
                $goodsArr = [];
                foreach($params['goods_id'] as $v){
                    $goodsArr[] = $v;
                }
                $model = CouponRules::find($params['id']);
                $model->couponWithGoods()->saveAll($goodsArr);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/18 10:11
     */
    public static function delete(array $params): bool
    {
        CouponCategory::where('coupon_id',$params['id'])->delete();
        return CouponRules::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/18 10:11
     */
    public static function detail($params): array
    {
        $rules = CouponRules::findOrEmpty($params['id'])->toArray();
        if(!empty($rules)){
            $rules['goods_category_ids'] =  CouponCategory::where('coupon_id',$params['id'])->column('goods_category_id');
            $rules['goods'] =  Goods::whereIn('goods_id',CouponGoods::where('coupon_id',$params['id'])->column('goods_id'))->column('*');
        }
        return $rules;
    }
}