<?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 app\common\api\TalentTypeChangeApi as ttcApi;
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"]);
        $params = $this->request->param();
        if ($params["id"]) {
            $info = ttcApi::getOne($params["id"]);
        }
        $year = $info["newYear"] ?: $params["year"];
        return view("apply", ['enterprise' => $enterprise, "info" => $info, 'year' => $year]);
    }

    public function view() {
        $params = $this->request->param();
        if ($params["id"]) {
            $info = ttcApi::getOne($params["id"]);
        }
        if ($info["enterpriseId"] != $this->user["uid"])
            $info = null;
        return view("", ["info" => $info]);
    }

    public function add() {
        $res = $this->dataCheck($this->request);
        if ($res !== true) {
            return $res;
        }
        $data = $this->request->param();
        if (strlen($data["talentId"]) == 19) {
            $where = [];
            $where[] = ["card_number", "=", $data["idCard"]];
            $where[] = ["checkState", "=", TalentState::CERTIFICATED];
            $where[] = ["delete", "=", 0];
            $talentInfo = Db::table("new_talent_info")->where($where)->order("talent_arrange asc")->find();
        } else {
            $talentInfo = TalentApi::getOne($data["talentId"]);
        }
        if (!$talentInfo || $talentInfo["checkState"] != TalentState::CERTIFICATED || $talentInfo["delete"] == 1) {
            return json(["msg" => "人才库中匹配不到该人才", "code" => 500]);
        }
        $condition_info = Db::table("new_talent_condition")->findOrEmpty($data["newIdentifyCondition"]);
        if (!$condition_info) {
            return json(["msg" => "新认定条件不存在", "code" => 500]);
        }

        if ($data["id"]) {
            $talentTypeChange = TalentTypeChangeModel::find($data["id"]);
            if (!$talentTypeChange)
                return json(["msg" => "不存在的变更记录", "code" => 500]);
            if ($talentTypeChange["checkState"] != MainState::SAVE && $talentTypeChange["checkState"] != MainState::FIRST_REJECT && $talentTypeChange["checkState"] != MainState::BEFORE_REJECT && $talentTypeChange["checkState"] != MainState::GENERAL_REJECT && $talentTypeChange["checkState"] != MainState::FIRST_REJECT_BRANCH) {
                return json(["msg" => "正在审核中，无法修改", "code" => 500]);
            }
            $data['updateUser'] = $this->user["uid"];
            $data['updateTime'] = date("Y-m-d H:i:s");
            TalentTypeChangeModel::update($data);
        } else {
            $data["id"] = getStringId();
            $data['checkState'] = MainState::SAVE;
            $data['basicState'] = MainState::BASIC_NEED;
            $data['isPublic'] = 1;
            $data['oldCertificateStartTime'] = $talentInfo["certificateGetTime"];
            $data['oldCertificateOutTime'] = $talentInfo["certificateExpireTime"];
            $data['oldIdentifyOutTime'] = $talentInfo["identifyExpireTime"];
            $data['createUser'] = $this->user["uid"];
            $data['createTime'] = date("Y-m-d H:i:s");
            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' => "<span class='label label-primary'>添加</span> ->" . MainState::getStateDesc($data['checkState']),
            'description' => '添加人才层次变更',
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => session('user')['account'] . "({$companyName})"
        ]);

        return json(["msg" => $data["id"] ? "修改成功" : "添加成功", "code" => 200, "obj" => ["id" => $data["id"], "checkState" => $data["checkState"]]]);
    }

    public function submitToCheck() {
        $response = new \stdClass();
        $response->code = 500;
        $id = $this->request["id"];
        $info = ttcApi::getOne($id);
        if (!$info) {
            $response->msg = "提交审核失败，请先填写基础信息";
            return $response;
        }
        if (!$info["talentId"]) {
            $response->msg = "没有对应的人才信息";
            return $response;
        }
        if (!$info["newIdentifyCondition"]) {
            $response->msg = "没有对应的认定条件";
            return $response;
        }
        if ($info["checkState"] != MainState::SAVE && $info["checkState"] != MainState::FIRST_REJECT && $info["checkState"] != MainState::BEFORE_REJECT && $info["checkState"] != MainState::FIRST_REJECT_BRANCH && $info["checkState"] != MainState::GENERAL_REJECT) {
            $response->msg = "不能重复提交审核";
            return $response;
        }
        $condition_info = Db::table("new_talent_condition")->findOrEmpty($info["newIdentifyCondition"]);
        if ($condition_info["bindFileTypes"]) {
            $whr[] = ["id", "in", $condition_info["bindFileTypes"]];
            $whr[] = ["must", "=", 1];
        }

        $where = [];
        $where[] = ["type", "=", $info["type"]];
        $where[] = ["project", "=", ProjectState::LEVELCHANGE];
        $where[] = ["active", "=", 1];
        $where[] = ["delete", "=", 0];

        if ($whr) {
            $filetypes = Db::table("new_common_filetype")->whereOr([$where, $whr])->order("sn asc")->select()->toArray();
        } else {
            $filetypes = Db::table("new_common_filetype")->where($where)->order("sn asc")->select()->toArray();
        }
        $sb = [];
        $sb[] = "以下为必传附件：";
        foreach ($filetypes as $filetype) {
            if ($filetype["must"] == 1) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["typeId", "=", $filetype["id"]];
                $count = Db::table("new_talent_file")->where($where)->count();
                if ($count == 0) {
                    $sb[] = $filetype["name"] . ";";
                }
            }
        }
        if (count($sb) > 1) {
            $response->msg = implode("<br>", $sb);
            return $response;
        }
        if (!$info["firstSubmitTime"]) {
            $data["firstSubmitTime"] = date("Y-m-d H:i:s");
        }
        $checkState = MainState::NEED_FIRST_CHECK;
        $ep = \app\common\api\EnterpriseApi::getOne($this->user["uid"]);
        if ($ep->isGeneral == 2 && \app\common\api\Nhc::hasGeneralHospital($ep->medicalCommunityId)) {
            //分院并且有总院
            $checkState = MainState::NEED_PRE_CHECK;
        }

        $data["newSubmitTime"] = date("Y-m-d H:i:s");
        $data["checkMsg"] = "";
        $data["files"] = "";
        $data["fields"] = "";
        $data["id"] = $id;
        $data["checkState"] = $checkState;
        TalentTypeChangeModel::update($data);
        $user = $this->user;
        $log["id"] = getStringId();
        $log["active"] = 1;
        $log["state"] = 1;
        $log["step"] = 0;
        $log["stateChange"] = MainState::getStateDesc($info['checkState']) . "->" . MainState::getStateDesc($data['checkState']);
        $log["type"] = ProjectState::LEVELCHANGE;
        $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");
        TalentChecklog::create($log);
        $response->code = 200;
        $response->msg = "提交审核成功";
        $response->obj = 3;
        return $response;
    }

    public function delete() {
        $response = new \stdClass();
        $response->code = 500;
        $info = TalentTypeChangeModel::where("id", $this->request["id"])->find();
        if ($info["checkState"] != MainState::SAVE) {
            $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;
    }

    /**
     * 审核列表页
     */
    public function examineCenter() {
        $tpl = "";
        switch ($this->user["type"]) {
            case \app\common\state\CommonConst::ENTERPRISE_WJ:
                $tpl = "/talent_type_change/examine_center"; //卫健医院
                break;
        }
        $where[] = ["medicalCommunityId", "=", $this->user["medicalCommunityId"]];
        $where[] = ["isGeneral", "=", 2];
        $assigns["enterprises"] = \app\common\api\EnterpriseApi::getSimpleList($where);
        return view($tpl, $assigns);
    }

    /**
     * 审核列表页
     */
    public function examineList() {
        $res = ttcApi::getHospitalExamineList($this->request);
        return json($res);
    }

    /**
     * 审核页面
     * @return type
     */
    public function toCheckPage() {
        $id = $this->request["id"];
        $info = ttcApi::getOne($id);
        $arrangeMap = DictApi::selectByParentCode("talent_arrange");
        $importMap = DictApi::selectByParentCode("import_way");
        $info["oldTalentArrangeName"] = $arrangeMap[$info["oldTalentArrange"]];
        $info["oldIntroductionModeName"] = $importMap[$info["oldIntroductionMode"]];
        $info["newTalentArrangeName"] = $arrangeMap[$info["newTalentArrange"]];
        $info["newIntroductionModeName"] = $importMap[$info["newIntroductionMode"]];
        $talentCatMap = DictApi::selectByParentCode("talent_condition_cats");
        if (strlen($info["oldIdentifyCondition"]) == 19) {
            $oldCondition = Db::table("un_identify_condition")->find($info["oldIdentifyCondition"]);
            $info["oldIdentifyConditionCH"] = $oldCondition["name"];
        } else {
            $oldCondition = \app\common\api\TalentConditionApi::getOne($info["oldIdentifyCondition"]);
            if ($oldCondition["talentLevelCat"]) {
                $info["oldIdentifyConditionCategoryName"] = $talentCatMap[$oldCondition["talentLevelCat"]];
            }
            $info["oldIdentifyConditionCH"] = $oldCondition["name"];
        }
        if (strlen($info["newIdentifyCondition"]) == 19) {
            $newCondition = Db::table("un_identify_condition")->find($info["newIdentifyCondition"]);
            $info["newIdentifyConditionCH"] = $newCondition["name"];
        } else {
            $newCondition = \app\common\api\TalentConditionApi::getOne($info["newIdentifyCondition"]);
            if ($newCondition["talentLevelCat"]) {
                $info["newIdentifyConditionCategoryName"] = $talentCatMap[$newCondition["talentLevelCat"]];
            }
            $info["newIdentifyConditionCH"] = $newCondition["name"];
        }
        return view("check", ["info" => $info]);
    }

    public function findFieldsAndFiles() {
        $response = new \stdClass();
        $response->code = 500;
        $params = $this->request->param();
        $id = $params["id"];
        $info = ttcApi::getOne($id);
        if (!$info) {
            $response->msg = "请选择需要修改的对象";
            return $response;
        }
        if ($info["checkState"] != MainState::GENERAL_REJECT) {
            $response->msg = "只能修改总院驳回的数据";
            return $response;
        }
        $talentInfo = \app\common\api\VerifyApi::getOne($info["talentId"]);
        if (!$talentInfo || $talentInfo["checkState"] != \app\common\api\TalentState::CERTIFICATED || $talentInfo["delete"] == 1) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        $fields = DictApi::getTalentTypeChangeFields($this->user["type"]);

        $field_tmp = [];
        if ($fields) {
            foreach ($fields as $key => $field) {
                $field_tmp[] = ["key" => $key, "value" => $field];
            }
        }
        $condition = \app\common\api\TalentConditionApi::getOne($info["newIdentifyCondition"]);
        $where = [];
        $whr = [];
        $where[] = ["project", "=", ProjectState::LEVELCHANGE];
        $where[] = ["active", "=", 1];
        $where[] = ["type", "=", $info["type"]];
        $where[] = ["isConditionFile", "<>", 1];
        $where[] = ["delete", "=", 0];
        if ($condition && $condition["bindFileTypes"]) {
            $companyWithFileType = array_filter(explode(";", $condition["companyWithFileType"]));
            $cfKv = [];
            for ($i = 0; $i < count($companyWithFileType); $i++) {
                $setting = explode(":", $companyWithFileType[$i]);
                $_companyId = $setting[0];
                $_files = explode(",", $setting[1]);
                $cfKv[$_companyId] = $_files;
            }
            $whr[] = ["id", "in", explode(",", $condition["bindFileTypes"])];
            $files = Db::table("new_common_filetype")->whereOr([$where, $whr])->order("sn asc")->select()->toArray();
            for ($i = 0; $i < count($files); $i++) {
                foreach ($cfKv as $_companyId => $_files) {
                    if (in_array($files[$i]["id"], $_files)) {
                        $company = getCacheById("Company", $_companyId);
                        $files[$i]["name"] .= sprintf("<span style='color:red;'>（%s）</span>", $company["name"]);
                        break;
                    }
                }
            }
        } else {
            $files = Db::table("new_common_filetype")->where($where)->order("sn asc")->select()->toArray();
        }
        $response->code = 200;
        $response->id = $id;
        $response->fileList = $files;
        $response->fieldList = $field_tmp;
        $response->select = [
            "files" => array_filter(explode(",", $info["files"])),
            "fields" => array_filter(explode(",", $info["fields"]))
        ];
        return $response;
    }

    public function updateFieldsAndFiles() {
        $response = new \stdClass();
        $response->code = 500;
        $params = $this->request->param();
        $info = ttcApi::getOne($params["id"]);
        if (!$info) {
            $response->msg = "请选择需要修改的对象";
            return $response;
        }
        if ($info["checkState"] != MainState::GENERAL_REJECT) {
            $response->msg = "只能修改总院驳回的数据";
            return $response;
        }
        $fields = array_filter(explode(",", $params["fields"]));
        $files = array_filter(explode(",", $params["files"]));
        if (!$fields && !$files) {
            $response->msg = "请选择驳回的字段或者附件";
            return $response;
        }
        $data["id"] = $params["id"];
        $data["fields"] = $fields ? implode(",", $fields) : "";
        $data["files"] = $files ? implode(",", $files) : "";
        if (TalentTypeChangeModel::update($data)) {
            $response->msg = "修改成功";
            $response->code = 200;
        } else {
            $response->msg = "修改失败";
        }
        return $response;
    }

    public function validateIsCheck() {
        $id = $this->request->param("id");
        $response = new \stdClass();
        $response->code = 500;
        $info = ttcApi::getOne($id);
        if (!$info || $info["delete"] == 1 || $info["type"] != $this->user["type"]) {
            $response->msg = "没有对应的人才变更记录";
            return $response;
        }
        if (!$info["talentId"]) {
            $response->msg = "没有对应的人才信息";
            return $response;
        }
        if (!$info["newIdentifyCondition"]) {
            $response->msg = "没有对应的认定条件";
            return $response;
        }
        $where = [];
        $where[] = ["active", "=", 0];
        $lastLog = [];
        if ($info["checkState"] != MainState::NEED_PRE_CHECK && $info["checkState"] != MainState::FIRST_REJECT) {
            $response->msg = "该申报不在审核范围内，无法审核";
        } else {
            $lastLog = TalentLogApi::getLastLogEx($id, ProjectState::LEVELCHANGE, 0, $where);
            $response->code = 200;
        }
        if ($response->code == 200) {
            if ($lastLog) {
                $info["checkState"] = $lastLog["state"];
                $info["checkMsg"] = $lastLog["description"];
            } else {
                $info["checkState"] = null;
                $info["checkMsg"] = "";
            }
            $response->data = $info;

            $condition = \app\common\api\TalentConditionApi::getOne($info["newIdentifyCondition"]);
            $whrFile = [];
            $whrOr = [];
            $whrFile[] = ["project", "=", ProjectState::LEVELCHANGE];
            $whrFile[] = ["active", "=", 1];
            $whrFile[] = ["type", "=", $info["type"]];
            $whrFile[] = ["isConditionFile", "<>", 1];
            $whrFile[] = ["delete", "=", 0];
            if ($condition && $condition["bindFileTypes"]) {
                $companyWithFileType = array_filter(explode(";", $condition["companyWithFileType"]));
                $cfKv = [];
                for ($i = 0; $i < count($companyWithFileType); $i++) {
                    $setting = explode(":", $companyWithFileType[$i]);
                    $_companyId = $setting[0];
                    $_files = explode(",", $setting[1]);
                    $cfKv[$_companyId] = $_files;
                }
                $whrOr[] = ["id", "in", explode(",", $condition["bindFileTypes"])];
                $files = \app\common\model\FileType::whereOr([$whrFile, $whrOr])->order("sn asc")->select()->toArray();
                for ($i = 0; $i < count($files); $i++) {
                    foreach ($cfKv as $_companyId => $_files) {
                        if (in_array($files[$i]["id"], $_files)) {
                            $company = getCacheById("Company", $_companyId);
                            $files[$i]["name"] .= sprintf("<span style='color:red;'>（%s）</span>", $company["name"]);
                            break;
                        }
                    }
                }
            } else {
                $files = \app\common\model\FileType::where($whrFile)->order("sn asc")->select()->toArray();
            }
            $response->fileList = $files;

            $fieldList = DictApi::getTalentTypeChangeFields($info["type"]);
            $field_tmp = [];
            foreach ($fieldList as $key => $field) {
                $field_tmp[] = ["key" => $key, "value" => $field];
            }
            $response->fieldList = $field_tmp;
        }
        return $response;
    }

    public function check() {
        $response = new \stdClass();
        $response->code = 500;
        $talentTypeChange = $this->request->param();
        $id = $talentTypeChange["id"];
        $process = -2;
        $checkState = $talentTypeChange["checkState"];
        $checkMsg = $talentTypeChange["checkMsg"];
        $fields = $talentTypeChange["fields"];
        $files = $talentTypeChange["files"];
        Db::startTrans();
        try {
            if (!$checkState) {
                $response->msg = "请选择审核状态";
                return $response;
            }
            $upd["id"] = $id;
            $upd["fields"] = $fields;
            $upd["files"] = $files;
            Db::table("un_talent_type_change")->update($upd);
            $where[] = ["active", "=", "0"];
            $where[] = ["step", "=", $process];
            $lastLog = TalentLogApi::getLastLogEx($id, ProjectState::LEVELCHANGE, 0, $where);
            $user = $this->user;

            $log["active"] = 0;
            $log["state"] = $checkState;
            $log["step"] = $process;
            $log["companyId"] = $user["companyId"];
            $log["stateChange"] = "保存未提交";
            $log["type"] = ProjectState::LEVELCHANGE;
            $log["mainId"] = $id;
            $log["description"] = $checkMsg;
            if ($lastLog) {
                $log["id"] = $lastLog["id"];
                $log["updateUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                $log["updateTime"] = date("Y-m-d H:i:s");
                Db::table("new_talent_checklog")->update($log);
            } else {
                $log["id"] = getStringId();
                $log["createUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                $log["createTime"] = date("Y-m-d H:i:s");
                Db::table("new_talent_checklog")->insert($log);
            }
            Db::commit();
            $response->msg = "审核成功";
            $response->code = 200;
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "审核失败：" . $e->getMessage();
            return $response;
        }
    }

    public function submitCheck() {
        $response = new \stdClass();
        $response->code = 500;
        $talentTypeChange = $this->request->param();
        $id = $talentTypeChange["id"];
        $companyId = $talentTypeChange["companyId"];
        $process = -2;
        $where = [];
        $where[] = ["active", "=", "0"];
        $where[] = ["step", "=", $process];
        $lastLog = TalentLogApi::getLastLogEx($id, ProjectState::LEVELCHANGE, 0, $where);
        if (!$lastLog) {
            $response->msg = "请先审核后再提交";
            return $response;
        }
        $checkState = $lastLog["state"];
        $checkMsg = $lastLog["description"];
        $data["id"] = $id;
        $data["checkMsg"] = $checkMsg;
        $old = ttcApi::getOne($id);
        //判断到达的最高流程
        $data["highProcess"] = !$old["highProcess"] ? $process : ($old["highProcess"] < $process ? $process : $old["highProcess"]);

        $user = $this->user;
        Db::startTrans();
        try {
            if ($checkState == -1) {
                $data["checkState"] = MainState::NOTPASS;
            }
            if ($checkState == 2) {
                $data["checkState"] = MainState::GENERAL_REJECT;
            }
            if ($checkState == 3) {
                $data["checkState"] = MainState::NEED_FIRST_CHECK;
                $data["firstBeforeSubmitTime"] = date("Y-m-d H:i:s");
            }
            $log["id"] = $lastLog["id"];
            $log["active"] = 1;
            $log["state"] = 8;
            $log["stateChange"] = MainState::getStateDesc($old["checkState"]) . "->" . MainState::getStateDesc($data["checkState"]);
            $log["updateUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
            $log["updateTime"] = date("Y-m-d H:i:s");
            Db::table("new_talent_checklog")->update($log);
            Db::table("un_talent_type_change")->update($data);
            Db::commit();
            $response->msg = "提交审核成功";
            $response->code = 200;
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "提交审核失败：" . $e->getMessage();
            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]);
        }
        if ($type == 2) {
            if (\StrUtil::isEmpOrNull($data->param('newIdentifyGetTime'))) {
                return json(["msg" => "新认定条件名称不能为空", "code" => 500]);
            }
        }
        if (\StrUtil::isEmpOrNull($data->param('newIdentifyGetTime'))) {
            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) and `delete`<>1')->find();

        if ($res) {
            return json(["msg" => "添加失败，该证件号码已申报", "code" => 500]);
        }
        return true;
    }

}
