<?php namespace Pan\Lib;
use Dever;
class Quark
{
    private $header;
    private $partition;
    public function run($account, $task, $partition)
    {
        if ($partition) {
            $this->partition = $partition;
        }
        $this->header($account['cookie']);
        if ($task['mul'] == 1 && $task['path']) {
            $this->handle($account, $task);
        } elseif ($task['file']) {
            $file = Dever::load('view', 'upload')->local($task['file']);
            $excel = Dever::load('import', 'excel')->act($file);
            if ($excel) {
                foreach ($excel as $k => $v) {
                    if ($v['A']) {
                        $task['path'] = trim($v['A']);
                        $task['code'] = trim($v['B']);
                        $this->handle($account, $task);
                    }
                }
            }
        }
    }

    # 处理
    private function handle($account, $task)
    {
        if (empty($task['code'])) {
            $task['code'] = '';
        }
        $temp = explode("\n", $task['path']);
        $task['path'] = $temp[0];
        if (isset($temp[1])) {
            $task['code'] = $temp[1];
        }
        $path = pathinfo($task['path']);
        if (strstr($path['filename'], '-')) {
            $path = explode('-', $path['filename']);
            $path = $path[0];
        } else {
            $path = $path['filename'];
        }
        
        if ($task['type'] == 1) {
            $this->save($path, $account, $task);
        } elseif ($task['type'] == 2) {
            $this->share($path, $account, $task);
        }
    }

    # 转存
    private function save($pwd_id, $account, $task, $end = false)
    {
        $token = $this->token($pwd_id, $task['code']);
        if ($token) {
            $page = 1;
            $state = true;
            while($state) {
                $data = $this->detail($page, $pwd_id, $token);
                if ($data) {
                    foreach ($data as $k => $v) {
                        $task_id = $this->saveFile($task['save_path'], $pwd_id, $token, $v['fid'], $v['share_fid_token'], $v['pdir_fid']);
                        $check = $this->check($account['id'], $task['id'], $v['fid']);
                        if (!$check) {
                            $this->up($account['id'], $task['id'], $pwd_id, $v['fid'], $v['file_name'], $task_id, $task_id, $v);
                        }
                    }
                    $page++;
                } else {
                    $state = false;
                }
            }
        }
    }

    # 分享
    private function share($path, $account, $task, $end = false)
    {
        $page = 1;
        $state = true;
        # 该path下是否还有目录，默认没有
        $result = false;
        while($state) {
            # 获取当前目录下的文件列表
            $result = Dever::curl('https://drive-pc.quark.cn/1/clouddrive/file/sort?pr=ucpro&fr=pc&uc_param_str=&pdir_fid='.$path.'&_page='.$page.'&_size=50&_fetch_total=1&_fetch_sub_dirs=0&_sort=file_type:asc,updated_at:desc', array(), 'get', false, $this->header)->result();
            $result = Dever::json_decode($result);
            if (isset($result['data']['list']) && $result['data']['list']) {
                $total = count($result['data']['list']);
                foreach ($result['data']['list'] as $k => $v) {
                    if ($task['oper_filter']) {
                        $temp = explode("\n", $task['oper_filter']);
                        foreach ($temp as $k => $v) {
                            if (strstr($v['file_name'], $v)) {
                                continue;
                            }
                        }
                    }
                    if ($v['file_type'] == 1) {
                        # 文件
                        $ext = pathinfo($v['file_name'], PATHINFO_EXTENSION);
                        if ($task['oper_ext'] && (!strstr($task['oper_ext'], $ext) || !strstr($task['oper_ext'], 'file'))) {
                            continue;
                        }
                        if ($end) {
                            continue;
                        }
                    } else {
                        $result = true;
                        # 目录
                        if ($end) {
                            continue;
                        }
                        if ($task['oper_ext'] && !strstr($task['oper_ext'], 'dir')) {
                            continue;
                        }
                        if ($task['oper'] == 2) {
                            # 获取所有资源
                            $this->handle($v['fid'], $account, $task);
                        } elseif ($task['oper'] == 3) {
                            # 寻找最后一级资源
                            $last = $this->handle($v['fid'], $account, $task, true);
                            if (!$last) {
                                $this->handle($v['fid'], $account, $task);
                            }
                            continue;
                        }
                    }
                    $check = $this->check($account['id'], $task['id'], $v['fid']);
                    if (!$check) {
                        $task_id = $this->create($v['fid'], $v['file_name']);
                        if ($task_id) {
                            $share_id = $this->task($task_id);
                            if ($share_id) {
                                $info = $this->password($share_id);
                                $this->up($account['id'], $task['id'], $path, $v['fid'], $v['file_name'], $task_id, $share_id, $info, $page, $total, $k+1);
                            }
                        }
                    }
                }
                $page++;
            } else {
                $state = false;
            }
        }
        return $result;
    }

