<?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\FarmPlotRunning;
use app\model\Member;
use app\model\MemberInfo;
use app\model\SysDept;
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;
use function _PHPStan_cc8d35ffb\RingCentral\Psr7\str;

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

    /**
     * @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_running_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([
            'plot' => function ($query) {
                $query->select('farm_plot_id', 'farm_plot_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, '');
            $item['farm_plot_id'] = $item['plot']['farm_plot_id'] ?? '';
            $item['farm_plot_name'] = $item['plot']['farm_plot_name'] ?? '';
        }

        return $items;
    }

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

        $farmPlotRunning = FarmPlotRunning::with([
            'plot' => function ($query) {
                $query->select('farm_plot_id', 'farm_plot_name', 'farm_plot_cover', 'join_farm_plot_dept_id', 'farm_plot_amount', 'farm_plot_cover', 'farm_plot_status', 'farm_plot_used_datetime', 'farm_plot_addtimes');
            },
            'memberInfo' => function ($query) {
                $query->select('join_info_member_id', 'member_info_nickname', 'member_info_headimg');
            }
        ])->where('farm_plot_running_id', $plotRunningId)
            ->select('farm_plot_running_id', 'join_running_farm_plot_id', 'join_farm_plot_running_member_id', 'farm_plot_running_json', 'farm_plot_running_process_json')
            ->first();
        if (!empty($farmPlotRunning->join_farm_plot_member_id)) {
            $member = Member::with([
                'role' => function ($query) {
                    $query->select('member_role_id', 'member_role_name');
                }
            ])->where('member_id', $farmPlotRunning->join_farm_plot_member_id)
                ->select('member_id', 'join_member_role_id')
                ->first();
            $farmPlotRunning->role_name = $member->role->member_role_name ?? '';
        }
        if (!empty($farmPlotRunning['plot']['join_farm_plot_dept_id'])) {
            $farmPlotRunning->dept_name = SysDept::where('dept_id', $farmPlotRunning['plot']['join_farm_plot_dept_id'])->value('dept_name');
        }
        if (!empty($farmPlotRunning['plot']['farm_plot_cover'])) {
            $farmPlotRunning->farm_plot_cover = getenv('STORAGE_DOMAIN') . $farmPlotRunning['plot']['farm_plot_cover'];
        }

//        $farmPlotRunning['member_info']['member_info_headimg'] = MemberService::getAvatarUrl($farmPlotRunning['member_info']['member_info_headimg'] ?? '');

        $harvestData = [];
        $processData = [];
        if (!empty($farmPlotRunning->farm_plot_running_json)) {
            $farmPlotRunningJson = json_decode($farmPlotRunning->farm_plot_running_json, true);
            if (isset($farmPlotRunningJson['harvest'])) {
                $harvest = $farmPlotRunningJson['harvest'];
                foreach ($harvest as &$item) {
                    $harvestData[] = [
                        'url' => getenv('STORAGE_DOMAIN') . $item['media'][0]['url'],
                        'plant' => $item['plant'],
                        'status' => $item['status'],
                        'weight' => $item['weight'],
                        'datetime' => $item['datetime']
                    ];
                }
            }
        }
        if (!empty($farmPlotRunning->farm_plot_running_process_json)) {
            $farmPlotRunningJson = json_decode($farmPlotRunning->farm_plot_running_process_json, true);
            if (isset($farmPlotRunningJson['process'])) {
                $process = $farmPlotRunningJson['process'];
                foreach ($process as &$item) {
                    $processData[] = [
                        'url' => !empty($item['media'][0]) ? getenv('STORAGE_DOMAIN') . $item['media'][0]['url'] : '',
                        'content' => $item['content'],
                        'datetime' => $item['datetime']
                    ];
                }
            }
        }

        $farmPlotRunning->harvest = $harvestData;
        $farmPlotRunning->process = $processData;

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

    /**
     * 添加
     * @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);
            $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);
            $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');
    }

    /**
     * @Desc 菜园维护
     * @Author Gorden
     * @Date 2024/10/17 13:14
     *
     * @param Request $request
     * @return Response
     */
    public function addProcess(Request $request)
    {
        $runningId = $request->post('farm_plot_running_id');
        if (!$runningId) {
            return json_fail("参数异常");
        }

        $running = FarmPlotRunning::where('farm_plot_running_id', $runningId)->first();
        $processJson = [];
        if (!empty($running->farm_plot_running_process_json)) {
            $processJson = json_decode($running->farm_plot_running_process_json, true);
        }

        try {
            $processJson['process'][] = [
                'media' => [[
                    'type' => 'image',
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $request->post('url', '')),
                ]],
                'content' => $request->post('content', ''),
                'datetime' => date('Y-m-d H:i:s')
            ];

            $running->farm_plot_running_process_json = json_encode($processJson);
            $running->save();

            return json_success("success");
        } catch (\Exception $e) {
            return json_fail("维护操作失败");
        }
    }


    /**
     * @Desc 菜园维护
     * @Author Gorden
     * @Date 2024/10/17 13:14
     *
     * @param Request $request
     * @return Response
     */
    public function addHarvest(Request $request)
    {
        $runningId = $request->post('farm_plot_running_id');
        if (!$runningId) {
            return json_fail("参数异常");
        }

        $running = FarmPlotRunning::where('farm_plot_running_id', $runningId)->first();
        $runningJson = [];
        if (!empty($running->farm_plot_running_json)) {
            $runningJson = json_decode($running->farm_plot_running_json, true);
        }

        try {
            $runningJson['harvest'][] = [
                'media' => [[
                    'type' => 'image',
                    'url' => str_replace(getenv('STORAGE_DOMAIN'), '', $request->post('url', '')),
                ]],
                'plant' => $request->post('plant', ''),
                'status' => $request->post('status', ''),
                'weight' => $request->post('weight', ''),
                'datetime' => date('Y-m-d H:i:s')
            ];

            $running->farm_plot_running_json = json_encode($runningJson);
            $running->save();

            return json_success("success");
        } catch (\Exception $e) {
            return json_fail("维护操作失败");
        }
    }
}