<?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\effective;


use app\common\model\effective\EffectiveCategory;
use app\common\model\effective\EffectiveRules;
use app\common\logic\BaseLogic;
use think\facade\Db;


/**
 * EffectiveRules逻辑
 * Class EffectiveRulesLogic
 * @package app\adminapi\logic\effective
 */
class EffectiveRulesLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/17 11:49
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            $effectiveRules = EffectiveRules::create([
                'effective_num' => $params['effective_num'],
                'effective_unit' => $params['effective_unit'],
                'remark' => $params['remark'],
            ]);
            if(!empty($params['goods_category_ids'])){
                $effectiveCategoryArr = [];
                $ruleId = $effectiveRules->id;
                foreach($params['goods_category_ids'] as $v){
                    $effectiveCategoryArr[] = end($v);
                }
                $categoryIds = EffectiveCategory::where([['goods_category_id','in',$effectiveCategoryArr],['effective_id','<>',$ruleId]])->column('goods_category_id');
                if(!empty($categoryIds)){
                    throw new \Exception('存在已分配的分类:'.implode(',',$categoryIds));
                }
                $effectiveRules->effectiveWithCategory()->saveAll($effectiveCategoryArr);
            }
            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/17 11:49
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            EffectiveRules::where('id', $params['id'])->update([
                'effective_num' => $params['effective_num'],
                'effective_unit' => $params['effective_unit'],
                'remark' => $params['remark'],
            ]);
            EffectiveCategory::where('effective_id',$params['id'])->delete();
            $effectiveCategoryArr = [];
            if(!empty($params['goods_category_ids'])){
                foreach($params['goods_category_ids'] as $v){
                    if(!is_array($v)){
                        $effectiveCategoryArr[] = $v;
                        continue;
                    }
                    $effectiveCategoryArr[] = end($v);
                }
                $categoryIds = EffectiveCategory::where([['goods_category_id','in',$effectiveCategoryArr],['effective_id','<>', $params['id']]])->column('goods_category_id');
                if(!empty($categoryIds)){
                    throw new \Exception('存在已分配的分类：'.implode(',',$categoryIds));
                }
                $effectiveRules = EffectiveRules::find($params['id']);
                $effectiveRules->effectiveWithCategory()->saveAll($effectiveCategoryArr);
            }
            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/17 11:49
     */
    public static function delete(array $params): bool
    {
        EffectiveCategory::where('effective_id',$params['id'])->delete();
        return EffectiveRules::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/17 11:49
     */
    public static function detail($params): array
    {

       $rules = EffectiveRules::findOrEmpty($params['id'])->toArray();
       if(!empty($rules)){
           $rules['goods_category_ids'] =  EffectiveCategory::where('effective_id',$params['id'])->column('goods_category_id');
       }
       return $rules;
    }
}