<?php

namespace app\admin\controller\member;

use app\admin\validate\life\CinemaIlkValidate;
use app\admin\validate\member\WellnessRecordValidate;
use app\controller\Curd;
use app\model\CinemaIlk as CinemaIlkModel;
use app\model\WellnessRecord;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class CheckupController extends Curd
{

    public function __construct()
    {
        $this->model = new WellnessRecord();
        $this->validate = true;
        $this->validateClass = new WellnessRecordValidate();
    }

    /**
     * @Desc 查询列表
     * @Author Gorden
     * @Date 2024/3/21 9:58
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $field = $field ?? 'wellness_record_addtimes';
        $order = $request->get('order', 'desc');
        $where['wellness_record_category'] = 'Examine';
        $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' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            }
        ]);
        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->wellness_record_file_json)) {
                $item->wellness_record_file_json = json_decode($item->wellness_record_file_json, true);
                $wellnessRecordFileJson = [];
                foreach ($item->wellness_record_file_json as $value) {
                    if (empty($value['url']) || empty($value['name'])){
                        continue;
                    }
                    $wellnessRecordFileJson[] = [
                        'url' => getenv('STORAGE_DOMAIN') . $value['url'],
                        'name' => $value['name']
                    ];
                }
                $item->wellness_record_file_json = $wellnessRecordFileJson;
            }
        }

        return $items;
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $data['wellness_record_datetime'] = date('Y-m-d H:i:s', strtotime($data['wellness_record_datetime']));
        if (!empty($data['wellness_record_file_json'])) {
            $data['wellness_record_file_json'] = json_decode($data['wellness_record_file_json'], true);
            $wellnessRecordFileJson = [];
            foreach ($data['wellness_record_file_json'] as $value) {
                $wellnessRecordFileJson[] = [
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $value['url']),
                    'name' => $value['name']
                ];
            }
            $data['wellness_record_file_json'] = json_encode($wellnessRecordFileJson);
        } else {
            $data['wellness_record_file_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['wellness_record_datetime'] = date('Y-m-d H:i:s', strtotime($data['wellness_record_datetime']));
        if (!empty($data['wellness_record_file_json'])) {
            $data['wellness_record_file_json'] = json_decode($data['wellness_record_file_json'], true);
            $wellnessRecordFileJson = [];
            foreach ($data['wellness_record_file_json'] as $value) {
                $wellnessRecordFileJson[] = [
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $value['url']),
                    'name' => $value['name']
                ];
            }
            $data['wellness_record_file_json'] = $wellnessRecordFileJson;
        }
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }
}