<?php

namespace app\admin\controller;

use app\admin\common\AdminController;
use app\common\model\TalentBasicChange as TbcModel;
use app\common\api\DictApi;
use app\common\state\MainState;
use app\common\model\TalentLog;
use app\common\state\ProjectState;
use think\facade\Db;

/**
 * Description of TalentBasicChange
 *
 * @author sgq
 */
class TalentBasicChange extends AdminController {

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

    public function list() {
        $params = $this->request->param();
        $offset = $params["offset"] ?: 0;
        $order = $params["order"] ?: "desc";
        $limit = $params["limit"] ?: 10;
        $where = $this->setTalentBasic($params);
        $where[] = ["type", "=", $this->user["type"]];
        $where[] = ["delete", "=", 0];
        $count = TbcModel::where($where)->count();
        $list = TbcModel::where($where)->limit($offset, $limit)->order("createTime {$order}")->select()->toArray();
        $nationalityMap = DictApi::selectByParentCode("nationality");
        $nationMap = DictApi::selectByParentCode("nation");
        $politicalMap = DictApi::selectByParentCode("politics");
        $cardTypeMap = DictApi::selectByParentCode("card_type");
        $epMaps = \app\common\model\Enterprise::column("name", "id");
        foreach ($list as $key => $item) {
            $list[$key]["oldNationalityName"] = $nationalityMap[$item["oldNationality"]];
            $list[$key]["oldNationName"] = $nationMap[$item["oldNation"]];
            $list[$key]["oldPoliticsName"] = $politicalMap[$item["oldPolitics"]];
            $list[$key]["oldCardTypeName"] = $cardTypeMap[$item["oldCardType"]];
            $list[$key]["newNationalityName"] = $nationalityMap[$item["newNationality"]];
            $list[$key]["newNationName"] = $nationMap[$item["newNation"]];
            $list[$key]["newPoliticsName"] = $politicalMap[$item["newPolitics"]];
            $list[$key]["newCardTypeName"] = $cardTypeMap[$item["newCardType"]];
            $list[$key]["enterpriseName"] = $epMaps[$item["enterpriseId"]];
            if ($item["checkState"] == -1) {
                $list[$key]["checkStateName"] = "待提交";
            }
            if ($item["checkState"] == 1) {
                $list[$key]["checkStateName"] = "待审核";
            }
            if ($item["checkState"] == 2) {
                $list[$key]["checkStateName"] = "审核驳回";
            }
            if ($item["checkState"] == 3) {
                $list[$key]["checkStateName"] = "已通过";
            }
            if ($item["checkState"] == 9) {
                $list[$key]["checkStateName"] = "重新提交";
            }
        }

        return json(["rows" => $list, "total" => $count]);
    }

    public function check() {
        $id = $this->request["id"];
        $info = TbcModel::where("id", $id)->find();
        return view("check", ["type" => $this->user["type"], "row" => $info]);
    }

