<?php

declare(strict_types=1);

namespace app\common\model;

use Error;
use Exception;
use think\facade\Db;
use mb\helper\Storage;
use think\facade\Filesystem;
use think\facade\Log;
use think\File;

/**
 * Class Base
 * @package app\common\model
 */
class Base
{
    /**
     * @param $ds
     * @param $key
     * @return array
     */
    public static function neaten($ds, $key)
    {
        if (!empty($ds) && !empty($key)) {
            $ret = [];
            foreach ($ds as $row) {
                $ret[] = $row[$key];
            }

            return $ret;
        }

        return [];
    }


    /**
     * @param $type
     * @param $data
     * @return bool|Error
     */
    public static function watch($type, $data)
    {
        $ids = [];
        switch ($type) {
            case 'subject':
                $table = 'exam_subject_watch';
                $param = 'subject_id';
                break;
            case 'news':
                $table = 'news_watch';
                $param = 'news_id';
                break;
            case 'mark_examination_papers':
                $table = 'account_mark_examination_papers';
                $param = 'account';
                break;
            case 'paper_watch':
                $table = 'exam_paper_watch';
                $param = 'paper_id';
                break;
            case 'paper_mark':
                $table = 'exam_paper_mark';
                $param = 'paper_id';
                break;
            default:
                return error(-1, '参数有误');
                break;
        }
        $paramRes = [];
        try {
            $paramRes = Db::table($table)->where([$param => $data['paramId']])->field('id')->select()->toArray();
        } catch (Exception $e) {
        }
        if (!empty($paramRes)) {
            $ids = self::neaten($paramRes, 'id');
            $where[] = ['id', 'in', $ids];
        }
        $department = [];
        $user = [];
        if (!empty($data['department'])) {
            $department = array_map(
                function ($d) use ($param, $data) {
                    return [$param => $data['paramId'], 'type' => 'department', 'binding_id' => $d];
                },
                $data['department']
            );
        }
        if (!empty($data['user'])) {
            $user = array_map(
                function ($u) use ($param, $data) {
                    return [$param => $data['paramId'], 'type' => 'user', 'binding_id' => $u];
                },
                $data['user']
            );
        }
        $newData = array_merge($department, $user);
        if (empty($newData)) {
            $newData = [
                $param => $data['paramId'],
                'type' => '',
                'binding_id' => 0
            ];
            try {
                Db::table($table)->insert($newData);
            } catch (Exception $e) {
                Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
            }
        } else {
            try {
                Db::table($table)->insertAll($newData);
            } catch (Exception $e) {
                Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
            }
        }
        if (!empty($ids)) {
            try {
                Db::table($table)->where($where)->delete();
            } catch (Exception $e) {
                Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
            }
        }
        return true;
    }

    /**
     * @return Storage
     */
    /*public static function createStorage()
    {
        $config = [
            'type' => 'qiniu',
            'key' => 'clB4wTgL4BiNpCa_J4uO3RQ7hMG92KGiUudNumg9',
            'secret' => 'NyzEFPvxuoXva3wGpUf5mH7_bOEEwhcYiayFM_7q',
            'host' => 'res.huihujiankang.cn',
            'bucket' => 'diagnosis'
        ];

        return Storage::create($config);
    }*/

    /**
     * 密码加密
     * @param $salt
     * @param $password
     * @return string
     */
    public static function encodePassword($salt, $password)
    {
        $string = "{$password}{$salt}";
        return sha1($string);
    }

    /**
     * 用$id作为键值
     * @param string $id
     * @param array $array
     * @return array
     */
    public static function headelId($id = 'id', array $array = [])
    {
        $newSet = [];
        foreach ($array as $v) {
            $newSet[$v[$id]] = $v;
        }
        return $newSet;
    }

    /**
     * key与Value 互相转换
     * @param $array
     * @return array
     */
    public static function exchangeKey($array)
    {
        $newArray = [];
        foreach ($array as $k => $v) {
            $newArray[$v] = $k;
        }
        return $newArray;
    }

    /**
     * input
     * fields
     * @param $array
     * @param $must
     * @param bool $equality
     * @return array|Error
     */
    public static function existsParams(array $array, array $must, $equality = false)
    {
        $params = [];
        if ($equality && (count($array) !== count($must))) {
            return error(-10, '长度不相等');
        }
        foreach ($must as $v) {
            if (!isset($array[$v])) {
                return error(-11, "缺少{$v}");
            }
            $params[$v] = $array[$v];
        }
        return $params;
    }

    /**
     * @param string $type
     * @param int $id
     * @return bool
     */
    public static function addView(string $type, int $id)
    {
        try {
            switch ($type) {
                case 'news':
                    $table = 'news';
                    break;
                case 'chapter':
                    $table = 'book_chapter';
                    break;
                default:
                    return false;
            }
            Db::table($table)->where(['id' => $id])->inc('view')->update();
            return true;
        } catch (Exception $e) {
        }
        return false;
    }

    /**
     * @param string $type images file
     * @return array|bool|string
     */
    public static function uploadfile($type = 'image')
    {
//        $imagesFile = public_path() . 'public/'.$type;
//        if (!is_dir($imagesFile)) {
//            mkdir($imagesFile);
//        }
        $files = input('file.file');
        if (empty($files)) {
            return [];
        }
        try {
            $saveName = [];
            if (is_array($files)) {
                foreach ($files as $k => $v) {
                    $src = Filesystem::disk($type)->putFile('', $v, 'md5');
                    $saveName[] = str_replace('\\', '/', $src);
                }
            } else {
//                dump($files->)
                $src = Filesystem::disk($type)->putFile('', $files, 'md5');
                $saveName = str_replace('\\', '/', $src);
            }
            return $type . '/' . $saveName;
        } catch (Exception $e) {
        }
        return [];
    }

    /**
     * @param $str
     * @return string|string[]|null
     */
    public static function mb_unserialize($str)
    {
        return preg_replace_callback('#s:(\d+):"(.*?)";#s', function ($match) {
            return 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
        }, $str);
    }
}