    # 导入分享数据
    public function import($account, $task, $partition)
    {
        if ($partition) {
            $this->partition = $partition;
        }
        $this->header($account['cookie']);
        $page = 1;
        $state = true;
        while($state) {
            $result = Dever::curl('https://drive-pc.quark.cn/1/clouddrive/share/mypage/detail?pr=ucpro&fr=pc&uc_param_str=&_page='.$page.'&_size=50&_order_field=created_at&_order_type=desc&_fetch_total=1&_fetch_notify_follow=1', array(), 'get', false, $this->header)->result();
            $result = Dever::json_decode($result);
            if (isset($result['data']['list']) && $result['data']['list']) {
                foreach ($result['data']['list'] as $k => $v) {
                    $check = $this->check($account['id'], $task['id'], $v['first_fid'], $v['share_id']);
                    if (!$check) {
                        $this->up($account['id'], $task['id'], 'share', $v['first_fid'], $v['title'], false, $v['share_id'], $v);
                    }
                }
                $page++;
            } else {
                $state = false;
            }
        }
    }

    private function header($cookie)
    {
        if (!$this->header) {
            $this->header['accept'] = 'application/json, text/plain, */*';
            $this->header['content-type'] = 'application/json';
            $this->header['sec-ch-ua'] = '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"';
            $this->header['ec-ch-ua-mobile'] = '?0';
            $this->header['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
            $this->header['sec-ch-ua-platform'] = '"Windows"';
            $this->header['origin'] = 'https://pan.quark.cn';
            $this->header['sec-fetch-site'] = 'same-site';
            $this->header['sec-fetch-mode'] = 'cors';
            $this->header['sec-fetch-dest'] = 'empty';
            $this->header['accept-encoding'] = 'gzip, deflate, br';
            $this->header['accept-language'] = 'zh-CN,zh;q=0.9';
            $this->header['referer'] = 'https://pan.quark.cn/';
            $this->header['cookie'] = $cookie;
        }
    }

    # 获取token
    private function token($pwd_id, $code)
    {
        $param = array();
        $param['pwd_id'] = $pwd_id;
        $param['passcode'] = $code;
        $result = Dever::curl('https://drive-pc.quark.cn/1/clouddrive/share/sharepage/token?pr=ucpro&fr=pc&uc_param_str=&__dt=405&__t=' . Dever::uuid(), $param, 'post', true, $this->header)->result();
        $result = Dever::json_decode($result);
        if (isset($result['data']['stoken']) && $result['data']['stoken']) {
            return $result['data']['stoken'];
        } else {
            return false;
        }
    }

    # 获取详情
    private function detail($page, $pwd_id, $token)
    {
        $param = array();
        $param['pwd_id'] = $pwd_id;
        $param['stoken'] = $token;
        $param['pdir_fid'] = '0';
        $param['_page'] = $page;
        $param['_size'] = 50;
        $result = Dever::curl('https://drive-pc.quark.cn/1/clouddrive/share/sharepage/detail', $param, 'get', false, $this->header)->result();
        $result = Dever::json_decode($result);
        if (isset($result['data']['list']) && $result['data']['list']) {
            return $result['data']['list'];
        } else {
            return false;
        }
    }

    # 开始分享
    private function create($id, $name)
    {
        $param = array();
        $param['expired_type'] = 1;
        $param['fid_list'] = array($id);
        $param['title'] = $name;
        $param['url_type'] = 1;//2是有提取码，1是无提取码
        //$param['passcode'] = '';
        $result = Dever::curl('https://drive-pc.quark.cn/1/clouddrive/share?pr=ucpro&fr=pc&uc_param_str=', $param, 'post', true, $this->header)->result();
        $result = Dever::json_decode($result);
        if (isset($result['data']['task_id']) && $result['data']['task_id']) {
            return $result['data']['task_id'];
        } else {
            return false;
        }
    }

    # 保存文件
    private function saveFile($save_path, $pwd_id, $token, $first_id, $share_fid_token, $to_pdir_fid)
    {
        if ($save_path) {
            $save_path = pathinfo($save_path);
            $save_path = explode('-', $save_path['filename']);
            $save_path = $save_path[0];
        } else {
            $save_path = '0';
        }
        $param['fid_list'] = $first_id;
        $param['fid_token_list'] = array($share_fid_token);
        $param['to_pdir_fid'] = $to_pdir_fid;
        $param['pwd_id'] = $pwd_id;
        $param['stoken'] = $token;
        $param['pdir_fid'] = $save_path;
        $param['scene'] = 'link';
        $result = Dever::curl('https://drive.quark.cn/1/clouddrive/share/sharepage/save?pr=ucpro&fr=pc&uc_param_str=&__dt=&__t=', $param, 'post', true, $this->header)->result();
        $result = Dever::json_decode($result);
        if (isset($result['data']['task_id']) && $result['data']['task_id']) {
            return $this->task($result['data']['task_id']);
        } else {
            return false;
        }
    }

    # 启动分享任务
    private function task($task_id)
    {
        $result = Dever::curl('https://drive-pc.quark.cn/1/clouddrive/task?pr=ucpro&fr=pc&uc_param_str=&task_id='.$task_id.'&retry_index=0', array(), 'get', false, $this->header)->result();
        $result = Dever::json_decode($result);
        if (isset($result['data']['share_id']) && $result['data']['share_id']) {
            return $result['data']['share_id'];
        } elseif (isset($result['data']['task_id']) && $result['data']['task_id']) {
            return $result['data']['task_id'];
        } else {
            return false;
        }
    }

    # 获得分享链接
    private function password($share_id)
    {
        $param['share_id'] = $share_id;
        $result = Dever::curl('https://drive-pc.quark.cn/1/clouddrive/share/password?pr=ucpro&fr=pc&uc_param_str=', $param, 'post', true, $this->header)->result();
        $result = Dever::json_decode($result);
        if (isset($result['data']['share_url']) && $result['data']['share_url']) {
            return $result['data'];
        } else {
            return false;
        }
    }

    # 删除分享
    public function delete($share_id, $cookie)
    {
        $this->header($cookie);
        $param['share_ids'] = $share_id;
        $result = Dever::curl('https://drive-pc.quark.cn/1/clouddrive/share/delete?pr=ucpro&fr=pc&uc_param_str=', $param, 'post', true, $this->header)->result();
        $result = Dever::json_decode($result);
        if (isset($result['message']) && $result['message'] == 'ok') {
            return true;
        } else {
            return false;
        }
    }

    # 检测数据
    private function check($account_id, $account_task_id, $fid, $share_id = false)
    {
        if ($this->partition) {
            $db = Dever::db('task_data', 'pan', 'default', $this->partition);
        } else {
            $db = Dever::db('task_data', 'pan');
        }
        $data['account_id'] = $account_id;
        $data['account_task_id'] = $account_task_id;
        $data['fid'] = $fid;
        if ($share_id) {
            $data['share_id'] = $share_id;
        }
        return $db->find($data);
    }

    # 保存数据
    private function up($account_id, $account_task_id, $path, $fid, $file_name, $task_id, $share_id, $info, $page = 1, $total = 1, $num = 1)
    {
        if ($this->partition) {
            $db = Dever::db('task_data', 'pan', 'default', $this->partition);
        } else {
            $db = Dever::db('task_data', 'pan');
        }
        $data['account_id'] = $account_id;
        $data['account_task_id'] = $account_task_id;
        $data['path'] = $path;
        $data['fid'] = $fid;
        $data['file_name'] = $file_name;
        if ($task_id) {
            $data['task_id'] = $task_id;
        }
        $data['share_id'] = $share_id;
        $data['share_url'] = $info['share_url'];
        if ($info) {
            $data['info'] = Dever::json_encode($info);
        }
        $db->insert($data);
        /*
        $task_data = $db->find(array('share_id' => $data['share_id']));
        if (!$task_data) {
            $db->insert($data);
        }*/
    }
}