<?php
namespace app\home\model;

use think\Model;

class Currency extends Model
{
    public function add($param)
    {
        if ($this->codeExists((string) $param['code'])) {
            return to_assign(1, '该币种代码已存在，请勿重复添加');
        }
        try {
            $param['code']        = strtoupper(trim((string) $param['code']));
            $param['create_time'] = time();
            $insertId = self::strict(false)->field(true)->insertGetId($param);
            add_log('add', $insertId, $param);
        } catch (\Exception $e) {
            return to_assign(1, '操作失败，原因：' . $e->getMessage());
        }
        return to_assign(0, '操作成功', ['return_id' => $insertId]);
    }

    public function edit($param)
    {
        if ($this->codeExists((string) $param['code'], (int) $param['id'])) {
            return to_assign(1, '该币种代码已存在，请勿重复添加');
        }
        try {
            $param['code'] = strtoupper(trim((string) $param['code']));
            self::where('id', $param['id'])->strict(false)->field(true)->update($param);
            add_log('edit', $param['id'], $param);
        } catch (\Exception $e) {
            return to_assign(1, '操作失败，原因：' . $e->getMessage());
        }
        return to_assign(0, '操作成功', ['return_id' => $param['id']]);
    }

    /**
     * 校验币种代码是否已被占用（编辑时排除自身）
     */
    protected function codeExists(string $code, int $excludeId = 0): bool
    {
        $code  = strtoupper(trim($code));
        $query = self::where(['code' => $code, 'delete_time' => 0]);
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->count() > 0;
    }

    public function getById($id)
    {
        return self::find($id);
    }

    public function delById($id)
    {
        try {
            self::where('id', $id)->update(['delete_time' => time()]);
            add_log('delete', $id);
        } catch (\Exception $e) {
            return to_assign(1, '操作失败，原因：' . $e->getMessage());
        }
        return to_assign();
    }

    /**
     * 业务表单下拉用：取所有启用币种，按 sort 排序
     */
    public static function getEnabled()
    {
        return self::where(['status' => 1, 'delete_time' => 0])
            ->order('sort asc, id asc')
            ->select();
    }
}