<?php

namespace app\enterprise\controller;

use app\common\api\TalentState;
use app\enterprise\api\TalentApi;
use app\enterprise\common\EnterpriseController;
use app\common\model\TalentBasicChange as TbcModel;
use app\common\api\TalentLogApi;
use app\common\state\ProjectState;
use app\common\model\TalentLog;
use app\enterprise\model\Talent;
use think\facade\Db;
use app\common\api\EnterpriseApi;

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

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

    public function list() {
        $type = $this->user["type"];
        $params = \StrUtil::batchGetRequestDecodeParam($this->request);
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;
        $where = [];
        $where[] = ["enterpriseId", "=", $this->user["uid"]];
        $where[] = ["delete", "=", 0];
        if ($params["oldName"]) {
            $where[] = ["oldName", "like", "%" . $params["oldName"] . "%"];
        }
        if ($params["oldCardType"]) {
            $where[] = ["oldCardType", "=", $params["oldCardType"]];
        }
        if ($params["oldIdCard"]) {
            $where[] = ["oldIdCard", "like", "%" . $params["oldIdCard"] . "%"];
        }
        if ($params["newName"]) {
            $where[] = ["newName", "like", "%" . $params["newName"] . "%"];
        }
        if ($params["newCardType"]) {
            $where[] = ["newCardType", "=", $params["newCardType"]];
        }
        if ($params["newIdCard"]) {
            $where[] = ["newIdCard", "like", "%" . $params["newIdCard"] . "%"];
        }
        if ($params["checkState"]) {
            $where[] = ["checkState", "=", $params["checkState"]];
        }
        $count = TbcModel::where($where)->count();
        $list = TbcModel::where($where)->limit($offset, $limit)->order("createTime " . $order)->select()->toArray();
        $nationalityMap = \app\common\api\DictApi::selectByParentCode("nationality");
        $nationMap = \app\common\api\DictApi::selectByParentCode("nation");
        $politicalMap = \app\common\api\DictApi::selectByParentCode("politics");
        $cardTypeMap = \app\common\api\DictApi::selectByParentCode("card_type");
        foreach ($list as &$item) {
            $item["oldNationalityName"] = $nationalityMap[$item["oldNationality"]];
            $item["oldNationName"] = $nationMap[$item["oldNation"]];
            $item["oldPoliticsName"] = $politicalMap[$item["oldPolitics"]];
            $item["oldCardTypName"] = $cardTypeMap[$item["oldCardType"]];
            $item["newNationalityName"] = $nationalityMap[$item["newNationality"]];
            $item["newNationName"] = $nationMap[$item["newNation"]];
            $item["newPoliticsName"] = $politicalMap[$item["newPolitics"]];
            $item["newCardTypName"] = $cardTypeMap[$item["newCardType"]];
        }unset($item);

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

    public function apply() {
        $request = $this->request;
        $id = isset($request["id"]) ? $request["id"] : 0;
        $talent_id = isset($request["talent_id"]) ? $request["talent_id"] : 0;
        $info = TbcModel::where("id", $id)->find();
        if ($this->request->isPost()) {
            $response = new \stdClass();
            $response->code = 500;
            $data = $request->param();
            $check = $this->dataCheck($data);
            if ($check->code == 500) {
                return $check;
            }
            $talentInfo = \app\common\api\VerifyApi::getTalentInfoById($request["talentId"]);
            if ($data["id"]) {
                unset($data["year"]);
                $data["updateUser"] = $this->user["uid"];
                $data["updateTime"] = date("Y-m-d H:i:s");
                TbcModel::update($data);
                $response->code = 200;
                $response->msg = "修改成功";
                return $response;
            } else {
                $data["id"] = getStringId();
                $data["oldName"] = $talentInfo["name"];
                $data["oldNationality"] = $talentInfo["nationality"];
                $data["oldNation"] = $talentInfo["nation"];
                $data["oldPolitics"] = $talentInfo["politics"];
                $data["oldCardType"] = $talentInfo["card_type"];
                $data["oldIdCard"] = $talentInfo["card_number"];
                $data["oldBirthday"] = $talentInfo["birthday"];
                $data["oldEmail"] = $talentInfo["email"];
                $data["oldContractTime"] = $talentInfo["labor_contract_rangetime"];
                $data["checkState"] = -1;
                $data["createUser"] = $this->user["uid"];
                $data["createTime"] = date("Y-m-d H:i:s");
                TbcModel::create($data);

                $user = $this->user;
                $log["id"] = getStringId();
                $log["active"] = 1;
                $log["state"] = 1;
                $log["step"] = 0;
                $log["stateChange"] = "";
                $log["type"] = ProjectState::BASICCHANGE;
                $log["mainId"] = $data["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 = $data;
                return $response;
            }
        }
        $assigns = [];
        if (!$info) {
            $info["enterpriseId"] = $this->user["uid"];
            $info["type"] = $this->user["type"];
            $where = [];
            $where[] = ["checkState", "<>", 3];
            $changes = TbcModel::where($where)->select()->column("talentId");
            unset($where);
            $where[] = ["enterprise_id", "=", $this->user["uid"]];
            $where[] = ["id", "not in", $changes];
            $where[] = ["checkState", "=", \app\common\api\TalentState::CERTIFICATED];

            $twiceIdentifyPersons = \app\common\api\VerifyApi::getTwiceIdentifyPersons();
            if ($twiceIdentifyPersons) {
                $_whr = $where;
                $where[] = ["card_number", "not in", $twiceIdentifyPersons];
                $_whr[] = ["card_number", "in", $twiceIdentifyPersons];
                $tmpList = \app\enterprise\model\Talent::where($_whr)->field("id,name")->select()->toArray();

                $twiceIdentifyPersonList = [];
                foreach ($tmpList as $person) {
                    if (!$twiceIdentifyPersonList[$person["card_number"]]) {
                        $twiceIdentifyPersonList[$person["card_number"]] = $person;
                    } else {
                        if ($person["talent_arrange"] < $twiceIdentifyPersonList[$person["card_number"]]["talent_arrange"]) {
                            $twiceIdentifyPersonList[$person["card_number"]] = $person;
                        }
                    }
                }
                sort($twiceIdentifyPersonList);
            }
            $list = \app\enterprise\model\Talent::where($where)->field("id,name")->select()->toArray();
            if ($twiceIdentifyPersonList) {
                $list = array_merge($twiceIdentifyPersonList, (array) $list);
            }
            $assigns["list"] = $list;
        }
        $assigns["type"] = $this->user["type"];
        $assigns["row"] = $info;
        $assigns['talent_id'] = $talent_id;
        return view("", $assigns);
    }

    public function view() {
        $request = $this->request;
        $id = isset($request["id"]) ? $request["id"] : 0;
        $info = TbcModel::where("id", $id)->find();
        return view("apply", ["row" => $info]);
    }

    public function submitToCheck() {
        $response = new \stdClass();
        $response->code = 500;
        $id = $this->request["id"];
        $info = TbcModel::where("id", $id)->find();
        if (!$info) {
            $response->msg = "提交审核失败，请先填写基础信息";
            return $response;
        }
        if ($info["checkState"] != -1 && $info["checkState"] != 2) {
            $response->msg = "不能重复提交审核";
            return $response;
        }
        $check = $this->dataCheck($info);
        if ($check->code == 500) {
            return $check;
        }
        $where = [];
        $where[] = ["type", "=", $info["type"]];
        $where[] = ["project", "=", ProjectState::BASICCHANGE];
        $where[] = ["active", "=", 1];
        $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;
        }
        $data["id"] = $id;

        if (\StrUtil::isEmpOrNull($info["firstSubmitTime"])) {
            $data["firstSubmitTime"] = date("Y-m-d H:i:s");
        }
        $data["newSubmitTime"] = date("Y-m-d H:i:s");
        $data["checkMsg"] = "";
        $data["checkState"] = $info["checkState"] == 2 ? 9 : 1;
        TbcModel::update($data);
        $sb = [];
        if ($info["checkState"] == -1) {
            $sb[] = \app\common\state\MainState::getStateName(-2);
        } else {
            $sb[] = \app\common\state\MainState::getStateName(2);
        }
        if ($data["checkState"] == 1) {
            $sb[] = \app\common\state\MainState::getStateName(1);
        } else {
            $sb[] = \app\common\state\MainState::getStateName(9);
        }

        $user = $this->user;
        $log["id"] = getStringId();
        $log["active"] = 1;
        $log["state"] = 1;
        $log["step"] = 0;
        $log["stateChange"] = implode("->", $sb);
        $log["type"] = ProjectState::BASICCHANGE;
        $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 = TbcModel::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");
        TbcModel::update($data);
        $response->code = 200;
        $response->msg = "删除成功";
        return $response;
    }

    private function dataCheck($data) {
        $response = new \stdClass();
        $response->code = 500;
        if (\StrUtil::isEmpOrNull($data["newName"])) {
            $response->msg = "现姓名不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newNationality"])) {
            $response->msg = "现国籍不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newNation"])) {
            $response->msg = "现民族不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newBirthday"])) {
            $response->msg = "现出生日期不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newPolitics"])) {
            $response->msg = "现政治面貌不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newCardType"])) {
            $response->msg = "现证件类型不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newIdCard"])) {
            $response->msg = "现证件号码不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newEmail"])) {
            $response->msg = "现电子邮箱不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newContractStartTime"])) {
            $response->msg = "现劳动合同开始时间不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newContractEndTime"])) {
            $response->msg = "现劳动合同结束时间不能为空";
            return $response;
        }
        if (!preg_match("/[\\w!#$%&'*+\/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+\/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?/", $data["newEmail"])) {
            $response->msg = "电子邮箱格式不正确";
            return $response;
        }
        if ($data["newCardType"] == 1 && !\app\common\api\IdCardApi::isValid($data["newIdCard"])) {
            $response->msg = "身份证号码不合法";
            return $response;
        }
        if ($data["newCardType"] == 2 && !preg_match("/^[a-zA-Z0-9]{6,10}$/", $data["newIdCard"]) && !preg_match("/^([0-9]{8}|[0-9]{10})$/", $data["newIdCard"])) {
            $response->msg = "通行证号码不合法";
            return $response;
        }
        if ($data["newCardType"] == 3 && !preg_match("/^([a-zA-z]|[0-9]){5,17}$/", $data["newIdCard"])) {
            $response->msg = "护照格式不合法";
            return $response;
        }
        //list($startTime, $endTime) = explode(" - ", $data["newContractTime"]);
        $startTime = $data["newContractStartTime"];
        $endTime = $data["newContractEndTime"];
        if (!strtotime($startTime) || !strtotime($endTime) || strtotime($startTime) > strtotime($endTime)) {
            $response->msg = "劳动合同起止时间不合法";
            return $response;
        }
        $response->code = 200;
        return $response;
    }

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

    public function htEndList() {
        $offset = trim($this->request->param("offset")) ?: 0;
        $limit = trim($this->request->param("limit")) ?: 10;
        $name = trim($this->request->param("name"));
        $idCard = trim($this->request->param("card_number"));
        $where = [];
        $where[] = ["ti.delete", "=", 0];
        $where[] = ["ti.active", "=", 1];
        $where[] = ["ti.checkState", "=", TalentState::CERTIFICATED];
        if (session("user")["usertype"] == 2) {
            $where[] = ["ti.enterprise_id", "=", session("user")["uid"]];
        }

        if ($name) {
            $where[] = ["ti.name", "like", "%" . $name . "%"];
        }
        if ($idCard) {
            $where[] = ["ti.card_number", "like", "%" . $idCard . "%"];
        }
        //dump($where);die;

        $now = date("Y-m-d", time());
        //$where[] = ["trim(SUBSTRING_INDEX(ti.labor_contract_rangetime,'-',-3))", "<", $now];


        $count = Talent::alias("ti")->field("ti.id,ti.name,ti.card_number,ti.labor_contract_rangetime")->leftJoin("un_talent_basic_change tbc", "ti.id = tbc.talentId")->where($where)->whereRaw("trim(SUBSTRING_INDEX(ti.labor_contract_rangetime,'-',-3)) < '{$now}' and tbc.id is null")->count();
        $list = Talent::alias("ti")->field("ti.id,ti.name,ti.card_number,ti.labor_contract_rangetime")->leftJoin("un_talent_basic_change tbc", "ti.id = tbc.talentId")->where($where)->whereRaw("trim(SUBSTRING_INDEX(ti.labor_contract_rangetime,'-',-3)) < '{$now}' and tbc.id is null")->limit($offset, $limit)->select()->toArray();
        //echo Talent::getLastSql();die;

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

    public function htEndExport() {
        $where = [];
        $where[] = ["ti.delete", "=", 0];
        $where[] = ["ti.active", "=", 1];
        $where[] = ["ti.checkState", "=", TalentState::CERTIFICATED];
        if (session("user")["usertype"] == 2) {
            $where[] = ["ti.enterprise_id", "=", session("user")["uid"]];
        }
        $now = date("Y-m-d", time());
        $count = Talent::alias("ti")->field("ti.id,ti.name,ti.card_number,ti.labor_contract_rangetime")->leftJoin("un_talent_basic_change tbc", "ti.id = tbc.talentId")->where($where)->whereRaw("trim(SUBSTRING_INDEX(ti.labor_contract_rangetime,'-',-3)) < '{$now}' and tbc.id is null")->count();

        if ($count > 0) {
            $columns = [
                '姓名',
                '证件号码',
                '劳动合同时间'
            ];
            $setting = [];
            $setting["freeze"] = "A2";
            $setting["filter"] = sprintf("A1:%s1", getExcelColumnByIndex(count($columns) - 1));
            $lists = Talent::alias("ti")->field("ti.id,ti.name,ti.card_number,ti.labor_contract_rangetime")->leftJoin("un_talent_basic_change tbc", "ti.id = tbc.talentId")->where($where)->whereRaw("trim(SUBSTRING_INDEX(ti.labor_contract_rangetime,'-',-3)) < '{$now}' and tbc.id is null")->select()->toArray();
            $datas = [];
            foreach ($lists as $v) {
                $item = [
                    $v['name'],
                    $v['card_number'],
                    $v['labor_contract_rangetime']
                ];
                array_push($datas, $item);
            }
            export($columns, $datas, "合同到期列表导出", $setting);
        } else {
            echo "<script>parent.layer.alert('没有可以导出的数据');window.history.go(-1);</script>";
        }
    }

}
