<?php

namespace app\common\controller;

use app\BaseController;
use app\common\middleware\Auth;
use think\facade\Db;
use app\enterprise\api\TalentApi;
use app\common\api\TalentLogApi;
use app\common\api\DictApi;

/**
 * 需要权限的公共方法放这
 * Description of Tool
 *
 * @author sgq
 */
class Api extends BaseController {

    protected $middleware = [Auth::class];
    protected $user;

    public function __construct(\think\App $app) {
        parent::__construct($app);
        $this->user = session("user");
    }

    public function findIdentifyConditionByLevel() {
        $params = $this->request->param();
        $id = $params["id"];
        if ($this->user["usertype"] == 2) {
            $type = $this->user["type"];
        } else {
            $talentInfo = TalentApi::getOne($id);
            $enterprise = \app\common\model\Enterprise::findOrEmpty($talentInfo["enterprise_id"]);
            $type = $enterprise["type"];
        }
        $list = \app\common\api\TalentConditionApi::getList($params["level"], $type);
        return json($list, 200);
    }

    public function getCheckLog() {
        $params = $this->request->param();
        $mainId = $params["mainId"];
        $type = $params["type"];
        $list = TalentLogApi::getList($type, $mainId);
        $new_list = [];
        foreach ($list as $item) {
            $new_item["stepName"] = DictApi::getTalentInfoStepByState($item["state"]);
            if ($item["state"] == 13) {
                $new_item["stateName"] = '<span class="label label-success">审核不通过</span>';
            } else if (in_array($item["state"], [3, 7, 9, 11])) {
                $new_item["stateName"] = '<span class="label label-primary">审核通过</span>';
            } else if (in_array($item["state"], [4, 8, 10, 12])) {
                $new_item["stateName"] = '<span class="label label-danger">审核驳回</span>';
            } else {
                $new_item["stateName"] = '<span class="label label-success">待审核</span>';
            }
            if ($item["last_state"] && $item["state"]) {
                $new_item["stateChange"] = sprintf("%s -> %s", DictApi::getTalentInfoStateName($item["last_state"]), DictApi::getTalentInfoStateName($item["state"]));
            } else {
                $new_item["stateChange"] = "";
            }
            $new_item["description"] = $item["description"];
            $new_item["createUser"] = $item["createUser"];
            $new_item["createTime"] = $item["createTime"];
            $new_list[] = $new_item;
        }
        return json(["rows" => $new_list]);
    }

    public function findCommonFileType() {
        $param = $this->request->param();
        $order = $param["order"];
        $project = $param["project"];
        $type = $param["type"];
        $checkState = $param["checkState"];
        if (in_array($checkState, [0, 1, 2, 3])) {
            $where[] = ["step", "=", 1];
        }
        $where[] = ["project", "=", $project];
        $where[] = ["type", "=", $type];
        return json(["rows" => Db::table("new_common_filetype")->where($where)->order("sn " . $order)->select()]);
    }

    public function listTalentFile() {
        $param = $this->request->param();
        $mainId = $param["mainId"];
        $typeId = $param["fileTypeId"];
        $where = [["mainId", "=", $mainId], ["typeId", "=", $typeId]];
        $list = Db::table("new_talent_file")->where($where)->select()->toArray();
        foreach ($list as $key => $item) {
            $list[$key]["url"] = "/storage/" . $item["url"]; //获取系统配置无效，暂时这样
        }
        return json($list);
    }

    public function addTalentFile() {
        $backName = $this->request->param("backName");
        $fileId = $this->request->param("fileId");
        $mainId = $this->request->param("mainId");
        $fileTypeId = $this->request->param("fileTypeId");
        $index = $this->request->param("index");
        $type = $this->request->param("type");
        $upload = new \app\common\api\UploadApi();
        $file = $this->request->file("fileUrl");
        if (!TalentApi::checkIsEditable($mainId)) {
            $res = ["msg" => "当前状态不能修改附件", "obj" => $index];
            echo sprintf("<script>parent.%s(%s);</script>", $backName, json_encode($res));
            exit();
        }
        $filestd = $upload->uploadOne($file, "image", "talent_files");
        if ($fileId) {
            if (!$this->chkIsFileOwner($mainId, $type)) {
                $res = ["msg" => "删除失败", "obj" => $index];
                echo sprintf("<script>parent.%s(%s);</script>", $backName, json_encode($res));
                exit();
            }
            $old = Db::table("new_talent_file")->findOrEmpty($fileId);
            $old_filepath = "storage/" . $old["url"];
            if (file_exists($old_filepath))
                unlink($old_filepath);
            $data["id"] = $fileId;
        }
        $data["mainId"] = $mainId;
        $data["type"] = $type;
        $data["typeId"] = $fileTypeId;
        $data["orignName"] = $file->getOriginalName();
        $data["url"] = $filestd->filepath;
        $data["sn"] = $index;
        $data["createTime"] = time();
        Db::table("new_talent_file")->save($data);
        TalentLogApi::write($type, $mainId, 0, sprintf("添加附件，附件名为：%s", $data["orignName"]), 1, $fileTypeId);
        $res = ["code" => 200, "msg" => "上传附件成功", "obj" => $index, "info" => $url];
        echo sprintf("<script>parent.%s(%s);</script>", $backName, json_encode($res));
    }

