<?php

namespace app\admin\controller;

use app\admin\common\AdminController;
use app\admin\model\ApiData;
use app\common\api\ChuanglanSmsApi;
use app\common\api\DictApi;
use app\common\api\EnterpriseApi;
use app\common\model\MessageRecord;
use app\common\model\TalentChecklog;
use app\common\api\TalentState;
use app\common\api\CompanyApi;
use think\facade\Db;
use app\admin\api\RsApi;
use app\common\state\CommonConst;

/**
 * 企业审核
 * checkState 1:用户提交 [2:审核驳回 3:审核通过] 4:重新提交 [5:初审驳回 6:初审通过]
 */
class Enterprise extends AdminController {

    public function gotoEnterprisePage() {
        $template = "";
        switch ($this->user["type"]) {
            case CommonConst::ENTERPRISE_WJ:
                $template = "/enterprise/hospital/goto_enterprise_page";
                break;
            case CommonConst::ENTERPRISE_GJ:
                $template = "/enterprise/school/goto_enterprise_page";
                break;
        }
        return view($template, []);
    }

    public function findEnterpriseByPage() {
        $res = EnterpriseApi::getList($this->request);

        return json($res);
    }

    public function gotoEnterpriseDetailPage() {
        $id = trim($this->request['id']);
        $ep = EnterpriseApi::getOne($id);
        if (!in_array($ep["type"], [CommonConst::ENTERPRISE_WJ, CommonConst::ENTERPRISE_GJ])) {
            $check_info = ApiData::where('action', '=', 'register_check')->where('uid', '=', $ep['idCard'])->where('status', '=', 1)->find();
            $force = intval($this->request['force'], 0);
            if ($force || !$check_info || !$check_info['status']) {
                $rsapi = new RsApi();
                switch ($ep['special']) {
                    case 0:
                        $ep['rs'] = $rsapi->I040102($ep['idCard']);
                        break;
                    case 1:
                        $ep['rs'] = $rsapi->I080101($ep['idCard']);
                        break;
                    case 3:
                        $ep['rs'] = $rsapi->I030501($ep['name'], $ep['idCard']);
                        break;
                }

                ApiData::where('action', '=', 'register_check')->where('uid', '=', $ep['idCard'])->where('status', '=', 1)->update(['status' => 0, 'updateTime' => time()]);
                $api_model_data = [
                    'uid' => $ep['idCard'],
                    'action' => 'register_check',
                    'content' => serialize($ep['rs']),
                    'createTime' => time()
                ];

                ApiData::create($api_model_data);
            } else {
                $ep['rs'] = unserialize($check_info['content']);
            }
        }

        if (!$ep) {
            return "无此企业";
        }
        //--------设置 审核状态---------------------------------------------------
        switch ($ep['checkState']) {
            case 1:
                $ep['checkStateName'] = "待审核";
                break;
            case 2:
                $ep['checkStateName'] = "审核驳回";
                break;
            case 3:
                $ep['checkStateName'] = "审核通过";
                break;
            case 4:
                $ep['checkStateName'] = "重新提交";
                break;
            case 5:
                $ep['checkStateName'] = "初审驳回";
                break;
            case 6:
                $ep['checkStateName'] = "初审通过";
                break;
        }
        //-------设置账号状态----------------------------------------------------
        switch ($ep['active']) {
            case 1:
                $ep['activeName'] = "账号有效";
                break;
            case 2:
                $ep['activeName'] = "冻结/拉黑";
                break;
        }
        //---------设置 街道-----------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['street'])) {
            $street_info = DictApi::findByParentCodeAndCode('street', $ep['street']);
            if ($street_info != null) {
                $ep['streetName'] = $street_info['name'];
            }
        }
        if (\StrUtil::isNotEmpAndNull($ep['agencyType'])) {
            $agencyType = DictApi::findByParentCodeAndCode('agency_type', $ep['agencyType']);
            $ep["agencyTypeName"] = $agencyType["name"];
        }

