<?php

namespace app\admin\controller\member;

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

class RulePricingController extends Curd
{
    public function __construct()
    {
        $this->model = new RulePricing();
        $this->validate = true;
        $this->validateClass = new RulePricingValidate();
    }

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

    public function selectList(Request $request)
    {
        $data = $this->model->where('rule_pricing_status', 'ACTIVED')
            ->select('rule_pricing_id', 'rule_pricing_name')
            ->get()
            ->toArray();

        return json_success('', $data);
    }

    protected function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item->rule_pricing_goods_json)) {
                $goodsJson = json_decode($item->rule_pricing_goods_json, true);
                $item->rule_pricing_goods_json = $goodsJson;
            }
            $item->rulr_priceing_nbr = $item->rulr_priceing_nbr * 100;
        }

        return $items;
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $data['rule_pricing_id'] = "RP" . str_pad(SysSerial::getSerial(), 16, '0', STR_PAD_LEFT) . random_string(6, 'up');
        $data['rulr_priceing_nbr'] = $data['rulr_priceing_nbr'] / 100;
//        if (!empty($data['rule_pricing_goods_json'])) {
//            $data['rule_pricing_goods_json'] = json_encode(explode(',', $data['rule_pricing_goods_json']));
//        } else {
//            $data['rule_pricing_goods_json'] = '[]';
//        }
        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $data['rulr_priceing_nbr'] = $data['rulr_priceing_nbr'] / 100;
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }

}