<?php

namespace app\admin\controller\mall;

use app\common\controller\Backend;
use support\Response;
use Webman\Http\Request;

/**
 * 商品管理
 */
class Item extends Backend
{
    /**
     * MallItem模型对象
     * @var object|null
     * @phpstan-var \app\common\model\MallItem|null
     */
    protected ?object $model = null;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array $withJoinTable = ['admin'];

    protected string|array $quickSearchField = ['id', 'title'];

    /** 添加时自动填充 admin_id */
    protected bool $autoFillAdminId = true;

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\common\model\MallItem();
    }

    /**
     * 查看
     */
    public function index(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) {
            return $response;
        }

        if ($request->get('select') || $request->post('select')) {
            return $this->select($request);
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->visible(['admin' => ['username']])
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        return $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 远程下拉选择数据（供 remoteSelect 使用）
     */
    public function select(Request $request): Response
    {
        $response = $this->initializeBackend($request);
        if ($response !== null) {
            return $response;
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field('id,title')
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        return $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 兼容不同前端键名，避免英文字段被漏存。
     * - 优先 snake_case: title_en / description_en
     * - 回落 camelCase: titleEn / descriptionEn
     */
    private function normalizeLangFields(array $data): array
    {
        $data['title_en'] = isset($data['title_en'])
            ? strval($data['title_en'])
            : strval($data['titleEn'] ?? '');
        $data['description_en'] = isset($data['description_en'])
            ? strval($data['description_en'])
            : strval($data['descriptionEn'] ?? '');
        $data['title_ms'] = isset($data['title_ms'])
            ? strval($data['title_ms'])
            : strval($data['titleMs'] ?? '');
        $data['description_ms'] = isset($data['description_ms'])
            ? strval($data['description_ms'])
            : strval($data['descriptionMs'] ?? '');

        unset($data['titleEn'], $data['descriptionEn'], $data['titleMs'], $data['descriptionMs']);

        return $data;
    }

    /**
     * 重写新增：显式处理中英马三语字段。
     */
    protected function _add(): Response
    {
        if ($this->request && $this->request->method() === 'POST') {
            $data = $this->request->post();
            if (!$data) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->applyInputFilter($data);
            $data = $this->normalizeLangFields($data);
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            if ($this->autoFillAdminId && $this->dataLimitField === 'admin_id') {
                $data['admin_id'] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) {
                            $validate->scene('add');
                        }
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            if ($result !== false) {
                return $this->success(__('Added successfully'));
            }
            return $this->error(__('No rows were added'));
        }

        return $this->error(__('Parameter error'));
    }

    /**
     * 重写编辑：显式处理中英马三语字段。
     */
    protected function _edit(): Response
    {
        $pk = $this->model->getPk();
        $id = $this->request ? ($this->request->post($pk) ?? $this->request->get($pk)) : null;
        $row = $this->model->find($id);
        if (!$row) {
            return $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            return $this->error(__('You have no permission'));
        }

        if ($this->request && $this->request->method() === 'POST') {
            $data = $this->request->post();
            if (!$data) {
                return $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->applyInputFilter($data);
            $data = $this->normalizeLangFields($data);
            $data = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) {
                            $validate->scene('edit');
                        }
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            if ($result !== false) {
                return $this->success(__('Update successful'));
            }
            return $this->error(__('No rows updated'));
        }

        return $this->success('', [
            'row' => $row
        ]);
    }
}