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


use app\common\model\master_commission\MasterWorkerCommissionConfig;
use app\common\logic\BaseLogic;
use app\common\model\master_commission\MasterWorkerCommissionRatio;
use think\facade\Db;
use think\facade\Log;


/**
 * MasterWorkerCommissionConfig逻辑
 * Class MasterWorkerCommissionConfigLogic
 * @package app\adminapi\logic
 */
class MasterWorkerCommissionConfigLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/12/06 10:42
     */
    public static function add(array $params): bool
    {
        if(isset($params['block_data'])){
            foreach ($params['block_data'] as &$data) {
                if($data['category_ids']){
                    $ids = [];
                    foreach ($data['category_ids'] as $val){
                        is_array($val)?($ids[] = end($val)):($ids[] = $val);
                    }
                    //$params['category_ids'] = ["goods_category_ids"=>$params['category_ids'],"ids"=>$ids];
                    $data['category_ids'] = implode(',',$ids);
                }
            }
        }
        Db::startTrans();
        try {
            $info = MasterWorkerCommissionConfig::where('master_worker_id',$params['master_worker_id'])->where('voucher_status',3)->findOrEmpty();
            if($info->isEmpty()){
                MasterWorkerCommissionConfig::create([
                    'master_worker_id' => $params['master_worker_id'],
                    'submit_admin_id' => $params['adminId'],
                    'voucher_status' => 3,
                    'notice_rule' => $params['notice_rule'],
                    'block_data' => $params['block_data'],
                ]);
            }else{
                throw new \Exception('存在审核中规则，无法新增');
            }
            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/12/06 10:42
     */
    public static function edit(array $params): bool
    {
        if(isset($params['block_data'])){
            foreach ($params['block_data'] as &$data) {
                if($data['category_ids']){
                    $ids = [];
                    foreach ($data['category_ids'] as $val){
                        is_array($val)?($ids[] = end($val)):($ids[] = $val);
                    }
                    $data['category_ids'] = implode(',',$ids);
                }
            }
        }
        Db::startTrans();
        try {
            $info = MasterWorkerCommissionConfig::where('master_worker_id',$params['master_worker_id'])->where('voucher_status',3)->findOrEmpty();
            if($info->isEmpty()){
                throw new \Exception('不存在待审核规则，无法编辑');
            }else{
                MasterWorkerCommissionConfig::where('id', $params['id'])->update([
                    'master_worker_id' => $params['master_worker_id'],
                    'submit_admin_id' => $params['adminId'],
                    'voucher_status' => $params['voucher_status'],
                    'notice_rule' => $params['notice_rule']?json_encode($params['notice_rule']):0,
                    'block_data' => $params['block_data']?json_encode($params['block_data']):0,
                ]);
            }
            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/12/06 10:42
     */
    public static function delete(array $params): bool
    {
        MasterWorkerCommissionRatio::where('commission_config_id',$params['id'])->delete();
        return MasterWorkerCommissionConfig::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/12/06 10:42
     */
    public static function detail($params): array
    {
        return MasterWorkerCommissionConfig::findOrEmpty($params['id'])->toArray();
    }

    public static function examine($params): bool
    {

        Db::startTrans();
        try {
            $info = MasterWorkerCommissionConfig::where('id',$params['id'])->where('voucher_status',3)->findOrEmpty();
            if($info->isEmpty()){
                throw new \Exception('不存在待审核规则，无法审核');
            }else{
                // 关闭所有旧规则
                MasterWorkerCommissionConfig::where('master_worker_id',$info->master_worker_id)->update(['voucher_status'=>1]);

                // 生成比例数据 [{"block_key":"0","category_ids":"59,54,53,20,36,35,34,33,32,48","ratio":"0.2"},{"block_key":"1","category_ids":"3","ratio":"0.7"}]
                $ratioData = [];
                foreach ($info->block_data as $data){
                    $category_ids = explode(',',$data['category_ids']);
                    foreach ($category_ids as $category_id) {
                        $ratioData[] = [
                            'commission_config_id' => $params['id'],
                            'goods_category_id' => $category_id,
                            'ratio' => $data['ratio'],
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                    }
                }
                Db::name('master_worker_commission_ratio')->insertAll($ratioData);

                // 单数规则数据 day_num: 0, order_num: 0, signing_date
                $noticeData = [];
                foreach ($info->notice_rule as $data){
                    $noticeData[] = [
                        'commission_config_id' => $params['id'],
                        'master_worker_id' => $info->master_worker_id,
                        'day_num' => $data['day_num'],
                        'order_num' => $data['order_num'],
                        'signing_date' => strtotime($data['signing_date']),
                        'signing_date_end' => strtotime($data['signing_date'])+($data['day_num']*86400),
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                }
                Db::name('master_worker_commission_notice')->insertAll($noticeData);

                // 启动
                MasterWorkerCommissionConfig::where('id', $params['id'])->update([
                    'examine_admin_id' => $params['adminId'],
                    'voucher_status' => 2
                ]);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            if (str_contains($e->getMessage(), "key 'category_config_id'")) {
                self::setError('规则中存在重复商品分类,请重新编辑');
            }else{
                self::setError($e->getMessage());
            }
            return false;
        }


    }
    public static function offCommission($params): bool
    {
        Db::startTrans();
        try {
            $info = MasterWorkerCommissionConfig::where('id',$params['id'])->findOrEmpty();
            if($info->isEmpty()){
                throw new \Exception('不存在规则，无法操作');
            }else{
                // 关闭
                MasterWorkerCommissionConfig::where('id',$params['id'])->update(['voucher_status'=>1]);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


}