<?php

namespace app\admin\controller\member;

use app\admin\validate\member\RoleValidate;
use app\controller\Curd;
use app\model\MemberRole;
use app\model\RuleAdded;
use app\model\RulePricing;
use app\model\SysSerial;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class RoleController extends Curd
{
    public function __construct()
    {
        $this->model = new MemberRole();
        $this->validate = true;
        $this->validateClass = new RoleValidate();
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'member_role_addtimes';
        $where['member_role_status'] = 'ACTIVED';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'category',
            'rulePricing'
        ]);
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    protected function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item->member_role_rule_json)) {
                $ruleJson = json_decode($item->member_role_rule_json, true);
                if (!empty($ruleJson['pricing'])) {
                    $item->join_member_role_rule_pricing_id = $ruleJson['pricing'];
                    $item->pricingName = RulePricing::where('rule_pricing_id', $ruleJson['pricing'])->value('rule_pricing_name');
                }
                if (!empty($ruleJson['added'])) {
                    $item->join_member_role_added_id = $ruleJson['added'];
                    $item->addedName = RuleAdded::where('rule_added_id', $ruleJson['added'])->value('rule_added_name');
                }
            }
        }

        return $items;
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $data['member_role_id'] = "MR" . date('ymdHi') . random_string(4, 'up');

        $data['member_role_rule_json'] = json_encode([
            'pricing' => $request->post('join_member_role_rule_pricing_id',''),
            'added' => $request->post('join_member_role_added_id',''),
        ]);
        return $data;
    }


    protected function updateInput(Request $request): array
    {
        $params = $request->post();

        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($params);
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }

        if (!empty($model->member_role_rule_json)) {
            $ruleJson = json_decode($model->member_role_rule_json, true);
            if (!empty($params['join_member_role_rule_pricing_id'])) {
                $ruleJson['pricing'] = $params['join_member_role_rule_pricing_id'];
            }else{
                $ruleJson['pricing'] = '';
            }
            if (!empty($params['join_member_role_added_id'])) {
                $ruleJson['added'] = $params['join_member_role_added_id'];
            }else{
                $ruleJson['added'] = '';
            }
            $data['member_role_rule_json'] = json_encode($ruleJson);
        } else {
            $data['member_role_rule_json'] = json_encode([
                'pricing' => $params['join_member_role_rule_pricing_id'] ?? '',
                'added' => $params['join_member_role_added_id'] ?? ''
            ]);
        }

        unset($data[$primary_key]);
        return [$id, $data];
    }

    public function selectList()
    {
        $roles = MemberRole::select('member_role_id','member_role_name')
            ->where('member_role_category','COMBINE')
            ->orderBy('member_role_sort','desc')
            ->get();
        return json_success('',$roles);
    }

}