<?php

namespace app\enterprise\controller;

use app\enterprise\common\EnterpriseController;
use app\common\model\TalentWorkUnitChange as TwcModel;
use app\common\api\TalentLogApi;
use app\common\state\ProjectState;
use app\common\model\TalentLog;
use think\facade\Db;
use app\common\api\EnterpriseApi;

/**
 * Description of TalentWorkUnitChange
 *
 * @author sgq
 */
class TalentWorkUnitChange 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[] = ["newEnterpriseId", "=", $this->user["uid"]];
        $where[] = ["delete", "=", 0];
        if ($params["talentName"]) {
            $where[] = ["talentName", "like", "%" . $params["talentName"] . "%"];
        }
        if ($params["idCard"]) {
            $where[] = ["idCard", "like", "%" . $params["idCard"] . "%"];
        }
        if ($params["oldEnterpriseId"]) {
            $whr = [];
            $whr[] = ["name", "like", "%{$params["oldEnterpriseId"]}%"];
            $ids = \app\common\model\Enterprise::where($whr)->column("id");
            $where[] = ["oldEnterpriseId", "in", $ids];
        }
        if ($params["checkState"]) {
            $where[] = ["checkState", "=", $params["checkState"]];
        }
        $count = TwcModel::where($where)->count();
        $list = TwcModel::where($where)->limit($offset, $limit)->order("createTime " . $order)->select()->toArray();
        $talentArrangeMap = \app\common\api\DictApi::selectByParentCode("talent_arrange");
        $epMaps = \app\common\model\Enterprise::column("name", "id");
        foreach ($list as &$item) {
            $item["talentArrangeName"] = $talentArrangeMap[$item["talentArrange"]];
            $item["oldEnterpriseName"] = $epMaps[$item["oldEnterpriseId"]];
            $item["newEnterpriseName"] = $epMaps[$item["newEnterpriseId"]];
        }unset($item);

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

    public function apply() {
        $request = $this->request;
        $id = isset($request["id"]) ? $request["id"] : 0;
        $talentId = isset($request["talentId"]) ? $request["talentId"] : 0;
        $info = TwcModel::where("id", $id)->find();
        if ($info) {
            $epOld = EnterpriseApi::getOne($info["oldEnterpriseId"]);
            $epNew = EnterpriseApi::getOne($info["newEnterpriseId"]);
            $info["oldEnterpriseName"] = $epOld["name"];
            $info["newEnterpriseName"] = $epNew["name"];
            if (strlen($info["talentId"]) == 19) {
                $newTalentInfo = $this->getTalentInfoByIdCard($info["idCard"]);
                $info["talentId"] = $newTalentInfo["id"];
            }
            $talentId = $info["talentId"];
        }
        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($talentId);
            if (!$talentInfo) {
                $response->msg = "未匹配到人才数据";
                return $response;
            }
            if ($data["id"]) {
                unset($data["year"]);
                $data["updateUser"] = $this->user["uid"];
                $data["updateTime"] = date("Y-m-d H:i:s");
                TwcModel::update($data);
                $response->code = 200;
                $response->msg = "修改成功";
                return $response;
            } else {
                $data["id"] = getStringId();
                $data["oldStartTime"] = $talentInfo["startTime"];
                $data["oldEndTime"] = $talentInfo["endTime"];
                $data["checkState"] = -1;
                $data["createUser"] = $this->user["uid"];
                $data["createTime"] = date("Y-m-d H:i:s");
                TwcModel::create($data);

                $user = $this->user;
                $log["id"] = getStringId();
                $log["active"] = 1;
                $log["state"] = 1;
                $log["step"] = 0;
                $log["stateChange"] = "";
                $log["type"] = ProjectState::WORKCHANGE;
                $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;
            }
        }
        $year = $info["year"] ?: $request["year"];
        return view("", ["type" => $this->user["type"], "year" => $year, "row" => $info]);
    }

    public function view() {
        $id = $this->request["id"];
        $info = TwcModel::where("id", $id)->find();
        $epOld = EnterpriseApi::getOne($info["oldEnterpriseId"]);
        $epNew = EnterpriseApi::getOne($info["newEnterpriseId"]);
        $info["oldEnterpriseName"] = $epOld["name"];
        $info["newEnterpriseName"] = $epNew["name"];
        return view("", ["row" => $info]);
    }

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

    private function getTalentInfoByIdCard($idCard, $active = null) {
        //$where[] = ["enterprise_id", "=", $this->user["uid"]];
        $where[] = ["card_number", "=", $idCard];
        $where[] = ["checkState", "=", \app\common\api\TalentState::CERTIFICATED];
        $where[] = ["delete", "=", 0];
        if ($active) {
            $where[] = ["active", "=", $active];
        }
        $ti = \app\enterprise\model\Talent::where($where)->order("talent_arrange asc")->find();
        return $ti;
    }

    private function dataCheck($data) {
        $response = new \stdClass();
        $response->code = 500;
        if (\StrUtil::isEmpOrNull($data["starttime"])) {
            $response->msg = "合同开始时间不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["endtime"])) {
            $response->msg = "合同结束时间不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["phone"])) {
            $response->msg = "手机号码不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["newEnterpriseId"])) {
            $response->msg = "新单位名称不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["phone"])) {
            $response->msg = "手机号码不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["anyTime"])) {
            $response->msg = "入职/变更时间不能为空";
            return $response;
        }
        if ($data["type"] == 1) {
            if (\StrUtil::isEmpOrNull($data["anyReason"])) {
                $response->msg = "单位变更申报原因不能为空";
                return $response;
            }
        }
        $response->code = 200;
        return $response;
    }

}
