<?php

namespace app\admin\controller\life;

use app\admin\service\member\MemberService;
use app\admin\validate\life\FarmLandValidate;
use app\controller\Curd;
use app\model\FarmPlot;
use app\model\Member;
use app\model\MemberInfo;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use support\exception\BusinessException;
use support\Model;
use support\Request;
use support\Response;

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

    /**
     * @Desc 列表
     * @Author Gorden
     * @Date 2024/2/27 14:46
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'farm_plot_addtimes';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 指定查询where条件,并没有真正的查询数据库操作
     * @param array $where
     * @param string|null $field
     * @param string $order
     * @return EloquentBuilder|QueryBuilder|Model
     */
    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'dept' => function ($query) {
                $query->select('dept_id', 'dept_name');
            },
            'user' => function ($query) {
                $query->select('user_id', 'user_name');
            },
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile', 'member_is_owner', 'member_is_vip', 'member_is_partner', 'member_is_referrer');
            },
            'memberCert' => 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;
    }

    /**
     * @Desc 查询后数据处理
     * @Author Gorden
     * @Date 2024/3/22 10:56
     *
     * @param $items
     * @return mixed
     */
    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item['farm_plot_cover'])) {
                $item['farm_plot_cover'] = getenv('STORAGE_DOMAIN') . $item['farm_plot_cover'];
            }
            $mobile = $item['member']['member_mobile'] ?? '';
            $certName = $item['memberCert']['member_cert_name'] ?? '';

            $item['member_name'] = MemberService::getMemberCertName($mobile, $certName, '');
        }

        return $items;
    }

    public function info(Request $request): Response
    {
        $plotId = $request->get('plot_id');
        if (!$plotId) {
            return json_fail("参数异常");
        }

        $farmPlot = FarmPlot::with([
            'memberInfo' => function ($query) {
                $query->select('join_info_member_id', 'member_info_nickname', 'member_info_headimg');
            }
        ])->where('farm_plot_id', $plotId)
            ->select('farm_plot_id', 'join_farm_plot_member_id')
            ->first();
        if (!empty($farmPlot->join_farm_plot_member_id)) {
            $member = Member::with([
                'role' => function ($query) {
                    $query->select('member_role_id', 'member_role_name');
                }
            ])->where('member_id', $farmPlot->join_farm_plot_member_id)
                ->select('member_id', 'join_member_role_id')
                ->first();
            $farmPlot->role_name = $member->role->member_role_name ?? '';
        }

//        $farmPlot['memberInfo']['member_info_headimg'] = MemberService::getAvatarUrl($farmPlot['memberInfo']['member_info_headimg'] ?? '');

        return json_success('success', $farmPlot);
    }

    /**
     * 添加
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        try {
            $data = $this->insertInput($request);
            $data['farm_plot_id'] = 'FP' . date('ymdHi') . random_string(4, 'up');
            $data['farm_plot_cover'] = str_replace(getenv('STORAGE_DOMAIN'), '', $data['farm_plot_cover']);
            $this->doInsert($data);
        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据写入失败');
        }
        return json_success('success');
    }


    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('update')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        try {
            [$id, $data] = $this->updateInput($request);
            $data['farm_plot_cover'] = str_replace(getenv('STORAGE_DOMAIN'), '', $data['farm_plot_cover']);
            $this->doUpdate($id, $data);
        } catch (BusinessException $e) {
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据更新失败');
        }

        return json_success('success');
    }
}