<?php

namespace app\job;

use think\queue\Job;
use think\facade\Log;
use think\facade\Db;
use app\common\api\ChuanglanSmsApi;
use app\common\api\TalentState;

/**
 * Description of Worker
 *
 * @author sgq
 */
class Worker {

    public function fire(Job $job, $data) {
        if ($this->deal($data)) {
            Log::info(json_encode($data));
            $job->delete();
            return true;
        }
        Log::error(json_encode($data));
        if ($job->attempts() >= 3) {
            $job->delete();
            return false;
        }
        $job->release(10); //10秒后重试
    }

    /**
     * 处理业务逻辑
     * @param type $data
     * @return bool
     */
    public function deal($data): bool {
        $type = $data["type"];
        switch ($type) {
            case 99://转移旧集成电路人才申报信息到新库
                $talent_info = $data["talent_info"];
                return $this->oldJcjlTalentInfoToNewTable($talent_info);
                break;
        }
        return false;
    }

    /**
     * 集成电路旧人才表转移到新人才表
     * @param type $talent_info
     */
    private function oldJcjlTalentInfoToNewTable($talent_info) {
        $whr = [];
        $whr[] = ["card_type", "=", $talent_info["cardType"]];
        $whr[] = ["card_number", "=", $talent_info["idCard"]];
        $whr[] = ["checkState", ">=", 0];
        if (Db::table("new_talent_info")->where($whr)->find()) {
            return false;
        }

        $data["oldId"] = $talent_info["id"];
        switch ($talent_info["checkState"]) {
            case -1:
                $data["checkState"] = TalentState::REVERIFY_FAIL;
                break;
            case 1:
                $data["checkState"] = TalentState::SCND_SAVE;
                break;
            case 7:
                $data["checkState"] = TalentState::SCND_SUBMIT;
                break;
            case 10:
                $data["checkState"] = TalentState::SCND_SAVE;
                break;
            case 20:
                $data["checkState"] = TalentState::SCND_SUBMIT;
                break;
            case 25:
                $data["checkState"] = TalentState::FST_VERIFY_PASS;
                break;
            case 35:
                if ($talent_info["isPublic"] == 5) {
                    $data["checkState"] = TalentState::PUBLISH_PASS;
                } else if ($talent_info["isPublic"] == 6) {
                    $data["checkState"] = TalentState::CERTIFICATED;
                } else {
                    $data["checkState"] = TalentState::REVERIFY_PASS;
                }
                break;
        }
        $data["highProcess"] = 0;
        switch ($talent_info["highProcess"]) {
            case 1:
                if ($talent_info["checkState"] == 25) {
                    $data["highProcess"] = 3;
                }
                break;
            case 3:
                if ($talent_info["checkState"] == 35) {
                    $data["highProcess"] = 5;
                } else {
                    $data["highProcess"] = 3;
                }
                break;
        }
        $data["enterprise_id"] = $talent_info["enterpriseId"];
        $data["name"] = $talent_info["name"];
        $data["phone"] = $talent_info["phone"];
        $data["email"] = $talent_info["email"];
        $data["sex"] = $talent_info["sex"];
        $data["card_type"] = $talent_info["cardType"];
        $data["card_number"] = $talent_info["idCard"];
        $data["headimgurl"] = $talent_info["photo"];
        $data["birthday"] = $talent_info["birthday"];
        $data["apply_year"] = $talent_info["year"];
        $data["province"] = $talent_info["provinceCode"];
        $data["city"] = $talent_info["cityCode"];
        $data["county"] = $talent_info["countyCode"];
        $data["nation"] = $this->getNewDictVal("un_nation", $talent_info["nation"], "nation");
        $data["nationality"] = $this->getNewDictVal("un_nationality", $talent_info["nationality"], "nationality", "other");
        $data["politics"] = $this->getNewDictVal("un_political", $talent_info["politics"], "politics");
        $data["highest_degree"] = $this->getNewDictVal("un_education", $talent_info["highEducation"], "highest_degree");
        $data["graduate_school"] = $talent_info["graduateSchool"];
        $data["major"] = $talent_info["major"];
        $data["position"] = $talent_info["post"];
        $data["study_abroad"] = $talent_info["studyAbroad"];
        $data["cur_entry_time"] = $talent_info["entryTime"];
        $data["cur_quit_time"] = $talent_info["quitTime"];
        $data["labor_contract_rangetime"] = $talent_info["startTime"] . " - " . $talent_info["endTime"];
        $data["talent_arrange"] = $talent_info["talentArrange"];
        $data["talent_condition"] = $this->getIdentifyCondition($talent_info["identifyCondition"]);

        $data["publicBatch"] = $talent_info["publicBatch"];
        $data["identifyConditionName"] = $talent_info["identifyConditionName"];
        $data["identifyGetTime"] = $talent_info["identifyGetTime"];
        $data["identifyExpireTime"] = $talent_info["identifyOutTime"];
        $data["identifyMonth"] = $talent_info["identifyMonth"];
        $data["certificateNo"] = $talent_info["certificateNO"];
        $data["certificateGetTime"] = $talent_info["certificateStartTime"];
        $data["certificateExpireTime"] = $talent_info["qzgccrcActiveTime"];
        $data["title"] = $talent_info["title"];
        $data["pro_qua"] = $talent_info["professionalQualifications"];
        $data["bank"] = $talent_info["bank"];
        $data["bank_branch_name"] = $talent_info["bankNetwork"];
        $data["bank_account"] = $talent_info["bankAccount"];
        $data["description"] = $talent_info["description"];
        $data["experience"] = $talent_info["mainHonours"];
        $data["education"] = $talent_info["educationAndResume"];
        $data["createTime"] = $talent_info["createTime"];
        $data["break_faith"] = $talent_info["breakFaith"];
        $data["first_submit_time"] = $talent_info["firstSubmitTime"];
        $data["new_submit_time"] = $talent_info["newSubmitTime"];
        $data["first_dept_check_time"] = $talent_info["firstDepPassTime"];
        $data["active"] = $talent_info["active"];
        $newTalentInfoId = Db::table("new_talent_info")->insertGetId($data);

        if ($newTalentInfoId) {
            $files = Db::table("un_talent_file")->where("mainId", $talent_info["id"])->select();
            foreach ($files as $file) {
                $newFileTypeId = $this->getFileTypeId($file["fileTypeId"]);

                $newFileData["mainId"] = $newTalentInfoId;
                $newFileData["type"] = 2;
                $newFileData["typeId"] = $newFileTypeId;
                $newFileData["orignName"] = $file["orignName"];
                $newFileData["url"] = $file["url"];
                $newFileData["sn"] = $file["sn"];
                $newFileData["description"] = $file["description"];
                $newFileData["createTime"] = $file["createTime"];
                $newFileData["createUser"] = $file["createUser"];
                $newFileData["updateTime"] = $file["updateTime"];
                $newFileData["updateUser"] = $file["updateUser"];
                Db::table("new_talent_file")->insert($newFileData);
            }
            $fieldMaps = [
                "name" => "name", "sex" => "sex", "birthday" => "birthday", "nationality" => "nationality", "provinceCode" => "province", "cityCode" => "city", "countyCode" => "county", "cardType" => "card_type",
                "idCard" => "card_number", "nation" => "nation", "politics" => "politics", "entryTime" => "cur_entry_time", "post" => "position", "startTime" => "labor_contract_rangetime",
                "endTime" => "labor_contract_rangetime", "highEducation" => "highest_degree", "graduateSchool" => "graduate_school", "major" => "major", "title" => "title", "professionalQualifications" => "pro_qua",
                "studyAbroad" => "study_abroad", "phone" => "phone", "email" => "email", "bank" => "bank", "bankNetwork" => "bank_branch_name", "bankNumber" => "bank_number", "bankAccount" => "bank_account",
                "breakFaith" => "break_faith", "talentArrange" => "talent_arrange", "identifyCondition" => "talent_condition", "identifyConditionName" => "identifyConditionName",
                "identifyGetTime" => "identifyGetTime", "educationAndResume" => "education", "mainHonours" => "experience"
            ];
            if (in_array($talent_info["checkState"], [10, 20])) {
                if ($talent_info["fields"]) {
                    $oldFields = array_filter(explode(",", $talent_info["fields"]));
                    $tmp = [];
                    foreach ($oldFields as $_of) {
                        $tmp[] = $fieldMaps[$_of];
                    }
                    $updData["modify_fields"] = implode(",", array_filter(array_unique($tmp)));
                }
                if ($talent_info["files"]) {
                    $oldFiles = array_filter(explode(",", $talent_info["files"]));
                    $tmp = [];
                    foreach ($oldFiles as $_of) {
                        $newFileTypeId = $this->getFileTypeId($_of);
                        $tmp[] = $newFileTypeId;
                    }
                    $updData["modify_files"] = implode(",", array_filter(array_unique($tmp)));
                }
                $updData["id"] = $newTalentInfoId;
                Db::table("un_talent_info")->save($updData);
            }
            return true;
        }
        return false;
    }

