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


use app\common\logic\TableDataLogic;
use app\common\model\auth\Admin;
use app\common\model\jobs_rules\JobsRules;
use app\common\logic\BaseLogic;
use think\facade\Db;


/**
 * JobsRules逻辑
 * Class JobsRulesLogic
 * @package app\adminapi\logic
 */
class JobsRulesLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/12/31 13:50
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            JobsRules::create([
                'rule_name' => $params['rule_name'],
                'code' => generateRandomString(8,2),
                'rule_term' => $params['rule_term'],
                //'rule_value' => $params['rule_value'],
                'remark' => $params['remark'],
            ]);
            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/31 13:50
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            JobsRules::where('id', $params['id'])->update([
                'rule_name' => $params['rule_name'],
                'rule_term' => $params['rule_term'],
                //'rule_value' => $params['rule_value'],
                'remark' => $params['remark'],
            ]);

            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/31 13:50
     */
    public static function delete(array $params): bool
    {
        return JobsRules::destroy($params['id']);
    }


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

    /**
     * @notes 获取规则数据
     * @param $params
     * @return array
     * @date 2024/12/31 13:50
     */
    public static function ruleData($params)
    {
        $result = [];
        /*1	省
        2	市
        3	销售组
        4	后台管理员
        5	代理人
        6	销售*/
        $province_ids = array_column($params['rules_data'], 'rule_value', 'rule_id');
        $province_ids = $province_ids[1]??[];
        switch ($params['id']) {
            case 1:
                $result = TableDataLogic::provinces();
                // 数组的开始位置添加一个数组
                array_unshift($result, [
                    "id" => 'self',
                    "name" => "管理员所属",
                    "value" => "self",
                    "type_value" => "data_table_provinces",
                ]);
                break;
            case 2:
                $result = TableDataLogic::citys($province_ids);
                // 数组的开始位置添加一个数组
                array_unshift($result, [
                    "id" => 'self',
                    "name" => "管理员所属",
                    "value" => "self",
                    "type_value" => "data_table_citys",
                ]);
                break;
            case 3:
                $result = TableDataLogic::saleGroup();
                break;
            case 4:
                $result = TableDataLogic::admins();
                // 数组的开始位置添加一个数组
                array_unshift($result, [
                    "id" => 'self',
                    "name" => "管理员所属",
                    "value" => "self",
                    "type_value" => "data_table_admins",
                ]);
                break;
            case 5:
                $result = TableDataLogic::propertyHead();
                break;
            case 6:
                $result = TableDataLogic::sale();
                break;
        }
        //provinces citys saleGroup admins propertyHead sale
        return $result?:[];
    }

    /**
     * 替换规则中的self为管理员所属的值
     * @param $adminId
     * @param $rules
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function ruleSelfValue($adminId,$rules)
    {
        $admin = Admin::where('id', $adminId)->where('root','=',0)->findOrEmpty();
        if($admin->isEmpty()){
            return [];
        }
        $admin = $admin->toArray();
        function replace_value($rule,$replace_value) {
            array_walk($rule,function (&$value,$key) use($replace_value) {
                if ($value == 'self'){
                    $value = $replace_value;
                }
            });
            return $rule;
        }
        //[1=>[,,,,,],2=>[,,,,,]]
        //provinces citys saleGroup admins propertyHead sale
        foreach ($rules as $key => &$rule) {
            switch ($key) {
                case 1:
                    $rule = replace_value($rule,$admin['province']);
                    break;
                case 2:
                    $rule = replace_value($rule,$admin['city']);
                    break;
                case 4:
                    $rule = replace_value($rule,$admin['id']);
                    break;

                case 3:
                case 5:
                case 6:
                    break;
            }
        }
        return $rules?:[];
    }



}