<?php

namespace app\admin\controller\client;

use app\controller\Curd;
use app\model\ClientMessage;
use app\model\Member;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class MessageController extends Curd
{
    public function __construct()
    {
        $this->model = new ClientMessage();
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'client_message_addtimes';
        $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(['member', 'cert','info']);
        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;
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item['client_message_body_json'])) {
                $bodyJson = json_decode($item['client_message_body_json'], true);
                if (isset($bodyJson['content'])) {
                    $item['client_message_body_json'] = $bodyJson['content'];
                }
            }
        }

        return $items;
    }

    public function insert(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        try {
            $params = $request->post();
            $memberIds = $params['join_client_message_recv_member_id'];
            foreach ($memberIds as $memberId){
                $params['join_client_message_send'] = 'SYSTEM';
                $params['join_client_message_recv_member_id'] = $memberId;
                $data = $this->insertInput($params);
                $this->doInsert($data);
            }
        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据写入失败11');
        }
        return json_success('success');
    }

    protected function insertInput($params): array
    {
        $data = $this->inputFilter($params);
        $title = self::$classify[$data['client_message_classify']] ?? '';
        $data['client_message_header_json'] = json_encode(['title'=>$title]);

        if (!empty($data['client_message_sendtime'])) {
            $data['client_message_sendtime'] = date('Y-m-d H:i:s', strtotime($data['client_message_sendtime']));
        }
        if (!empty($data['client_message_header_json']) && !is_json($data['client_message_header_json'])) {
            $data['client_message_header_json'] = json_encode(['header' => $data['client_message_header_json']]);
        }
        if (!empty($data['client_message_body_json']) && !is_json($data['client_message_body_json'])) {
            $data['client_message_body_json'] = json_encode(['content' => $data['client_message_body_json']]);
        }
        return $data;
    }

    /**
     * 群发
     */
    public function groupInsert(Request $request)
    {
        try {
            $params = $request->post();
            $memberIds = Member::where('member_status','ACTIVED')->pluck('member_id');
            foreach ($memberIds as $memberId){
                $params['join_client_message_send'] = 'SYSTEM';
                $params['join_client_message_recv_member_id'] = $memberId;
                $data = $this->insertInput($params);
                $this->doInsert($data);
            }
        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据写入失败11');
        }
        return json_success('success');
    }

    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);
        }
        $headerJson = [];
        if(!empty($model->client_message_header_json)){
            $headerJson = json_decode($model->client_message_header_json,true);
        }
        $headerJson['title'] = self::$classify[$data['client_message_classify']] ?? '';
        $data['client_message_header_json'] = json_encode($headerJson);

        if(!empty($params['header_title'])){
            $headerJson['title'] = $params['header_title'];
            $data['client_message_header_json'] = json_encode($headerJson);
        }
        if (!empty($data['client_message_datetimes'])) {
            $data['client_message_sendtime'] = date('Y-m-d H:i:s', strtotime($data['client_message_sendtime']));
        }
        if (!empty($data['client_message_header_json']) && !is_json($data['client_message_header_json'])) {
            $data['client_message_header_json'] = json_encode(['header' => $data['client_message_header_json']]);
        }
        if (!empty($data['client_message_body_json']) && !is_json($data['client_message_body_json'])) {
            $data['client_message_body_json'] = json_encode(['content' => $data['client_message_body_json']]);
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }

    public static $classify = [
        'WARNING' => '预警消息',
        'REMIND' => '提醒消息',
        'NOTICE' =>'系统通知',
        'APPOINTMENT'=>'预约(服务)消息',
        'ORDER'=>'订单消息',
        'CHAT'=>'未读消息'
    ];
}