<?php

namespace app\model;

use think\Model;

class OssUpload extends Model
{

    protected $connection = 'mysql';

    protected $pk = 'id';

    protected $name = 'oss_upload';

    public static function datainitial()
    {
        $weid = weid();
        $data[1] = [
            'weid' => $weid,
            'code' => 'qiniuyun',
            'title' => '七牛云oss',
            'settings' => '',
            'status' => 0,
            'sort' => 10,
        ];
        $data[2] = [
            'weid' => $weid,
            'code' => 'ali',
            'title' => '阿里云oss',
            'settings' => '',
            'status' => 0,
            'sort' => 20,
        ];

        foreach ($data as $vo) {
            if (!(self::where(['weid' => $weid, 'code' => $vo['code']])->find())) {
                self::create($vo);
            }
        }
    }
    public static function getSettings($code = '')
    {
        $where['status'] = 1;
        if ($code) {
            $where['code'] = $code;
        }

        $data = self::where(['weid' => weid()])->where($where)->order('id desc')->find();

        if (empty($data)) {
            $data = self::where(['weid' => 0])->where($where)->order('id desc')->find();
        }
        if (!empty($data)) {
            $data = $data->toArray();
            $data['settings'] = iunserializer($data['settings']);
            $data['settings']['status'] = $data['status'];
            $data['settings']['code'] = $data['code'];
        }
        return self::setcompatible($data['settings'], $data['code']);
    }

    public static function setcompatible($data, $code)
    {
        if ($code == 'qiniuyun') {
            $data['oss_accessKey'] = $data['oss_accessKey'] ?? $data['qny_oss_accessKey'];
            $data['oss_secretKey'] = $data['oss_secretKey'] ?? $data['qny_oss_secretKey'];
            $data['oss_bucket'] = $data['oss_bucket'] ?? $data['qny_oss_bucket'];
            $data['oss_domain'] = $data['oss_domain'] ?? $data['qny_oss_domain'];
        } elseif ($code == 'ali') {
            $data['oss_accessKey'] = $data['oss_accessKey'] ?? $data['ali_oss_accessKeyId'];
            $data['oss_secretKey'] = $data['oss_secretKey'] ?? $data['ali_oss_accessKeySecret'];
            $data['oss_bucket'] = $data['oss_bucket'] ?? $data['ali_oss_bucket'];
            $data['oss_domain'] = $data['oss_domain'] ?? $data['ali_oss_endpoint'];
        }

        return $data;
    }
}
