<?php

namespace app\admin\controller\Home;

use app\BaseController;
use app\common\model\Home\HomeEnv as ModelHomeEnv;
use app\Request;
use think\Validate;
use think\exception\ValidateException;
use think\facade\Filesystem;
use app\common\arw\adjfut\src\Excel;
use app\common\arw\adjfut\src\UploadFile;
use app\common\exception\Tool;
use think\facade\Db;
use think\facade\Env;

class HomeEnv extends BaseController
{
    /**
     * 获取首页环境列表
     */
    public function getHomeEnvList(Request $request): array
    {
        $params = $request->param();
        $con = [];

        $con = Tool::getOptionalQuery();

        $query = ModelHomeEnv::where($con)
            ->field([
                'home_env_id',
                'home_env_guid',
                'home_env_img',
                'home_env_sort'
            ])
            ->order('home_env_sort', 'asc');

        return msg("获取首页环境列表成功!", $query);
    }

    /**
     * 编辑首页环境
     */
    public function editHomeEnv(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'home_env_img|图片' => 'require',
            'home_env_sort|排序' => 'require'
        ]);
        $model = ModelHomeEnv::where('home_env_guid', $params['home_env_guid'])->find();
        if (!$model) throwErrorMsg("该首页环境不存在", 1);
        $model->allowField([
            'home_env_update_user_guid',
            'home_env_img',
            'home_env_sort'
        ])->save($params);
        return msg('编辑成功!');
    }

    /**
     * 添加首页环境
     */
    public function addHomeEnv(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'home_env_img|图片' => 'require',
            'home_env_sort|排序' => 'require'
        ]);
        $model = ModelHomeEnv::create($params, [
            'home_env_guid',
            'home_env_create_user_guid',
            'home_env_update_user_guid',
            'home_env_img',
            'home_env_sort'
        ]);
        return msg('添加成功!');
    }

    /**
     * 删除首页环境
     */
    public function deleteHomeEnv(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'home_env_guid' => 'require',
        ]);
        $home_env = ModelHomeEnv::where([
            'home_env_guid' => explode(',', $params['home_env_guid'])
        ])->select();
        $home_env->delete();
        return msg('删除成功!');
    }

    /**
     * 导出Excel
     */
    public function exportExcel(Request $request)
    {
        $params = $request->param();
        $select = ModelHomeEnv::field([
            'home_env_img',
            'home_env_sort'
        ])
            ->order('home_env_sort', 'asc')
            ->select()->toArray();
        return ModelHomeEnv::exportExcel($select);
    }
}
