<?php

namespace app\index\controller;

use Alchemy\Zippy\Zippy;
use app\model\Category;
use app\model\Nav;
use app\model\Post;
use app\model\PostCategory;
use app\model\Share;
use app\model\ShareFiles;
use app\UploadFiles;
use think\facade\App;
use think\facade\Session;
use think\facade\Validate;
use think\facade\View;
use think\File;
use think\Request;
use think\validate\ValidateRule;

class Index extends Common
{
  /**
   * 显示资源列表
   *
   * @return \think\Response
   */
  public function index()
  {
    //

    $list_active_shares = Share::where('user_id', $this->modelUser->id)->order('id desc')->where('status', 0)->select();

    View::assign('list_active_shares', $list_active_shares);

    return View::fetch();
  }


  /**
   * 显示创建资源表单页.
   *
   * @return \think\Response
   */
  public function create()
  {
    //
  }

  /**
   * 保存新建的资源
   *
   * @param  \think\Request  $request
   * @return \think\Response
   */
  public function save(Request $request)
  {
    //

    $post_data = $request->post();

    $post_data['user_id'] = $this->modelUser->id;
    $post_data['uid'] = uniqid();
    $post_data['times_last'] = $post_data['times'];
    $root_dir = App::getRootPath();

    $safe_dir = '/safe/';

    $file_preifx = $root_dir . $safe_dir;


    $validate = Validate::rule('files_list', ValidateRule::isRequire()->isArray()->requireCallback(function ($value) use ($file_preifx) {
      foreach ($value as $key_v => $value_v) {
        $file_path = $file_preifx . $value_v['save_name'];

        if (!file_exists($file_path)) {
          return false;
        }
      }

      return true;
    }, '文件不存在'))
      ->rule('password', ValidateRule::length('6,18'))
      ->rule('times', ValidateRule::requireCallback(function ($value) {
        if (empty($value)) {
          return true;
        }

        if (is_numeric($value)) {
          if ($value > 0) {
            return true;
          }
        }

        return false;
      }))
      ->rule('expire', ValidateRule::isRequire()->isNumber()->min(1));

    if (!$validate->check($post_data)) {
      return json_message($validate->getError());
    }


    $model_share = Share::create($post_data);

    $total_size = 0;

    $files_list = [];

    foreach ($post_data['files_list'] as $key_file => $value_file) {

      $file_path = $file_preifx . $value_file['save_name'];

      UploadFiles::use($value_file['save_name']);

      $file = new File($file_path);

      $model_share_file = new ShareFiles();

      $model_share_file->save_name = $value_file['save_name'];
      $model_share_file->file_name = $value_file['file_name'];

      $model_share_file->mime_type = $file->getMime();

      $model_share_file->file_size = $file->getSize();

      $model_share_file->ext_name = $file->extension();

      $model_share_file->file_md5 = $file->md5();
      $model_share_file->file_sha1 = $file->sha1();

      $model_share_file->share_id = $model_share->id;

      $model_share_file->save();

      $file_name = $value_file['file_name'];

      $file_name = $this->build_files_list_key($files_list, $file_name);

      $files_list[$file_name] = $file_path;


      $total_size += $file->getSize();
    }

    // 合成大文件

    $zippy = Zippy::load();

    $download_zip_save_name = 'build_download_zip/' . uniqid() . '.zip';

    $build_download_path = $file_preifx . $download_zip_save_name;

    $build_download_dir = dirname($build_download_path);

    if (!is_dir($build_download_dir)) {
      mkdir($build_download_dir, 0777, true);
    }

    $build_archive = $zippy->create($build_download_path, $files_list, true);

    $model_share->build_download_save_name = $download_zip_save_name;

    $model_share->total_size = $total_size;

    $model_share->save();

    return json_message();
  }

  public function build_files_list_key($file_list, $file_key)
  {
    if (!isset($file_list[$file_key])) {
      return $file_key;
    }

    $file_name = $file_key;
    $file_ext = '';
    if (strpos($file_key, '.') !== false) {
      $file_key_array = explode('.', $file_key);
      $file_ext = array_pop($file_key_array);

      $file_name = implode('.', $file_key_array);
    }

    $new_file_name = $file_name . '(1).' . $file_ext;

    return $this->build_files_list_key($file_list, $new_file_name);
  }

  public function logout()
  {
    Session::clear();

    return $this->success('已成功退出', url('index'));
  }

  /**
   * 显示指定的资源
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function read($uid)
  {
    //
    $msg = '';

    $model_share = Share::where('uid', $uid)->find();
    View::assign('share', $model_share);

    $list_share_files = ShareFiles::where('share_id', $model_share->id)->select();

    View::assign('share_files', $list_share_files);


    $is_download = $this->request->param('do_download');
    $password = trim($this->request->param('password'));


    if (empty($model_share)) {
      $msg = '访问的分享链接不存在';
    } else if ($model_share->expire_time < time()) {
      $msg = '分享链接已过期';
    } else if (!empty($model_share->password)) {
      if ($is_download == 1) {
        if (empty($password)) {
          $msg = '请输入密码';
        }

        if ($model_share->password != $password) {
          $msg = '输入的密码错误';
        }
      }
    } else if ($model_share->times > 0 && $model_share->times_last == 0) {
      $msg = '分享的文件已没有下载次数';
    } else if ($model_share->status != 0) {
      $msg = '文件已下架';
    }

    if ($is_download == 1) {

      if (!empty($msg)) {
        return $this->error($msg);
      }

      if ($model_share->times > 0) {
        $model_share->times_last--;
        $model_share->times_download++;
        $model_share->save();
      }

      return download(ShareFiles::build_safe_path($model_share->build_download_save_name), basename($model_share->build_download_save_name));
    }

    $model_share->visit++;
    $model_share->save();

    View::assign('msg', $msg);
    return  View::fetch();
  }

  /**
   * 显示编辑资源表单页.
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function edit($id)
  {
    //
  }

  /**
   * 保存更新的资源
   *
   * @param  \think\Request  $request
   * @param  int  $id
   * @return \think\Response
   */
  public function update(Request $request, $id)
  {
    //
  }

  /**
   * 删除指定资源
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function delete($id)
  {
    //
  }
}