    public function deleteFile() {
        $param = $this->request->param();
        $where = [["id", "=", $param["id"]]];
        $file = Db::table("new_talent_file")->where($where)->findOrEmpty();

        if (!TalentApi::checkIsEditable($file["mainId"]))
            return json(["msg" => "当前状态不能删除"]);
        if ($this->chkIsFileOwner($file["mainId"], $file["type"])) {
            $filepath = "storage/" . $file["url"];
            if (file_exists($filepath)) {
                unlink($filepath);
            }
            Db::table("new_talent_file")->delete($file["id"]);
            TalentLogApi::write($file["type"], $file["mainId"], 0, sprintf("删除附件，附件名为：%s", $file["orignName"]), 1, $file["typeId"]);
            return json(["code" => 200, "msg" => "删除成功"]);
        }
        return json(["msg" => "不能删除"]);
    }

    /**
     * 下载文件
     */
    public function downloadFile() {
        $param = $this->request->param();
        $type = $param["type"];
        $id = $param["id"];
        $where = [];
        $where[] = ["id", "=", $id];
        $where[] = ["type", "=", $type];
        $fileinfo = Db::table("new_talent_file")->where($where)->findOrEmpty();
        $filename = $fileinfo["orignName"];
        $filepath = "storage/" . $fileinfo["url"];     // 下载文件名
        if (!file_exists($filepath)) {
            header('HTTP/1.1 404 NOT FOUND');
        } else {
            $file = fopen($filepath, "rb");

            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length: " . filesize($filepath));
            Header("Content-Disposition: attachment; filename=" . $filename);

            echo fread($file, filesize($filepath));
            fclose($file);

            exit();
        }
    }

    /**
     * 打包下载人才申请附件
     */
    public function downloadZip() {
        $param = $this->request->param();
        $type = $param["type"];
        $id = $param["id"];
        $where = [];
        $where[] = ["mainId", "=", $id];
        $where[] = ["type", "=", $type];
        $files = Db::table("new_talent_file")->where($where)->select()->toArray();
        if (!$files)
            die("没有附件不能打包下载");

        $talent_info = \app\enterprise\model\Talent::findOrEmpty($id);
        $enterprise_info = \app\common\model\Enterprise::findOrEmpty($talent_info["enterprise_id"]);
        $zip_filename = sprintf("%s(%s)人才申报材料.zip", $talent_info["name"], $enterprise_info["name"]);

        $tmp_path = "storage/temp/";
        $tmp_file_path = $tmp_path . $zip_filename;
        if (!file_exists($tmp_path)) {
            mkdir($tmp_path);
        }
        $zip = new \ZipArchive();
        if (!$zip->open($tmp_file_path, \ZipArchive::CREATE | \ZipArchive::OVERWRITE)) {
            header('HTTP/1.1 404 NOT FOUND');
        }
        foreach ($files as $file) {
            $filepath = "storage/" . $file["url"];
            $filename = $file["orignName"];
            $zip->addFile($filepath, $filename);
        }
        $zip->close();
        if (file_exists($tmp_file_path)) {
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header('Content-disposition: attachment; filename=' . $zip_filename); //文件名
            header("Content-Type: application/octet-stream;charset=utf-8"); //zip格式的
            header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
            header('Content-Length: ' . filesize($tmp_file_path)); //告诉浏览器，文件大小
            @readfile($tmp_file_path);
        }
        //删除临时文件
        @unlink($tmp_file_path);
    }

    private function chkIsFileOwner($mainId, $type) {
        switch ($type) {
            case 1:
                if ($this->user["usertype"] == 2) {
                    $user_id = $this->user["uid"];
                    $talent_info = Db::table("new_talent_info")->findOrEmpty($mainId);
                    if ($user_id == $talent_info["enterprise_id"])
                        return true;
                }
                break;
        }
        return false;
    }

    public function getCompanyKvs() {
        $companys = \app\common\model\Company::field("name,id")->select();
        return json($companys);
    }

}