        //---------设置产业领域 --------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['industryFieldNew'])) {
            $industryFieldNew = DictApi::findByParentCodeAndCode('industry_field', $ep['industryFieldNew']);
            if ($industryFieldNew != null) {
                $ep['industryFieldNewName'] = $industryFieldNew['name'];
            }
        }
        //---------设置行业领域 --------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['industryFieldOld'])) {
            $industryFieldOld = DictApi::findByParentCodeAndCode($ep['industryFieldNew'] . "_field", $ep['industryFieldOld']);
            if ($industryFieldOld != null) {
                $ep['industryFieldOldName'] = $industryFieldOld['name'];
            }
        }
        //---------设置单位标签 --------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['enterpriseTag'])) {
            $enterpriseTag = DictApi::findByParentCodeAndCode("enterprise_tag", $ep['enterpriseTag']);
            if ($enterpriseTag != null) {
                $ep['enterpriseTagName'] = $enterpriseTag['name'];
            }
        }
        //---------设置机构标签 --------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['organizationTag'])) {
            $organizationTag = DictApi::findByParentCodeAndCode("organization_tag", $ep['organizationTag']);
            if ($organizationTag != null) {
                $ep['organizationTagName'] = $organizationTag['name'];
            }
        }
        //---------设置事业单位标签 --------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['institutionTag'])) {
            $institutionTag = DictApi::findByParentCodeAndCode("institution_tag", $ep['institutionTag']);
            if ($institutionTag != null) {
                $ep['institutionTagName'] = $institutionTag['name'];
            }
        }
        //---------设置单位类型 --------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['enterpriseType'])) {
            $enterpriseType = DictApi::findByParentCodeAndCode("enterprise_type", $ep['enterpriseType']);
            if ($enterpriseType != null) {
                $ep['enterpriseTypeName'] = $enterpriseType['name'];
            }
        }

        $imgurl_info = pathinfo($ep['imgurl']);
        if (in_array($imgurl_info['extension'], ["jpeg", "jpg", "png", "gif"])) {
            $ep['imgurl_is_img'] = 1;
        } else {
            $ep['imgurl_is_img'] = 0;
        }

        $bankImg_info = pathinfo($ep['bankImg']);
        if (in_array($bankImg_info['extension'], ["jpeg", "jpg", "png", "gif"])) {
            $ep['bankImg_is_img'] = 1;
        } else {
            $ep['bankImg_is_img'] = 0;
        }

        $domainImg_info = pathinfo($ep['domainImg']);
        if (in_array($domainImg_info['extension'], ["jpeg", "jpg", "png", "gif"])) {
            $ep['domainImg_is_img'] = 1;
        } else {
            $ep['domainImg_is_img'] = 0;
        }

        $typeImg_info = pathinfo($ep['typeImg']);
        if (in_array($typeImg_info['extension'], ["jpeg", "jpg", "png", "gif"])) {
            $ep['typeImg_is_img'] = 1;
        } else {
            $ep['typeImg_is_img'] = 0;
        }

        $beian_info = pathinfo($ep['beian']);
        if (in_array($beian_info['extension'], ["jpeg", "jpg", "png", "gif"])) {
            $ep['beian_is_img'] = 1;
        } else {
            $ep['beian_is_img'] = 0;
        }

        $template = "";
        switch ($this->user["type"]) {
            case CommonConst::ENTERPRISE_WJ:
                $template = "/enterprise/hospital/goto_enterprise_detail_page";
                $ep["medicalCommunityName"] = \app\common\api\Nhc::getMedicalCommunityMap()[$ep["medicalCommunityId"]];
                break;
            case CommonConst::ENTERPRISE_GJ:
                $template = "/enterprise/school/goto_enterprise_detail_page";
                break;
        }
        $assign['ep'] = $ep;

        return view($template, $assign);
    }

    public function gotoExaminePage() {
        $id = trim($this->request['id']);
        $ep = EnterpriseApi::getOne($id);
        $lastLog = \app\common\api\TalentLogApi::getLastLog($id, 10);
        if ($lastLog["active"] == 0) {
            $ep["checkState"] = $lastLog["state"];
            $ep["checkMsg"] = $lastLog["description"];
        }
        if (!$ep) {
            return "无此企业";
        }
        //---------设置产业领域 --------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['industryFieldNew'])) {
            $industryFieldNew = DictApi::findByParentCodeAndCode('industry_field', $ep['industryFieldNew']);
            if ($industryFieldNew != null) {
                $ep['industryFieldNewName'] = $industryFieldNew['name'];
            }
        }
        $fieldsAndFiles = $this->getFieldAndFilesBySpecialAndType($ep->special, $ep->type);
        $fields = $fieldsAndFiles["fields"];
        $files = $fieldsAndFiles["files"];

        $modify_fields = [];
        $modify_files = [];
        $_modify_fields = explode(",", $ep["modify_fields"]);
        foreach ($fields as $key => $value) {
            $checked = in_array($key, $_modify_fields);
            $modify_fields[$key] = ["field" => $key, "name" => $value, "checked" => $checked];
        }
        $_modify_files = explode(",", $ep["modify_files"]);
        foreach ($files as $key => $value) {
            $checked = in_array($key, $_modify_files);
            $modify_files[$key] = ["field" => $key, "name" => $value, "checked" => $checked];
        }
        $template = "";
        switch ($this->user["type"]) {
            case CommonConst::ENTERPRISE_WJ:
                $template = "/enterprise/hospital/goto_examine_page";
                break;
            case CommonConst::ENTERPRISE_GJ:
                $template = "/enterprise/school/goto_examine_page";
                break;
        }

        return view($template, ['ep' => $ep, 'checkUser' => session('user')['name'], 'fields' => $modify_fields, "files" => $modify_files]);
    }

    public function doExamine() {
        $id = trim($this->request['id']);
        $doSubmit = $this->request["submit"] == 1 ? true : false;
        if (!$id) {
            return json(["msg" => 'ID不能为空!']);
        }
        $ep = EnterpriseApi::getOne($id);
        if (!$ep) {
            return json(["msg" => '无此企业!']);
        }

        $oriCheckState = $ep["checkState"];
        if ($oriCheckState == 6 && !EnterpriseApi::chkUserInSuperusers() && !in_array($this->user["type"], [CommonConst::ENTERPRISE_JC, CommonConst::ENTERPRISE_WJ, CommonConst::ENTERPRISE_GJ])) {
            return json(["msg" => "已经流转到复审，不在审核范围内"]);
        }

        if (!in_array($ep["checkState"], [1, 4, 6]))
            return json(["msg" => "不在审核范围内"]);
        $checkState = $this->request['checkState'];
        if ($checkState == null || ($checkState != 5 && $checkState != 2 && $checkState != 3)) {
            return json(["msg" => '请选择审核状态!']);
        }
        $checkMsg = $this->request['checkMsg'];
        $fields = $this->request['fields'];
        $files = $this->request['files'];
        if ($checkState == 2 || ($checkState == 5 && $ep["type"] == CommonConst::ENTERPRISE_WJ)) {
            if ($checkState == 5 && $ep["isGeneral"] == 1) {
                return json(["msg" => '总院不能驳回到分院!']);
            }
            if (\StrUtil::isEmpOrNull($checkMsg)) {
                return json(["msg" => '请填写审核意见!']);
            }
            if (strlen($checkMsg) > 1000) {
                return json(["msg" => '审核意见最多1000个字符!']);
            }
            if (!$fields && !$files) {
                return json(["msg" => '请选择驳回修改的字段或者附件!']);
            }
        }
        try {
            $lastLog = \app\common\api\TalentLogApi::getLastLog($id, 10);
            $companyName = session('user')["companyName"] ?: session('user')["rolename"];
            if ($checkState == 3) {
                $fields = null;
                $files = null;
            }
            if ($oriCheckState == 6 || $ep["type"] == 2) {
                $newCheckState = $checkState;
            } else {
                $newCheckState = $checkState == 3 ? 6 : 5;
            }
            if ($doSubmit) {
                $checkData = [
                    'id' => $id,
                    'checkState' => $newCheckState,
                    'checkMsg' => $checkMsg,
                    'modify_fields' => $fields ? implode(",", $fields) : null,
                    'modify_files' => $files ? implode(",", $files) : null,
                    'checkUser' => session('user')['name'],
                    'updateUser' => session('user')['uid'],
                    'updateTime' => date("Y-m-d H:i:s")
                ];
                if ($ep["type"] == CommonConst::ENTERPRISE_WJ) {
                    if ($newCheckState == 2 || $newCheckState == 5) {
                        $checkData["step"] = 0;
                    } else {
                        $checkData["step"] = 2;
                    }
                }

                $res = EnterpriseApi::updateById($checkData);

                //短信入库数据
                $record_data = [
                    'id' => getStringId(),
                    'bizId' => getStringId(),
                    'userId' => $id,
                    'type' => 2,
                    'smsType' => 2,
                    'name' => $ep['name'],
                    'phone' => $ep['agentPhone'],
                    'params' => '机构注册信息',
                    'state' => 1,
                    'sendingDate' => date("Y-m-d H:i:s", time()),
                    'createTime' => date("Y-m-d H:i:s", time())
                ];

                if ($checkState == 2 || $checkState == 5) {
                    $record_data['templateCode'] = "【晋江市人才服务平台】您好！您提交的晋江市现代产业体系人才机构注册信息因信息填写错误或上传不完整已被退回，请及时登录“晋江市人才综合服务申报平台”根据审核意见修改并重新提交。退订回复TD。";
                }
                if ($newCheckState == 3) {
                    $record_data['templateCode'] = "【晋江市人才服务平台】您好！您提交的晋江市现代产业体系人才机构注册信息已审核通过，可登录“晋江市人才综合服务申报平台”做相关事宜申报。退订回复TD。";

                    queue("app\job\Enterprise", ["type" => 1, "id" => $id]);
                }

                if ($newCheckState == 3 || ($checkState == 2 && $ep["type"] != CommonConst::ENTERPRISE_WJ) || ($checkState == 2 && $ep["isGeneral"] == 1) || $checkState == 5) {
                    $smsapi = new ChuanglanSmsApi();

                    $result = $smsapi->sendSMS($ep['agentPhone'], $record_data['templateCode']);

                    MessageRecord::create($record_data);
                }
                if ($lastLog["active"] === 0) {
                    TalentChecklog::update([
                        'id' => $lastLog["id"],
                        'active' => 1,
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => TalentState::stateEnum($newCheckState),
                        'description' => $checkMsg,
                        'updateTime' => date("Y-m-d H:i:s", time()),
                        'updateUser' => session('user')['name'] . "({$companyName})"
                    ]);
                } else {
                    TalentChecklog::create([
                        'id' => getStringId(),
                        'mainId' => $id,
                        'type' => 10,
                        'typeFileId' => null,
                        'active' => 1,
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => TalentState::stateEnum($newCheckState),
                        'description' => $checkMsg,
                        'createTime' => date("Y-m-d H:i:s", time()),
                        'createUser' => session('user')['name'] . "({$companyName})"
                    ]);
                }

                return json(["msg" => '操作成功!', "code" => 200]);
            } else {
                $checkData = [
                    'id' => $id,
                    'modify_fields' => $fields ? implode(",", $fields) : null,
                    'modify_files' => $files ? implode(",", $files) : null,
                    'checkUser' => session('user')['name'],
                    'updateUser' => session('user')['uid'],
                    'updateTime' => date("Y-m-d H:i:s")
                ];
                $res = EnterpriseApi::updateById($checkData);

                if ($lastLog["active"] === 0) {
                    TalentChecklog::update([
                        'id' => $lastLog["id"],
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => TalentState::stateEnum($newCheckState),
                        'description' => $checkMsg,
                        'updateTime' => date("Y-m-d H:i:s", time()),
                        'updateUser' => session('user')['name'] . "({$companyName})"
                    ]);
                } else {
                    TalentChecklog::create([
                        'id' => getStringId(),
                        'mainId' => $id,
                        'type' => 10,
                        'typeFileId' => null,
                        'active' => 0,
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => TalentState::stateEnum($checkState),
                        'description' => $checkMsg,
                        'createTime' => date("Y-m-d H:i:s", time()),
                        'createUser' => session('user')['name'] . "({$companyName})"
                    ]);
                }
                return json(["msg" => '保存成功!', "code" => 200]);
            }
        } catch (\Exception $e) {
            return json(["msg" => $e->getMessage()]);
        }
    }

    public function gotoRejectPage() {
        $id = trim($this->request['id']);
        $ep = EnterpriseApi::getOne($id);
        if (!$ep) {
            return "无此企业";
        }
        if ($ep["checkState"] != 3) {
            return "该操作只能对已通过企业进行驳回";
        }
        $lastLog = \app\common\api\TalentLogApi::getLastLog($id, 10);
        if ($lastLog["active"] != 1 || $lastLog["state"] != $ep["checkState"]) {
            return "日志状态与当前状态不一致，已中止操作";
        }
        $ep["passedUser"] = $lastLog["createUser"];
        $ep["passedTime"] = $lastLog["createTime"];
        //---------设置产业领域 --------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['industryFieldNew'])) {
            $industryFieldNew = DictApi::findByParentCodeAndCode('industry_field', $ep['industryFieldNew']);
            if ($industryFieldNew != null) {
                $ep['industryFieldNewName'] = $industryFieldNew['name'];
            }
        }

        $fieldsAndFiles = $this->getFieldAndFilesBySpecialAndType($ep->special, $ep->type);
        $fields = $fieldsAndFiles["fields"];
        $files = $fieldsAndFiles["files"];

        $modify_fields = [];
        $modify_files = [];
        $_modify_fields = explode(",", $ep["modify_fields"]);
        foreach ($fields as $key => $value) {
            $modify_fields[$key] = ["field" => $key, "name" => $value];
        }
        $_modify_files = explode(",", $ep["modify_files"]);
        foreach ($files as $key => $value) {
            $modify_files[$key] = ["field" => $key, "name" => $value];
        }

        return view("", ['ep' => $ep, 'fields' => $modify_fields, "files" => $modify_files]);
    }

    public function doReject() {
        $id = trim($this->request['id']);
        if (!$id) {
            return json(["msg" => 'ID不能为空!']);
        }
        $ep = EnterpriseApi::getOne($id);
        if (!$ep) {
            return json(["msg" => '无此企业!']);
        }
        if ($ep["checkState"] != 3) {
            return json(["msg" => '该操作只能对已通过企业进行驳回!']);
        }
        $checkMsg = $this->request['checkMsg'];
        $fields = $this->request['fields'];
        $files = $this->request['files'];
        if (\StrUtil::isEmpOrNull($checkMsg)) {
            return json(["msg" => '请填写审核意见!']);
        }
        if (strlen($checkMsg) > 1000) {
            return json(["msg" => '审核意见最多1000个字符!']);
        }
        if (!$fields && !$files) {
            return json(["msg" => '请选择驳回修改的字段或者附件!']);
        }
        try {
            $lastLog = \app\common\api\TalentLogApi::getLastLog($id, 10);
            if ($lastLog["active"] != 1 || $lastLog["state"] != $ep["checkState"]) {
                return json(["msg" => '日志状态与当前状态不一致，已中止操作']);
            }
            $companyName = session('user')["companyName"] ?: session('user')["rolename"];
            $checkData = [
                'id' => $id,
                'checkState' => 2,
                'checkMsg' => $checkMsg,
                'modify_fields' => $fields ? implode(",", $fields) : null,
                'modify_files' => $files ? implode(",", $files) : null,
                'checkUser' => session('user')['name'],
                'updateUser' => session('user')['uid'],
                'updateTime' => date("Y-m-d H:i:s")
            ];
            $res = EnterpriseApi::updateById($checkData);

            $tplContent = "【晋江市人才服务平台】您好！您提交的晋江市现代产业体系人才机构注册信息因信息填写错误或上传不完整已被退回，请及时登录“晋江市人才综合服务申报平台”根据审核意见修改并重新提交。退订回复TD。";
            $smsapi = new ChuanglanSmsApi();
            $result = $smsapi->sendSMS($ep['agentPhone'], $tplContent);

            //短信入库数据
            $record_data = [
                'id' => getStringId(),
                'bizId' => $result['msgId'],
                'userId' => $id,
                'type' => 2,
                'smsType' => 2,
                'name' => $ep['name'],
                'phone' => $ep['agentPhone'],
                'params' => '机构注册通过再驳回',
                'state' => $result['code'] == 0 ? 2 : 3,
                'sendingDate' => date("Y-m-d H:i:s", time()),
                'createTime' => date("Y-m-d H:i:s", time()),
                'templateCode' => $tplContent,
                "msg" => $result['errorMsg']
            ];

            MessageRecord::create($record_data);
            TalentChecklog::create([
                'id' => getStringId(),
                'mainId' => $id,
                'type' => 10,
                'typeFileId' => null,
                'active' => 1,
                'state' => 2,
                'step' => 101,
                'stateChange' => TalentState::stateEnum(2),
                'description' => $checkMsg,
                'createTime' => date("Y-m-d H:i:s", time()),
                'createUser' => session('user')['name'] . "({$companyName})"
            ]);

            return json(["msg" => '操作成功!', "code" => 200]);
        } catch (\Exception $e) {
            return json(["msg" => $e->getMessage()]);
        }
    }

    public function delEnterprise() {
        if (!$id = trim($this->request['id'])) {
            return json(["msg" => 'ID不能为空!', "code" => 500]);
        }
        $ep = EnterpriseApi::getOne($id);
        if (!$ep || $ep->delete == 1)
            return json(["msg" => '要删除的数据不存在!', "code" => 500]);

        $ep->delete = 1;
        $ep->deleteUser = session('user')['uid'] . "";
        $ep->deleteTime = date('Y-m-d H:i:s');

        try {
            $ep->save();
            return json(["msg" => '操作成功!', "code" => 200]);
        } catch (\Exception $e) {
            return json(["msg" => $e->getMessage()]);
        }
    }

    public function GotoActivePage() {
        $id = trim($this->request['id']);
        $ep = EnterpriseApi::getOne($id);

        $template = "";
        switch ($this->user["type"]) {
            case CommonConst::ENTERPRISE_WJ:
                $template = "/enterprise/hospital/goto_active_page";
                break;
            case CommonConst::ENTERPRISE_GJ:
                $template = "/enterprise/school/goto_active_page";
                break;
        }

        return view($template, ['ep' => $ep]);
    }

    public function setActive() {
        if (!$id = trim($this->request['id'])) {
            return json(["msg" => 'ID不能为空!', "code" => 500]);
        }
        $ep = EnterpriseApi::getOne($id);
        $active = $this->request['active'];
        if ($ep['active'] == null || ($ep['active'] != 1 && $ep['active'] != 2)) {
            return json(["msg" => '状态有误!', "code" => 500]);
        }
        if ($ep['active'] == 2) {
            $msg = trim($this->request['activeMsg']);
            if (empty($msg)) {
                return json(["msg" => '请填写拉黑/冻结原因!', "code" => 500]);
            }
            if (strlen($msg) > 100) {
                return json(["msg" => '拉黑/冻结原因 最多100个字符!', "code" => 500]);
            }
        }

        $company = CompanyApi::getOne(session('user')['companyId']);
        $ep->active = $active;
        $ep->activeMsg = $msg;
        $ep->updateUser = session('user')['uid'] . "";
        $ep->updateTime = date('y-m-d H:i:s');

        try {
            $ep->save();
            //添加日志
            TalentChecklog::create([
                'id' => getStringId(),
                'mainId' => $ep['id'],
                'type' => 10,
                'typeFileId' => null,
                'active' => 1,
                'state' => TalentState::RCRD_BASEIC_FROZEN,
                'step' => 102,
                'stateChange' => TalentState::stateEnum(10),
                'description' => $msg,
                'createTime' => date("Y-m-d H:i:s", time()),
                'createUser' => session('user')['name'] . "({$company['name']})"
            ]);

            return json(["msg" => '操作成功!', "code" => 200]);
        } catch (\Exception $e) {
            return json(["msg" => $e->getMessage()]);
        }
    }

    public function resetPassword() {
        if (!$id = trim($this->request['id'])) {
            return json(["msg" => 'ID不能为空!', "code" => 500]);
        }
        $ep = EnterpriseApi::getOne($id);
        if (!$ep) {
            return json(["msg" => '找不到该用户!', "code" => 500]);
        }
        $ep->password = hash("md5", 'JJrc@123'); //默认密码
        $ep->updateUser = session('user')['uid'] . "";
        $ep->updateTime = date("Y-m-d H:i:s");
        $ep->save();

        $company = CompanyApi::getOne(session('user')['companyId']);
        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $ep['id'],
            'type' => 10,
            'typeFileId' => null,
            'active' => 1,
            'state' => null,
            'step' => 103,
            'stateChange' => '重置密码',
            'description' => '重置密码',
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => session('user')['name'] . "({$company['name']})"
        ]);
        return json(["msg" => '重置密码成功!', "code" => 200]);
    }

    public function export() {
        $res = EnterpriseApi::getList($this->request, true);
        $rows = $res["rows"];
        $columns = ["单位名称", " 统一社会信用代码", "产业领域", "单位标签", " 所属街道", "单位地址", " 法人代表", " 单位电话", "人才联络员", "人才联络员电话", "人才联络员邮箱", "审核状态", "账号状态", "注册时间", "备注"];

        $exportDatas = [];
        if ($res["rows"]) {
            $stateMaps = [1 => "未审核", 2 => "审核驳回", 3 => "审核通过", 4 => "重新提交", 5 => "初审驳回", 6 => "初审通过"];
            $activeMaps = [1 => "账号有效", 2 => "拉黑/冻结"];
            foreach ($rows as $row) {
                $exportDatas[] = [
                    $row['name'],
                    $row['idCard'],
                    $row['industryFieldNewName'],
                    $row['enterpriseTagName'],
                    $row['streetName'],
                    $row['address'],
                    $row['legal'],
                    $row['ephone'],
                    $row['agentName'],
                    $row['agentPhone'],
                    $row['agentEmail'],
                    $stateMaps[$row["checkState"]],
                    $activeMaps[$row["active"]],
                    $row['createTime'],
                    $row['description']
                ];
            }
            export($columns, $exportDatas, "企业用户信息");
            exit();
        }
        return json(["msg" => "没有可以导出的内容"]);
    }

    public function findFieldsAndFiles() {
        $id = $this->request->param("id");
        $ep = EnterpriseApi::getOne($id);

        $fieldsAndFiles = $this->getFieldAndFilesBySpecialAndType($ep->special, $ep->type);
        $fields = $fieldsAndFiles["fields"];
        $files = $fieldsAndFiles["files"];

        $modify_fields = [];
        $modify_files = [];
        $_modify_fields = explode(",", $ep["modify_fields"]);
        foreach ($fields as $key => $value) {
            $checked = in_array($key, $_modify_fields);
            $modify_fields[$key] = ["field" => $key, "name" => $value, "checked" => $checked];
        }
        $_modify_files = explode(",", $ep["modify_files"]);
        foreach ($files as $key => $value) {
            $checked = in_array($key, $_modify_files);
            $modify_files[$key] = ["field" => $key, "name" => $value, "checked" => $checked];
        }
        return json(["code" => 200, "files" => $modify_files, "fields" => $modify_fields]);
    }

    public function updateFieldsAndFiles() {
        try {
            $params = $this->request->param();
            $id = $params["id"];
            $ep = EnterpriseApi::getOne($id);
            if (!$ep) {
                throw new \think\Exception("没有对应的企业信息");
            }
            if (!in_array($ep["checkState"], [2, 5])) {
                throw new \think\Exception("不是驳回状态，不能修改驳回字段！");
            }
            if ($ep["checkState"] == 2 && !EnterpriseApi::chkUserInSuperusers() && !in_array($this->user["type"], [CommonConst::ENTERPRISE_JC, CommonConst::ENTERPRISE_WJ, CommonConst::ENTERPRISE_GJ])) {
                throw new \think\Exception("已经流转到审核，不在审核范围内");
            }
            $fields = array_filter(explode(",", $params["fields"]));
            $files = array_filter(explode(",", $params["files"]));
            if (!$fields && !$files)
                throw new \think\Exception("请选择要驳回的字段或附件！");
            $data["id"] = $id;
            $data["modify_fields"] = $fields ? implode(",", $fields) : null;
            $data["modify_files"] = $files ? implode(",", $files) : null;
            $data["updateTime"] = date("Y-m-d H:i:s");
            $data["updateUser"] = session("user")["uid"];
            if (EnterpriseApi::updateById($data)) {
                return json(["code" => 200, "msg" => "修改成功！"]);
            }
        } catch (\think\Exception $e) {
            return json(["msg" => $e->getMessage()]);
        }
    }

    private function getFieldAndFilesBySpecialAndType($special, $type) {
        if ($special == 0) {
            if ($type == CommonConst::ENTERPRISE_JC) {
                $fields = ["name" => "企业名称", "idCard" => "统一社会信用代码", "legal" => "法人代表", "address" => "企业地址", "street" => "所属街道", "ephone" => "企业电话", "bankCard" => "企业银行账号", "bank" => "企业开户银行", "bankNetwork" => "企业开户银行网点",
                    "agentName" => "人才联络员姓名", "agentPhone" => "人才联络员电话", "agentEmail" => "人才联络员邮箱"];
                $files = ["imgurl" => "企业营业执照", "bankImg" => "开户许可证/基本存款账户信息", "beian" => "人才联络员信息备案表"];
            } else if ($type == CommonConst::ENTERPRISE_WJ) {
                $fields = ["name" => "医院名称", "idCard" => "登记号", "legal" => "法人代表", "medicalCommunityId" => "医共体", "isGeneral" => "是否总院", "ephone" => "医院电话", "province" => "地址省", "city" => "地址市", "county" => "地址县\区", "address" => "医院地址",
                    "bankCard" => "银行账号", "bank" => "开户银行", "bankNetwork" => "开户银行网点",
                    "agentName" => "人才联络员姓名", "agentPhone" => "人才联络员电话", "agentEmail" => "人才联络员邮箱"];
                $files = ["imgurl" => "医疗机构执业许可证", "bankImg" => "开户许可证/基本存款账户信息", "beian" => "人才联络员信息备案表"];
            } else if ($type == CommonConst::ENTERPRISE_GJ) {
                $fields = ["name" => "学校名称", "idCard" => "统一社会信用代码", "legal" => "法人代表", "ephone" => "学校电话", "province" => "地址省", "city" => "地址市", "county" => "地址县\区", "address" => "学校地址",
                    "agentName" => "人才联络员姓名", "agentPhone" => "人才联络员电话", "agentEmail" => "人才联络员邮箱"];
                $files = ["imgurl" => "办学许可证、法人证书或登记证书", "beian" => "人才联络员信息备案表"];
            } else {
                $fields = ["name" => "企业名称", "idCard" => "统一社会信用代码", "legal" => "法人代表", "address" => "企业地址", "street" => "所属街道", "ephone" => "企业电话", "bankCard" => "企业银行账号", "bank" => "企业开户银行", "bankNetwork" => "企业开户银行网点",
                    "agencyType" => "机构类型", "industryFieldNew" => "产业领域", "industryFieldOld" => "行业领域", "enterpriseTag" => "企业标签", "enterpriseType" => "企业类型",
                    "agentName" => "人才联络员姓名", "agentPhone" => "人才联络员电话", "agentEmail" => "人才联络员邮箱"];
                $files = ["imgurl" => "企业营业执照", "bankImg" => "开户许可证/基本存款账户信息", "domainImg" => "行业领域佐证材料", "beian" => "人才联络员信息备案表", "typeImg" => "规上、高新技术、专精特新企业上传材料"];
            }
        } else {
            $fields = ["name" => "单位名称", "idCard" => "统一社会信用代码", "legal" => "法人代表", "address" => "单位地址", "street" => "所属街道", "ephone" => "单位电话", "bankCard" => "单位银行账号", "bank" => "单位开户银行", "bankNetwork" => "单位开户银行网点",
                "agentName" => "人才联络员姓名", "agentPhone" => "人才联络员电话", "agentEmail" => "人才联络员邮箱"];
            if ($special == 1) {
                $fields["institutionTag"] = "单位标签";
            }
            if ($special == 3) {
                $fields["organizationTag"] = "机构标签";
            }
            $files = ["imgurl" => "法人证或批文", "bankImg" => "开户许可证/基本存款账户信息", "beian" => "人才联络员备案表"];
        }
        return ["fields" => $fields, "files" => $files];
    }

}
