<?php

namespace app\admin\controller;

use app\admin\common\AdminController;
use app\common\model\TalentWorkUnitChange as TwcModel;
use app\common\api\DictApi;
use app\common\state\MainState;
use app\common\model\TalentLog;
use app\common\state\ProjectState;
use think\facade\Db;
use app\common\api\EnterpriseApi;

/**
 * Description of TalentWorkUnitChange
 *
 * @author sgq
 */
class TalentWorkUnitChange 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->setTalentWorkunitChange($params);
        $where[] = ["type", "=", $this->user["type"]];
        $where[] = ["delete", "=", 0];
        //获取字典表人才层次
        $levelMap = DictApi::selectByParentCode("talent_arrange");
        $epMaps = \app\common\model\Enterprise::column("name", "id");
        $count = TwcModel::where($where)->count();
        $list = TwcModel::where($where)->limit($offset, $limit)->order("createTime {$order}")->select()->toArray();
        foreach ($list as $key => $item) {
            $list[$key]["talentArrangeName"] = $levelMap[$item["talentArrange"]];
            $list[$key]["oldEnterpriseName"] = $epMaps[$item["oldEnterpriseId"]];
            $list[$key]["newEnterpriseName"] = $epMaps[$item["newEnterpriseId"]];
            if ($item["checkState"] == -2) {
                $list[$key]["checkStateName"] = "审核不通过";
            }
            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 = TwcModel::where("id", $id)->find();
        $info["talentArrangeName"] = DictApi::selectByParentCode("talent_arrange")[$info["talentArrange"]];
        $epOld = EnterpriseApi::getOne($info["oldEnterpriseId"]);
        $epNew = EnterpriseApi::getOne($info["newEnterpriseId"]);
        $info["oldEnterpriseName"] = $epOld["name"];
        $info["newEnterpriseName"] = $epNew["name"];
        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 = TwcModel::where("id", $id)->find();
        if (!$info) {
            $responseObj->msg = "系统错误，请联系管理员";
            return $responseObj;
        }
        if (strlen($info["talentId"]) == 19) {
            //旧系统申请兼容处理
            unset($where);
            $where[] = ["enterprise_id", "=", $info["oldEnterpriseId"]];
            $where[] = ["card_number", "=", $info["idCard"]];
            $where[] = ["checkState", "=", \app\common\api\TalentState::CERTIFICATED];
            $where[] = ["active", "=", 2];
            $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;
        }
        $tmpState = $checkState == -2 ? -1 : $checkState;
        Db::startTrans();
        try {
            //添加日志
            $user = $this->user;
            $log["id"] = getStringId();
            $log["active"] = 1;
            $log["state"] = $tmpState;
            $log["step"] = 11;
            $log["stateChange"] = MainState::getStateName($info["checkState"]) . "->" . MainState::getStateName($tmpState);
            $log["type"] = ProjectState::WORKCHANGE;
            $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");
            $updWorkChange["id"] = $id;
            $updWorkChange["checkState"] = $checkState;
            $updWorkChange["checkMsg"] = $checkMsg;
            if ($checkState == 3) {
                //修改人才库信息
                $upd["id"] = $info["talentId"];
                $upd["enterprise_id"] = $info["newEnterpriseId"];
                $upd["labor_contract_rangetime"] = $info["starttime"] . " - " . $info["endtime"];
                $upd["cur_entry_time"] = $info["anyTime"];
                $upd["active"] = 1;
                $upd["cur_quit_time"] = null;
                $upd["position"] = $info["newPost"];
                Db::table("new_talent_info")->save($upd);

                $talentLog["id"] = getStringId();
                $talentLog["active"] = 1;
                $talentLog["step"] = 21;
                $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);
                $updWorkChange["passTime"] = date("Y-m-d H:i:s");
            }
            Db::table("new_talent_checklog")->insert($log);
            Db::table("un_talent_workunit_change")->save($updWorkChange);
            $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["talentName"] = \StrUtil::getRequestDecodeParam($request, "talentName");
        $data["idCard"] = \StrUtil::getRequestDecodeParam($request, "idCard");
        $data["oldEnterpriseName"] = \StrUtil::getRequestDecodeParam($request, "oldEnterpriseName");
        $data["newEnterpriseName"] = \StrUtil::getRequestDecodeParam($request, "newEnterpriseName");
        $data["checkState"] = \StrUtil::getRequestDecodeParam($request, "checkState");
        $where = $this->setTalentWorkunitChange($data);
        $where[] = ["type", "=", $this->user["type"]];
        $where[] = ["delete", "=", 0];

        $list = TwcModel::where($where)->select()->toArray();
        $levelMap = DictApi::selectByParentCode("talent_arrange");
        $epMaps = \app\common\model\Enterprise::column("name", "id");

        if ($this->user["type"] == 1) {
            $title = ["姓名", "证件号码", "人才层次", "原工作单位", "离职时间", "离职申报原因", "新工作单位",
                "合同开始时间", "合同结束时间", "入职/变更时间", "单位变更申报原因", "手机号码", "审核状态", "审核意见", "审核通过时间"];
            $keys = ["talentName", "idCard", "talentArrangeName", "oldEnterpriseName", "quitTime", "quitReason", "newEnterpriseName",
                "starttime", "endtime", "anyTime", "anyReason", "phone", "checkStateName", "checkMsg", "passTime"];
        } else {
            $title = ["姓名", "证件号码", "人才层次", "原工作单位", "离职时间", "新工作单位",
                "合同开始时间", "合同结束时间", "入职/变更时间", "手机号码", "审核状态", "审核意见", "审核通过时间"];
            $keys = ["talentName", "idCard", "talentArrangeName", "oldEnterpriseName", "quitTime", "newEnterpriseName",
                "starttime", "endtime", "anyTime", "phone", "checkStateName", "checkMsg", "passTime"];
        }
        $rows = [];
        foreach ($list as &$item) {
            $item["talentArrangeName"] = $levelMap[$item["talentArrange"]];
            $item["oldEnterpriseName"] = $epMaps[$item["oldEnterpriseId"]];
            $item["newEnterpriseName"] = $epMaps[$item["newEnterpriseId"]];
            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 setTalentWorkunitChange($twcInfo) {
        $where = [];
        if (\StrUtil::isNotEmpAndNull($twcInfo["talentName"])) {
            $where[] = ["talentName", "=", $twcInfo["talentName"]];
        }
        if (\StrUtil::isNotEmpAndNull($twcInfo["idCard"])) {
            $where[] = ["idCard", "=", $twcInfo["IdCard"]];
        }
        if (\StrUtil::isNotEmpAndNull($twcInfo["oldEnterpriseName"])) {
            $whr = [];
            $whr[] = ["name", "like", "%{$params["oldEnterpriseName"]}%"];
            $ids = \app\common\model\Enterprise::where($whr)->column("id");
            $where[] = ["oldEnterpriseId", "in", $ids];
        }
        if (\StrUtil::isNotEmpAndNull($twcInfo["newEnterpriseName"])) {
            $whr = [];
            $whr[] = ["name", "like", "%{$params["newEnterpriseName"]}%"];
            $ids = \app\common\model\Enterprise::where($whr)->column("id");
            $where[] = ["newEnterpriseId", "in", $ids];
        }
        if ($twcInfo["checkState"] != null) {
            $where[] = ["checkState", "=", $talentQuitInfo["checkState"]];
        }
        return $where;
    }

}
