<?php

namespace app\admin\controller\asset;

use app\admin\validate\asset\HouseTypeValidate;
use app\controller\Curd;
use app\model\Content;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

class HouseTypeController extends Curd
{
    public function __construct()
    {
        $this->model = new Content();
//        $this->validate = true;
//        $this->validateClass = new HouseTypeValidate();
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['content_category'] = 'HOUSE';
        $order = $request->get('order', 'desc');
        $field = $field ?? 'content_sort';
        $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' => function ($query) {
                $query->select('category_id', 'category_name');
            },
            'user'
        ]);
        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)
    {
        $specs = self::$specs;
        foreach ($items as &$item) {
            $configJson = json_decode($item->content_config_json, true);
            if (isset($configJson['img'])){
                $configJson['img'] = getenv("STORAGE_DOMAIN").$configJson['img'][0];
            }
            if (isset($configJson['cover'])){
                $configJson['cover'] = getenv("STORAGE_DOMAIN").$configJson['cover'][0];
            }
            if (isset($configJson['specs'])){
                $newSpecs = [];
                foreach ($configJson['specs'] as $key => $value) {
                    if (in_array($key, $specs)) {
                        $key = array_search($key, $specs);
                        $newSpecs[$key] = $value;
                    }
                }
                if (!empty($newSpecs)) {
                    $configJson['specs'] = $newSpecs;
                    $item->content_config_json = $configJson;
                }
            }
        }

        return $items;
    }

    /**
     * @Desc 提交数据处理
     * @Author Gorden
     * @Date 2024/3/6 9:11
     *
     * @param Request $request
     * @return array
     * @throws \support\exception\BusinessException
     */
    protected function insertInput(Request $request): array
    {
        $params = $request->post();
        $params['content_config_json'] = json_encode($params['content_config_json']);
        $data = $this->inputFilter($params);
        $data['content_config_json'] = json_decode($data['content_config_json'], true);
        if (!empty($data['content_config_json']['cover'])) {
            $data['content_config_json']['cover'] = [str_replace(getenv("STORAGE_DOMAIN"), '', $data['content_config_json']['cover'])];
        }
        if (!empty($data['content_config_json']['img'])) {
            $data['content_config_json']['img'] = [str_replace(getenv("STORAGE_DOMAIN"), '', $data['content_config_json']['img'])];
        }
        $specs = [];
        foreach ($data['content_config_json']['specs'] as $key => $item) {
            $specs[self::$specs[$key]] = $item;
        }
        $data['content_config_json']['specs'] = $specs;

        $data['creator_user_id'] = JwtToken::getCurrentId();

        $data['content_config_json'] = json_encode($data['content_config_json']);

        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $params = $request->post();
        $params['content_config_json'] = json_encode($params['content_config_json']);

        $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);
        }

        $data['content_config_json'] = json_decode($data['content_config_json'], true);
        if (!empty($data['content_config_json']['cover'])) {
            $data['content_config_json']['cover'] = [str_replace(getenv("STORAGE_DOMAIN"), '', $data['content_config_json']['cover'])];
        }
        if (!empty($data['content_config_json']['img'])) {
            $data['content_config_json']['img'] = [str_replace(getenv("STORAGE_DOMAIN"), '', $data['content_config_json']['img'])];
        }
        $specs = [];
        foreach ($data['content_config_json']['specs'] as $key => $item) {
            $specs[self::$specs[$key]] = $item;
        }
        $data['content_config_json']['specs'] = $specs;

        $data['content_config_json'] = json_encode($data['content_config_json']);

        $data['content_updatetimes'] = time();

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

    public static $specs = [
        'bianhao' => "编号",
        'cengshu' => '层数',
        'chanquan' => '产权',
        'chaoxiang' => '朝向',
        'jiaofang' => '交房',
        'mianji' => '面积',
        'xingzhi' => '性质',
        'zhuangxiu' => '装修'
    ];
}