    private function getNewDictVal($old_pcode, $old_code, $new_pcode, $new_code_default = "") {
        $where = [];
        $where[] = ["d2.code", "=", $old_pcode];
        $where[] = ["d1.code", "=", $old_code];
        $oldDict = Db::table("sys_dict")->alias("d1")->leftJoin("sys_dict d2", "d1.pid=d2.id")->where($where)->field("d1.*")->find();
        $oldDictName = $oldDict["name"];
        $where = [];
        $where[] = ["d2.code", "=", $new_pcode];
        $where[] = ["d1.name", "=", $oldDictName];
        $newDict = Db::table("new_talent_dict")->alias("d1")->leftJoin("new_talent_dict d2", "d1.pid=d2.id")->where($where)->field("d1.*")->find();
        return $newDict["code"] ?: $new_code_default;
    }

    private function getFileTypeId($typeId) {
        $fileType = Db::table("un_common_filetype")->where("id", $typeId)->find();
        $where = [];
        $where[] = ["type", "=", 2];
        $where[] = ["project", "=", 1];
        $where[] = ["name", "=", $fileType["name"]];
        $newFileType = Db::table("new_common_filetype")->where($where)->find();
        $newFileTypeId = $newFileType["id"];
        if (!$newFileTypeId) {
            $newFileTypeData["type"] = $newFileType["type"];
            $newFileTypeData["source"] = $newFileType["source"];
            $newFileTypeData["project"] = $newFileType["project"];
            $newFileTypeData["name"] = $newFileType["name"];
            $newFileTypeData["api"] = $newFileType["api"];
            $newFileTypeData["must"] = $newFileType["must"];
            $newFileTypeData["active"] = $newFileType["active"];
            $newFileTypeData["sn"] = $newFileType["sn"];
            $newFileTypeData["description"] = $newFileType["description"];
            $newFileTypeData["createUser"] = $newFileType["createUser"];
            $newFileTypeData["createTime"] = $newFileType["createTime"];
            $newFileTypeData["updateUser"] = $newFileType["updateUser"];
            $newFileTypeData["updateTime"] = $newFileType["updateTime"];
            $newFileTypeData["templateUrl"] = $newFileType["templateUrl"];
            $newFileTypeId = Db::table("new_common_filetype")->insertGetId($newFileTypeData);
        }
        return $newFileTypeId;
    }

    private function getIdentifyCondition($conditionId) {
        $oldCondition = Db::table("un_identify_condition")->where("id", $conditionId)->find();
        $where = [];
        $where[] = ["name", "=", $oldCondition["name"]];
        $where[] = ["type", "=", 2];
        $newCondition = Db::table("new_talent_condition")->where($where)->find();
        return $newCondition["id"];
    }

}
