<?php

namespace app\enterprise\controller;

use app\common\api\EnterpriseApi;
use app\common\api\TalentLogApi;
use app\common\api\TalentState;
use app\common\model\TalentChecklog;
use app\common\state\MainState;
use app\common\state\ProjectState;
use app\enterprise\common\EnterpriseController;
use app\enterprise\api\TalentApi;
use app\common\api\DictApi;
use app\common\api\VerifyApi;
use app\Request;
use app\enterprise\model\TalentTypeChange as TalentTypeChangeModel;
use think\facade\Db;

/**
 * Description of TalentTypeChange
 *
 * @author sgq
 */
class TalentTypeChange extends EnterpriseController {

    public function index() {
        return view("", ["type" => $this->user["type"]]);
    }

    public function list() {
        $res = TalentApi::getTypeChangeList($this->request);
        return json($res);
    }

    public function apply() {
        $enterprise = EnterpriseApi::getOne($this->user["uid"]);
        $year = $this->request->param('year');
        return view("apply", ['enterprise' => $enterprise, 'year' => $year]);
    }

    public function view() {
        return view();
    }

    public function add() {
        $res = $this->dataCheck($this->request);
        if (!$res) {
            return json(["msg" => "添加失败，该证件号码已申报", "code" => 500]);
        }
        $data = $this->request->param();
        $data['checkState'] = TalentState::BASIC_SAVE;
        $data['basicState'] = TalentState::BASIC_NEED;
        $data['isPublic'] = 1;
        $data['createUser'] = $this->user["uid"];
        $data['createTime'] = date("Y-m-d H:i:s");
        $condition_info = Db::table("new_talent_condition")->findOrEmpty($data["newIdentifyCondition"]);
        if (!$condition_info) {
            return json(["msg" => "新认定条件不存在", "code" => 500]);
        }

        TalentTypeChangeModel::create($data);
        $companyName = session('user')["companyName"] ?: session('user')["rolename"];

        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $data['id'],
            'type' => intval(ProjectState::LEVELCHANGE),
            'typeFileId' => null,
            'active' => 1,
            'state' => null,
            'step' => 0,
            'stateChange' => TalentState::stateEnum(-2),
            'description' => '添加人才层次变更',
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => session('user')['name'] . "({$companyName})"
        ]);

        return json(["msg" => "添加成功", "code" => 200]);
    }

    public function submitToCheck() {
        $response = new \stdClass();
        $response->code = 500;
        $id = $this->request["id"];
        $info = TalentTypeChangeModel::where("id", $id)->find();
        if (!$info) {
            $response->msg = "提交审核失败，请先填写基础信息";
            return $response;
        }
        if ($info["checkState"] != -1 && $info["checkState"] != 10 && $info["checkState"] != 5) {
            $response->msg = "不能重复提交审核";
            return $response;
        }
        $where = [];
        $where[] = ["type", "=", $info["type"]];
        $where[] = ["project", "=", ProjectState::LEVELCHANGE];
        $where[] = ["active", "=", 1];
        $filetypes = Db::table("new_common_filetype")->where($where)->order("sn asc")->select()->toArray();
        foreach ($filetypes as $filetype) {
            $sb = [];
            $sb[] = "以下为必传附件：";
            if ($filetype["must"] == 1) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["typeId", "=", $filetype["id"]];
                $count = Db::table("new_talent_common_file")->where($where)->count();
                if ($count == 0) {
                    $sb[] = $filetype["name"] . ";";
                }
            }
        }
        if (count($sb) > 1) {
            $response->msg = implode("<br>", $sb);
            return $response;
        }
        $data["id"] = $id;
        $data["checkState"] = $info["checkState"] == 2 ? 9 : 1;
        TqModel::update($data);
        $user = $this->user;
        $log["id"] = getStringId();
        $log["active"] = 1;
        $log["state"] = 1;
        $log["step"] = 0;
        $log["stateChange"] = "<span class='label'>待提交</span>-><span class='label label-success'>待审核</span>";
        $log["type"] = ProjectState::QUIT;
        $log["mainId"] = $id;
        $log["description"] = "确认提交审核";
        $log["createUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
        $log["createTime"] = date("Y-m-d H:i:s");
        TalentLog::create($log);
        $response->code = 200;
        $response->msg = "提交审核成功";
        $response->obj = 1;
        return $response;
    }

    public function delete() {
        $response = new \stdClass();
        $response->code = 500;
        $info = TalentTypeChangeModel::where("id", $this->request["id"])->find();
        if ($info["checkState"] != -1) {
            $response->msg = "已提交审核，无法删除";
            return $response;
        }
        $data["id"] = $info["id"];
        $data["delete"] = 1;
        $data["deleteTime"] = date("Y-m-d H:i:s");
        TalentTypeChangeModel::update($data);
        $response->code = 200;
        $response->msg = "删除成功";
        return $response;
    }

    private function dataCheck($data) {
        $type = $data->param('type');
        if ($type == 1) {
            
        }
        if (\StrUtil::isEmpOrNull($data->param('newTalentArrange'))) {
            return json(["msg" => "新人才层次不能为空", "code" => 500]);
        }
        if (\StrUtil::isEmpOrNull($data->param('newIdentifyCondition'))) {
            return json(["msg" => "新人才层次不能为空", "code" => 500]);
        }
        $res = TalentTypeChangeModel::where('idCard', $data->param('idCard'))->where('id', '<>', $data->param('id'))->whereRaw('isPublic <> 6 and (isPublic <> 5 or checkState <> -1)')->findOrEmpty();
        if ($res) {
            return true;
        } else {
            return false;
        }
    }

}
