<?php

namespace app\admin\controller\client;

use app\admin\service\member\MemberService;
use app\controller\Curd;
use app\model\ClientFavorite;
use app\model\Goods;
use app\model\GoodsEvaluate;
use app\model\Member;
use app\model\MemberRole;
use support\exception\BusinessException;
use support\Request;
use support\Response;

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

    public function select(Request $request): Response
    {
        $goodsName = $request->get('goods_name', '');
        $searchTimes = $request->get('goods_evaluate_addtimes', []);

        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'goods_evaluate_addtimes';

        if ($goodsName != '') {
            $goodsIds = Goods::where('goods_name', 'like', '%' . $goodsName . '%')->pluck('goods_id')->toArray();
            $where['join_evaluate_goods_id'] = ['in', implode(',', $goodsIds)];
        }
        if (!empty($searchTimes)) {
            $searchTimes[0] = !empty($searchTimes[0]) ? strtotime($searchTimes[0]) : time();
            $searchTimes[1] = !empty($searchTimes[1]) ? strtotime($searchTimes[1]) : time();

            $where['goods_evaluate_addtimes'] = $searchTimes;
        }

        $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');
            },
            'good' => function ($query) {
                $query->select('goods_id', 'goods_name');
            },
            '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;
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item->goods_evaluate_json)) {
                $imagesStr = '';
                $goodsEvaluateJson = json_decode($item->goods_evaluate_json, true);
                if (isset($goodsEvaluateJson['photo'])) {
                    foreach ($goodsEvaluateJson['photo'] as $images) {
                        if (isset($images['file'])) {
                            $imagesStr .= getenv('APP_IMAGE_DOMAIN') . $images['file']['file_savepath'] . $images['file']['file_savename'] . ',';
                        }
                    }
                }
                if (isset($goodsEvaluateJson['desc'])) {
                    $item->desc = $goodsEvaluateJson['desc'];
                }
                $item->photos = rtrim($imagesStr, ',');
            }
        }
        return $items;
    }

    /**
     * @Desc 评价管理顶部统计
     * @Author Gorden
     * @Date 2024/11/1 13:41
     *
     * @param Request $request
     * @return Response
     */
    public function statistics(Request $request)
    {
        $total = GoodsEvaluate::count('goods_evaluate_id');
        $pendingTotal = GoodsEvaluate::where('goods_evaluate_status', 'PENDING')->count('goods_evaluate_id');
        $activedTotal = GoodsEvaluate::where('goods_evaluate_status', 'ACTIVED')->count('goods_evaluate_id');
        $disabledTotal = GoodsEvaluate::where('goods_evaluate_status', 'DELETED')->count('goods_evaluate_id');
        $oneScoreTotal = GoodsEvaluate::where('goods_evaluate_value', 1)->count('goods_evaluate_id');
        $twoScoretotal = GoodsEvaluate::where('goods_evaluate_value', 2)->count('goods_evaluate_id');
        $threeScoretotal = GoodsEvaluate::where('goods_evaluate_value', 3)->count('goods_evaluate_id');
        $fourScoretotal = GoodsEvaluate::where('goods_evaluate_value', 4)->count('goods_evaluate_id');
        $fiveScoretotal = GoodsEvaluate::where('goods_evaluate_value', 5)->count('goods_evaluate_id');

        return json_success('success', [
            'total' => $total,
            'pendingTotal' => $pendingTotal,
            'activedTotal' => $activedTotal,
            'disabledTotal' => $disabledTotal,
            'oneScoreTotal' => $oneScoreTotal,
            'twoScoretotal' => $twoScoretotal,
            'threeScoretotal' => $threeScoretotal,
            'fourScoretotal' => $fourScoretotal,
            'fiveScoretotal' => $fiveScoretotal,
        ]);
    }

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

        $evaluate = GoodsEvaluate::with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id', 'member_is_vip', 'member_is_partner', 'member_is_referrer');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
            'info' => function ($query) {
                $query->select('join_info_member_id', 'member_info_nickname', 'member_info_headimg');
            },
            'goods' => function ($query) {
                $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_sales_price');
            },
            'order' => function ($query) {
                $query->select('order_id', 'order_amount_pay', 'order_is_complete', 'order_status_system', 'order_status_payment', 'order_addtimes');
            }
        ])->where('goods_evaluate_id', $goodsEvaluateId)
            ->first();

        if (!empty($evaluate->goods_evaluate_json)) {
            $imagesStr = '';
            $goodsEvaluateJson = json_decode($evaluate->goods_evaluate_json, true);
            if (isset($goodsEvaluateJson['photo'])) {
                foreach ($goodsEvaluateJson['photo'] as $file) {
                    if (isset($file['file'])) {
                        $imagesStr .= getenv('APP_IMAGE_DOMAIN_LOCAL') . $file['file']['file_savepath'] . $file['file']['file_savename'] . ',';
                    }
                }
                $evaluate->photos = rtrim($imagesStr, ',');
            }
            if (isset($goodsEvaluateJson['desc'])) {
                $evaluate->desc = $goodsEvaluateJson['desc'];
            }
        }
        if (!empty($evaluate->member) && !empty($evaluate->member->join_member_role_id)) {
            $evaluate->member->level = MemberRole::where('member_role_id', $evaluate->member->join_member_role_id)->value('member_role_name');
        }
        $evaluate->member->member_info_headimg = MemberService::getAvatarUrl(!empty($evaluate->info) && !empty($evaluate->info->member_info_headimg) ? $evaluate->info->member_info_headimg : '');
        $evaluate->member->member_info_nickname = MemberService::getNickname(!empty($evaluate->info) && !empty($evaluate->info->member_info_nickname) ? $evaluate->info->member_info_nickname : '', !empty($evaluate->member) ? $evaluate->member->member_mobile : '');

        if (!empty($evaluate->goods)) {
            $evaluateGoods = $evaluate->goods;
            foreach ($evaluateGoods as &$good) {
                $good['goods_cover'] = getenv('STORAGE_DOMAIN') . $good['goods_cover'];
                $good['goods_cover_origin'] = str_replace('/thumb', '', $good['goods_cover']);
            }
            $evaluate->goods = $evaluateGoods;
//            $evaluate->goods->goods_cover = getenv('STORAGE_DOMAIN') . $evaluate->goods->goods_cover;
//            $evaluate->goods->goods_cover_origin = str_replace('/thumb', '', $evaluate->goods->goods_cover);
        }

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

    /**
     * 添加
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        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 array
     * @throws BusinessException
     */
    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());

        if (!empty($data['goods_evaluate_json'])) {
            $goodsEvaluateJson = explode(',', $data['goods_evaluate_json']);
            foreach ($goodsEvaluateJson as $key => $item) {
                $goodsEvaluateJson[$key] = str_replace(getenv('STORAGE_DOMAIN'), '', $item);
            }

            $data['goods_evaluate_json'] = json_encode(['images' => $goodsEvaluateJson]);
        }

        return $data;
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        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');
    }

    /**
     * 更新前置方法
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }

        if (!empty($data['goods_evaluate_json'])) {
            $goodsEvaluateJson = explode(',', $data['goods_evaluate_json']);
            foreach ($goodsEvaluateJson as $key => $item) {
                $goodsEvaluateJson[$key] = str_replace(getenv('STORAGE_DOMAIN'), '', $item);
            }

            $data['goods_evaluate_json'] = json_encode(['images' => $goodsEvaluateJson]);
        }

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

}