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


use app\common\model\goods\Goods;
use app\common\logic\BaseLogic;
use app\common\model\goods_category\GoodsCategory;
use app\common\model\performance\PerformanceRules;
use think\Exception;
use think\facade\Db;


/**
 * Goods逻辑
 * Class GoodsLogic
 * @package app\adminapi\logic\goods
 */
class GoodsLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/07 18:37
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            if((!$params['type'] || !$params['rate']) && $params['goods_status']==1){
                throw new Exception('商品规格的绩效未配置，不允许上架');
            }

            $params['goods_category_id'] = end($params['goods_category_ids']);
            if ($params['is_type'] == 1) {
                $params['is_agent'] = 1;
                $params['is_activity'] = 0;
            } else if ($params['is_type'] == 2) {
                $params['is_agent'] = 0;
                $params['is_activity'] = 1;
            } else {
                $params['is_agent'] = 0;
                $params['is_activity'] = 0;
            }
            $goods = Goods::create([
                'goods_category_ids' => $params['goods_category_ids'],
                'category_type' => GoodsCategory::where('id',$params['goods_category_id'])->value('category_type'),
                'goods_category_id' => $params['goods_category_id'],
                'goods_name' => $params['goods_name'],
                'goods_image' => $params['goods_image'],
                'goods_video' => $params['goods_video'],
                'goods_banners' => $params['goods_banners'],
                'goods_number' => $params['goods_number'],
                'good_unit' => $params['good_unit'],
                'goods_size' => $params['goods_size'],
                'goods_type' => $params['goods_type'],
                'goods_brand' => $params['goods_brand'],
                'install_guide' => $params['install_guide'],
                'goods_payment_type'=>$params['goods_payment_type'],
                'base_service_fee' => $params['base_service_fee'],
                'service_total' => $params['service_total'],
                'service_fee' => $params['service_fee'],
                'service_image' => $params['service_image'],
                'warranty_period'=>$params['warranty_period'],
                'fee_schedule' => $params['fee_schedule'],
                'goods_status' => 0,
                'is_recommend' => $params['is_recommend'] ?:0,
                'recommend_weight' => $params['recommend_weight'] ?:0,
                'is_top' => $params['is_top'] ?:0,
                'top_weight' => $params['top_weight'] ?:0,
                'is_hot' => $params['is_hot'] ?:0,
                'hot_weight' => $params['hot_weight'] ?:0,
                'is_agent' => $params['is_agent'] ?:0,
                'is_activity' => $params['is_activity'] ??0,
                'property_activity_id' => $params['property_activity_id'] ??0,
                'labels' => (isset($params['labels']) && $params['labels'])?implode(',',$params['labels']):'',
                'activity_service_fee' => $params['activity_service_fee'] ??'',
            ]);

            //更新绩效规则
            if(in_array($params['type'],[0,1,2])){
                // 0-1
                if($params['rate']>1){
                    throw new Exception('商品绩效比率不能大于1');
                }
            }
            if(in_array($params['type'],[3])){
                // ≥1
                if($params['rate']<1){
                    throw new Exception('金额不能小于1');
                }
            }
            $rule = PerformanceRules::where(['goods_id'=>$goods->id])->findOrEmpty();
            if(!$rule->isEmpty()){
                $rule->type = $params['type'];
                $rule->rate = $params['rate'];
            }else{
                $rule = new PerformanceRules();
                $rule->goods_id = $goods->id;
                $rule->type = $params['type'];
                $rule->rate = $params['rate'];
            }
            $rule->save();

            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/07 18:37
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {

            if((!$params['type'] || !$params['rate']) && $params['goods_status']==1){
                throw new Exception('商品规格的绩效未配置，不允许上架');
            }

            $params['goods_category_id'] = end($params['goods_category_ids']);
            if ($params['is_type'] == 1) {
                $params['is_agent'] = 1;
                $params['is_activity'] = 0;
            } else if ($params['is_type'] == 2) {
                $params['is_agent'] = 0;
                $params['is_activity'] = 1;
            } else {
                $params['is_agent'] = 0;
                $params['is_activity'] = 0;
            }
            Goods::where('id', $params['id'])->update([
                'category_type' => GoodsCategory::where('id',$params['goods_category_id'])->value('category_type'),
                'goods_category_ids' => json_encode($params['goods_category_ids'],true),
                'goods_category_id' => $params['goods_category_id'],
                'goods_name' => $params['goods_name'],
                'goods_image' => $params['goods_image'],
                'goods_video' => $params['goods_video'],
                'goods_banners' => !empty($params['goods_banners']) ? json_encode($params['goods_banners'],true) : null,
                'goods_number' => $params['goods_number'],
                'good_unit' => $params['good_unit'],
                'goods_size' => $params['goods_size'],
                'goods_type' => $params['goods_type'],
                'goods_brand' => $params['goods_brand'],
                'install_guide' => $params['install_guide'],
                'goods_payment_type'=>$params['goods_payment_type'],
                'base_service_fee' => $params['base_service_fee'],
                'service_total' => $params['service_total'],
                'service_fee' => $params['service_fee'],
                'service_image' => $params['service_image'],
                'warranty_period'=>$params['warranty_period'],
                'fee_schedule' => $params['fee_schedule'],
                'goods_status' => $params['goods_status'],
                'is_recommend' => $params['is_recommend'] ?:0,
                'recommend_weight' => $params['recommend_weight'] ?:0,
                'is_top' => $params['is_top'] ?:0,
                'top_weight' => $params['top_weight'] ?:0,
                'is_hot' => $params['is_hot'] ?:0,
                'hot_weight' => $params['hot_weight'] ?:0,
                'is_agent' => $params['is_agent'] ?:0,
                'is_activity' => $params['is_activity'] ??0,
                'property_activity_id' => $params['property_activity_id'] ??0,
                'labels' => (isset($params['labels']) && $params['labels'])?implode(',',$params['labels']):'',
                'activity_service_fee' => $params['activity_service_fee'] ??'',
            ]);

            //更新绩效规则
            if(in_array($params['type'],[0,1,2])){
                // 0-1
                if($params['rate']>1){
                    throw new Exception('商品绩效比率不能大于1');
                }
            }
            if(in_array($params['type'],[3])){
                // ≥1
                if($params['rate']<1){
                    throw new Exception('金额不能小于1');
                }
            }
            $rule = PerformanceRules::where(['goods_id'=>$params['id']])->findOrEmpty();
            if(!$rule->isEmpty()){
                $rule->type = $params['type'];
                $rule->rate = $params['rate'];
            }else{
                $rule = new PerformanceRules();
                $rule->goods_id = $params['id'];
                $rule->type = $params['type'];
                $rule->rate = $params['rate'];
            }
            $rule->save();

            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/07 18:37
     */
    public static function delete(array $params): bool
    {
        return Goods::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     */
    public static function detail($params): array
    {
        return Goods::with('performanceRules')->append(['is_type'])->findOrEmpty($params['id'])->toArray();
    }
    /**
     * @notes 批量规则配置
     * @param $params
     * @return array
     */
    public static function rulesBatch($params): bool
    {
        Db::startTrans();
        try {
            if(in_array($params['type'],[0,1,2])){
                // 0-1
                if($params['rate']>1){
                    throw new Exception('商品绩效比率不能大于1');
                }
            }
            if(in_array($params['type'],[3])){
                // ≥1
                if($params['rate']<1){
                    throw new Exception('金额不能小于1');
                }
            }
            foreach ($params['ids'] as $id){
                $rule = null;
                //更新绩效规则
                $rule = PerformanceRules::where(['goods_id'=>$id])->findOrEmpty();
                if(!$rule->isEmpty()){
                    $rule->type = $params['type'];
                    $rule->rate = $params['rate'];
                }else{
                    $rule = new PerformanceRules();
                    $rule->goods_id = $id;
                    $rule->type = $params['type'];
                    $rule->rate = $params['rate'];
                }
                $rule->save();
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


}