    public function submitToCheck() {
        $responseObj = new \stdClass();
        $responseObj->code = 500;
        $id = $this->request["id"];
        $checkState = $this->request["checkState"];
        $checkMsg = $this->request["checkMsg"];
        $info = TbcModel::where("id", $id)->find();
        if (!$info) {
            $responseObj->msg = "系统错误，请联系管理员";
            return $responseObj;
        }
        if (strlen($info["talentId"]) == 19) {
            //旧系统申请兼容处理
            unset($where);
            $where[] = ["enterprise_id", "=", $info["enterpriseId"]];
            $where[] = ["card_type", "=", $info["oldCardType"]];
            $where[] = ["card_number", "=", $info["oldIdCard"]];
            $where[] = ["checkState", "=", \app\common\api\TalentState::CERTIFICATED];
            $where[] = ["active", "=", 1];
            $where[] = ["delete", "=", 0];
            $ti = \app\enterprise\model\Talent::where($where)->order("createTime desc")->find();
            if (!$ti) {
                $responseObj->msg = "未匹配到人才数据";
                return $responseObj;
            }
            $info["talentId"] = $ti["id"];
        }
        if (!$checkState) {
            $responseObj->msg = "请选择审核状态";
            return $responseObj;
        }
        Db::startTrans();
        try {
            //添加日志
            $user = $this->user;
            $log["id"] = getStringId();
            $log["active"] = 1;
            $log["state"] = $checkState;
            $log["step"] = 11;
            $log["stateChange"] = MainState::getStateName($info["checkState"]) . "->" . MainState::getStateName($checkState);
            $log["type"] = ProjectState::BASICCHANGE;
            $log["mainId"] = $id;
            $log["description"] = $checkMsg;
            $log["createUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
            $log["createTime"] = date("Y-m-d H:i:s");
            $updTalentBasic["id"] = $id;
            $updTalentBasic["checkState"] = $checkState;
            $updTalentBasic["checkMsg"] = $checkMsg;
            if ($checkState == 3) {
                //修改人才库信息
                $upd["id"] = $info["talentId"];
                $upd["name"] = $info["newName"];
                $upd["birthday"] = $info["newBirthday"];
                $upd["nationality"] = $info["newNationality"];
                $upd["nation"] = $info["newNation"];
                $upd["politics"] = $info["newPolitics"];
                $upd["card_type"] = $info["newCardType"];
                $upd["card_number"] = $info["newIdCard"];
                $upd["email"] = $info["newEmail"];
                $upd["labor_contract_rangetime"] = $info["newContractStartTime"] . " - " . $info["newContractEndTime"];
                Db::table("new_talent_info")->save($upd);

                $talentLog["id"] = getStringId();
                $talentLog["active"] = 1;
                $talentLog["step"] = 24;
                $talentLog["type"] = ProjectState::TALENT;
                $talentLog["mainId"] = $info["talentId"];
                $talentLog["description"] = "基础信息变更通过，同步到人才库";
                $talentLog["createUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                $talentLog["createTime"] = date("Y-m-d H:i:s");
                Db::table("new_talent_checklog")->insert($talentLog);
            }
            Db::table("new_talent_checklog")->insert($log);
            Db::table("un_talent_basic_change")->save($updTalentBasic);
            $responseObj->code = 200;
            $responseObj->msg = "审核成功";

            Db::commit();
            return $responseObj;
        } catch (\think\db\exception\DbException $e) {
            $responseObj->msg = $e->getMessage();
            Db::rollback();
            return $responseObj;
        }
    }

    public function export() {
        $request = $this->request;
        $data["enterpriseName"] = \StrUtil::getRequestDecodeParam($request, "enterpriseName");
        $data["oldName"] = \StrUtil::getRequestDecodeParam($request, "oldName");
        $data["oldCardType"] = \StrUtil::getRequestDecodeParam($request, "oldCardType");
        $data["oldIdCard"] = \StrUtil::getRequestDecodeParam($request, "oldIdCard");
        $data["newName"] = \StrUtil::getRequestDecodeParam($request, "newName");
        $data["newCardType"] = \StrUtil::getRequestDecodeParam($request, "newCardType");
        $data["newIdCard"] = \StrUtil::getRequestDecodeParam($request, "newIdCard");
        $data["checkState"] = \StrUtil::getRequestDecodeParam($request, "checkState");
        $where = $this->setTalentBasic($data);
        $where[] = ["type", "=", $this->user["type"]];
        $where[] = ["delete", "=", 0];

        $list = TbcModel::where($where)->select()->toArray();
        $nationalityMap = DictApi::selectByParentCode("nationality");
        $nationMap = DictApi::selectByParentCode("nation");
        $politicalMap = DictApi::selectByParentCode("politics");
        $cardTypeMap = DictApi::selectByParentCode("card_type");
        $epMaps = \app\common\model\Enterprise::column("name", "id");

        $title = ["申报单位", "原姓名", "原出生日期", "原国家/地区", "原民族", "原政治面貌", "原证件类型", "原证件号码", "原电子邮箱", "原劳动合同起止时间",
            "现姓名", "现出生日期", "现国家/地区", "现民族", "现政治面貌", "现证件类型", "现证件号码", "现电子邮箱", "现劳动合同起止时间", "首次提交时间", "最新提交时间", "审核状态"];
        $keys = ["enterpriseName", "oldName", "oldBirthday", "oldNationalityName", "oldNationName", "oldPoliticsName", "oldCardTypeName", "oldIdCard", "oldEmail", "oldContractTime",
            "newName", "newBirthday", "newNationalityName", "newNationName", "newPoliticsName", "newCardTypeName", "newIdCard", "newEmail", "newContractTime", "firstSubmitTime", "newSubmitTime", "checkStateName"];
        $rows = [];
        foreach ($list as &$item) {
            $item["oldNationalityName"] = $nationalityMap[$item["oldNationality"]];
            $item["oldNationName"] = $nationMap[$item["oldNation"]];
            $item["oldPoliticsName"] = $politicalMap[$item["oldPolitics"]];
            $item["oldCardTypeName"] = $cardTypeMap[$item["oldCardType"]];
            $item["newNationalityName"] = $nationalityMap[$item["newNationality"]];
            $item["newNationName"] = $nationMap[$item["newNation"]];
            $item["newPoliticsName"] = $politicalMap[$item["newPolitics"]];
            $item["newCardTypeName"] = $cardTypeMap[$item["newCardType"]];
            $item["enterpriseName"] = $epMaps[$item["enterpriseId"]];
            switch ($item["checkState"]) {
                case -1:
                    $item["checkStateName"] = "待提交";
                    break;
                case 1:
                    $item["checkStateName"] = "待审核";
                    break;
                case 2:
                    $item["checkStateName"] = "审核驳回";
                    break;
                case 3:
                    $item["checkStateName"] = "已通过";
                    break;
                case 9:
                    $item["checkStateName"] = "重新提交";
                    break;
            }
            $row = [];
            for ($i = 0; $i < count($keys); $i++) {
                $row[] = $item[$keys[$i]];
            }
            $rows[] = $row;
        }unset($item);

        if (!$rows) {
            return json(["msg" => "没有可导出的内容"]);
        }
        $fileName = "基础信息变更列表";
        export($title, $rows, $fileName);
    }

    private function setTalentBasic($talentBasicInfo) {
        $where = [];
        if (\StrUtil::isNotEmpAndNull($talentBasicInfo["enterpriseName"])) {
            $whr = [];
            $whr[] = ["name", "like", "%{$talentBasicInfo["enterpriseName"]}%"];
            $ids = \app\common\model\Enterprise::where($whr)->column("id");
            $where[] = ["enterpriseName", "in", $ids];
        }
        if (\StrUtil::isNotEmpAndNull($talentBasicInfo["oldName"])) {
            $where[] = ["oldName", "like", "%" . $talentBasicInfo["oldName"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($talentBasicInfo["oldCardType"])) {
            $where[] = ["oldCardType", "=", $talentBasicInfo["oldCardType"]];
        }
        if (\StrUtil::isNotEmpAndNull($talentBasicInfo["oldIdCard"])) {
            $where[] = ["oldIdCard", "like", "%" . $talentBasicInfo["oldIdCard"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($talentBasicInfo["newName"])) {
            $where[] = ["newName", "like", "%" . $talentBasicInfo["newName"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($talentBasicInfo["newCardType"])) {
            $where[] = ["newCardType", "=", $talentBasicInfo["newCardType"]];
        }
        if (\StrUtil::isNotEmpAndNull($talentBasicInfo["newIdCard"])) {
            $where[] = ["newIdCard", "like", "%" . $talentBasicInfo["newIdCard"] . "%"];
        }
        if ($talentBasicInfo["checkState"] != null) {
            $where[] = ["checkState", "=", $talentBasicInfo["checkState"]];
        }
        return $where;
    }

}
