<?php

namespace app\enterprise\controller;

use app\admin\model\Enterprise;
use app\common\api\DictApi;
use app\common\api\EnterpriseApi;
use app\common\model\CurrentcyFileType;
use app\common\model\TalentChecklog;
use app\common\model\TalentCommonFile;
use app\enterprise\model\EnterpriseRecord;
use app\enterprise\common\EnterpriseController;
use app\Request;
use think\exception\ValidateException;
use app\common\api\UploadApi;
use app\common\state\CommonConst;
use app\common\api\LocationApi;
use think\facade\Db;

class Api extends EnterpriseController {

    private $compatible_time = "2022-10-15 23:59:59";

    public function findEnterpriseChangeByPage() {
        $order = trim($this->request->param("order")) ?: "desc";
        $offset = trim($this->request->param("offset")) ?: 0;
        $limit = trim($this->request->param("limit")) ?: 10;

        $list = EnterpriseRecord::where('mainId', session("user")["uid"])->limit($offset, $limit)->order('createTime ' . $order)->select()->toArray();
        $count = count($list);
        if ($count > 0) {
            $streetList = DictApi::selectByParentCode('street');
            $typeList = DictApi::selectByParentCode('enterprise_type');
            $industryFieldNew = DictApi::selectByParentCode('industry_field');
            $medicalCommunityList = \app\common\api\Nhc::getMedicalCommunityMap();
            foreach ($list as $k => &$v) {
                $v['newIndustryFieldNewName'] = $industryFieldNew[$v['newIndustryFieldNew']];
                $v['newEnterpriseType'] = $typeList[$v['newEnterpriseType']];
                $v['newStreetName'] = $streetList[$v['newStreet']];
                $v['newMedicalCommunityName'] = $medicalCommunityList[$v["newMedicalCommunityId"]];
            }
        }

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

    public function findUnfinishedChangeRecord() {
        return EnterpriseRecord::where('mainId', session("user")["uid"])->where('checkState', '<>', 4)->select()->toArray();
    }

    public function toAdd() {
        $ep = Enterprise::where('id', session("user")["uid"])->find();
        $ecr = [
            "special" => $ep["special"],
            'enterprise_id' => $ep['id'],
            'newName' => $ep['name'],
            'newIdCard' => $ep['idCard'],
            'newMedicalCommunityId' => $ep["medicalCommunityId"],
            'newIsGeneral' => $ep["isGeneral"],
            'newStreet' => $ep['street'],
            'newAddress' => $ep['address'],
            'newProvince' => $ep['province'],
            'newCity' => $ep['city'],
            'newCounty' => $ep['county'],
            'newLegal' => $ep['legal'],
            'newEphone' => $ep['ephone'],
            'newAgentName' => $ep['agentName'],
            'newAgentEmail' => $ep['agentEmail'],
            'newAgentPhone' => $ep['agentPhone'],
            'type' => $ep['type'],
            'newAgencyType' => $ep['agencyType'],
            'newEnterpriseTag' => $ep['enterpriseTag'],
            'newOrganizationTag' => $ep['organizationTag'],
            'newInstitutionTag' => $ep['institutionTag'],
            'newEnterpriseType' => $ep['enterpriseType'],
            'newIndustryFieldNew' => $ep['industryFieldNew'],
            'newIndustryFieldOld' => $ep['industryFieldOld'],
            'newBankCard' => $ep['bankCard'],
            'newBank' => $ep['bank'],
            'newBankNetwork' => $ep['bankNetwork']
        ];
        if ($ep["imgurl"]) {
            $ecr["imgurl"] = $ep["imgurl"];
            $extension = pathinfo($ep["imgurl"])["extension"];
            if (in_array($extension, ["jpeg", "jpg", "png", "gif"])) {
                $ecr["imgurl_is_img"] = 1;
            }
        }
        if ($ep["bankImg"]) {
            $ecr["bankImg"] = $ep["bankImg"];
            $extension = pathinfo($ep["bankImg"])["extension"];
            if (in_array($extension, ["jpeg", "jpg", "png", "gif"])) {
                $ecr["bankImg_is_img"] = 1;
            }
        }
        if ($ep["domainImg"]) {
            $ecr["domainImg"] = $ep["domainImg"];
            $extension = pathinfo($ep["domainImg"])["extension"];
            if (in_array($extension, ["jpeg", "jpg", "png", "gif"])) {
                $ecr["domainImg_is_img"] = 1;
            }
        }
        if ($ep["typeImg"]) {
            $ecr["typeImg"] = $ep["typeImg"];
            $extension = pathinfo($ep["typeImg"])["extension"];
            if (in_array($extension, ["jpeg", "jpg", "png", "gif"])) {
                $ecr["typeImg_is_img"] = 1;
            }
        }
        if ($ep["beian"]) {
            $ecr["beian"] = $ep["beian"];
            $extension = pathinfo($ep["beian"])["extension"];
            if (in_array($extension, ["jpeg", "jpg", "png", "gif"])) {
                $ecr["beian_is_img"] = 1;
            }
        }

        switch ($ep['checkState']) {
            case 1:
                $ecr['checkStateName'] = '保存未提交审核';
                break;
            case 2:
                $ecr['checkStateName'] = '待审核';
                break;
            case 3:
                $ecr['checkStateName'] = '审核驳回';
                break;
            case 4:
                $ecr['checkStateName'] = '审核通过';
                break;
            case 5:
                $ecr['checkStateName'] = '重新提交';
                break;
            default:
                $ecr['checkStateName'] = '';
        }
        $template = "";
        $assigns = [];
        switch ($ep->type) {
            case CommonConst::ENTERPRISE_WJ:
                $template = "/api/hospital/to_add";
                $assigns["medicalCommunities"] = \app\common\api\Nhc::getMedicalCommunityList();
                break;
            case CommonConst::ENTERPRISE_GJ:
                $template = "/api/school/to_add";
                break;
        }
        $assigns["ecr"] = $ecr;
        return view($template, $assigns);
    }

    public function upsert() {
        $data = [
            'id' => \StrUtil::getRequestDecodeParam($this->request, 'enterprise_id'),
            'name' => \StrUtil::getRequestDecodeParam($this->request, 'newName'), //单位名称
            'idCard' => \StrUtil::getRequestDecodeParam($this->request, 'newIdCard'), //统一社会信用代码
            'medicalCommunityId' => \StrUtil::getRequestDecodeParam($this->request, 'newMedicalCommunityId'), //医共体
            'isGeneral' => \StrUtil::getRequestDecodeParam($this->request, 'newIsGeneral'), //是否总院
            'agentName' => \StrUtil::getRequestDecodeParam($this->request, 'newAgentName'), //人才联络员
            'agentPhone' => \StrUtil::getRequestDecodeParam($this->request, 'newAgentPhone'), //人才联络员电话
            'legal' => \StrUtil::getRequestDecodeParam($this->request, 'newLegal'), //法人
            'street' => \StrUtil::getRequestDecodeParam($this->request, 'newStreet'), //镇街
            'province' => \StrUtil::getRequestDecodeParam($this->request, 'newProvince'), //地址省
            'city' => \StrUtil::getRequestDecodeParam($this->request, 'newCity'), //地址市
            'county' => \StrUtil::getRequestDecodeParam($this->request, 'newCounty'), //地址县区
            'address' => \StrUtil::getRequestDecodeParam($this->request, 'newAddress'), //地址
            'type' => intval($this->request['type']),
            'agencyType' => intval($this->request['newAgencyType']),
            'enterpriseTag' => \StrUtil::getRequestDecodeParam($this->request, 'newEnterpriseTag'), //单位标签
            'organizationTag' => \StrUtil::getRequestDecodeParam($this->request, 'newOrganizationTag'), //机构标签
            'institutionTag' => \StrUtil::getRequestDecodeParam($this->request, 'newInstitutionTag'), //事业单位标签
            'enterpriseType' => \StrUtil::getRequestDecodeParam($this->request, 'newEnterpriseType'), //单位类型
            'agentEmail' => \StrUtil::getRequestDecodeParam($this->request, 'newAgentEmail'), //邮箱
            'ephone' => \StrUtil::getRequestDecodeParam($this->request, 'newEphone'), //单位电话
            'industryFieldNew' => \StrUtil::getRequestDecodeParam($this->request, 'newIndustryFieldNew'), //产业领域
            'industryFieldOld' => \StrUtil::getRequestDecodeParam($this->request, 'newIndustryFieldOld'), //行业领域
            'bankCard' => \StrUtil::getRequestDecodeParam($this->request, 'newBankCard'), //银行
            'bank' => \StrUtil::getRequestDecodeParam($this->request, 'newBank'), //开户行
            'bankNetwork' => \StrUtil::getRequestDecodeParam($this->request, 'newBankNetwork')//网点
        ];
        $response_object = new \stdClass();
        try {
            if (stripos($data['name'], "(")) {
                $data['name'] = str_replace('(', '（', $data['name']);
            }

            if (stripos($data['name'], ")")) {
                $data['name'] = str_replace(')', '）', $data['name']);
            }
            $ep = Enterprise::where('id', session("user")["uid"])->find();
            if (!in_array($ep["checkState"], [1, 3, 6])) {
                throw new ValidateException("审核中，请耐心等待");
            }
            switch ($ep->special) {
                case 0:
                    if ($ep->type == CommonConst::ENTERPRISE_JC) {
                        validate(\app\common\validate\Enterprise::class)->batch(true)->scene('jc_change')->check($data);
                    } else if ($ep->type == CommonConst::ENTERPRISE_WJ) {
                        validate(\app\common\validate\Hospital::class)->batch(true)->scene('change')->check($data);
                    } else if ($ep->type == CommonConst::ENTERPRISE_GJ) {
                        validate(\app\common\validate\School::class)->batch(true)->scene('change')->check($data);
                    } else {
                        if ($data["agencyType"] == 1) {
                            validate(\app\common\validate\Enterprise::class)->batch(true)->scene('change')->check($data);
                        } else {
                            validate(\app\common\validate\Enterprise::class)->batch(true)->scene('change2')->check($data);
                        }
                    }
                    break;
                case 1:
                    validate(\app\common\validate\Enterprise::class)->batch(true)->scene('sy_change')->check($data);
                    break;
                default:

                    break;
            }

            $record_id = \StrUtil::getRequestDecodeParam($this->request, 'id');
            if (!$record_id) {
                $record_id = getStringId();
                $record_data = [
                    'id' => $record_id,
                    'mainId' => $data['id'],
                    'type' => $data['type'],
                    'oldAgencyType' => $ep['agencyType'],
                    'oldName' => $ep['name'],
                    'oldIdCard' => $ep['idCard'],
                    'oldMedicalCommunityId' => $ep['medicalCommunityId'],
                    'oldIsGeneral' => $ep['isGeneral'],
                    'oldIndustryFieldNew' => $ep['industryFieldNew'],
                    'oldIndustryFieldOld' => $ep['industryFieldOld'],
                    'oldStreet' => $ep['street'],
                    'oldProvince' => $ep['province'],
                    'oldCity' => $ep['city'],
                    'oldCounty' => $ep['county'],
                    'oldProvinceName' => $ep['provinceName'],
                    'oldCityName' => $ep['cityName'],
                    'oldCountyName' => $ep['countyName'],
                    'oldAddress' => $ep['address'],
                    'oldLegal' => $ep['legal'],
                    'oldEphone' => $ep['ephone'],
                    'oldAgentName' => $ep['agentName'],
                    'oldAgentEmail' => $ep['agentEmail'],
                    'oldAgentPhone' => $ep['agentPhone'],
                    'oldEnterpriseTag' => $ep['enterpriseTag'],
                    'oldOrganizationTag' => $ep['organizationTag'],
                    'oldInstitutionTag' => $ep['institutionTag'],
                    'oldEnterpriseType' => $ep['enterpriseType'],
                    'oldBankCard' => $ep['bankCard'],
                    'oldBank' => $ep['bank'],
                    'oldBankNetwork' => $ep['bankNetwork'],
                    "oldImgurl" => $ep["imgurl"],
                    "oldBankImg" => $ep["bankImg"],
                    "oldDomainImg" => $ep["domainImg"],
                    "oldTypeImg" => $ep["typeImg"],
                    "oldBeian" => $ep["beian"],
                    'newAgencyType' => $data['agencyType'],
                    'newName' => htmlspecialchars($data['name']),
                    'newIdCard' => htmlspecialchars($data['idCard']),
                    'newMedicalCommunityId' => $data['medicalCommunityId'],
                    'newIsGeneral' => $data['isGeneral'],
                    'newIndustryFieldNew' => $data['industryFieldNew'],
                    'newIndustryFieldOld' => $data['industryFieldOld'],
                    'newStreet' => $data['street'],
                    'newProvince' => $data['province'],
                    'newCity' => $data['city'],
                    'newCounty' => $data['county'],
                    'newProvinceName' => $data['province'] ? LocationApi::getNameByCode($data['province']) : null,
                    'newCityName' => $data['city'] ? LocationApi::getNameByCode($data['city']) : null,
                    'newCountyName' => $data['county'] ? LocationApi::getNameByCode($data['county']) : null,
                    'newAddress' => $data['address'],
                    'newLegal' => $data['legal'],
                    'newEphone' => $data['ephone'],
                    'newAgentName' => $data['agentName'],
                    'newAgentEmail' => $data['agentEmail'],
                    'newAgentPhone' => $data['agentPhone'],
                    'newEnterpriseTag' => $data['enterpriseTag'],
                    'newOrganizationTag' => $data['organizationTag'],
                    'newInstitutionTag' => $data['institutionTag'],
                    'newEnterpriseType' => $data['enterpriseType'],
                    'newBankCard' => $data['bankCard'],
                    'newBank' => $data['bank'],
                    'newBankNetwork' => $data['bankNetwork'],
                    'checkState' => 1,
                    'createTime' => date("Y-m-d H:i:s", time()),
                    'createUser' => session("user")["uid"]
                ];
                $record_data["newImgurl"] = $ep["imgurl"];
                $record_data["newBankImg"] = $ep["bankImg"];
                $record_data["newDomainImg"] = $ep["domainImg"];
                $record_data["newTypeImg"] = $ep["typeImg"];
                $record_data["newBeian"] = $ep["beian"];
                if ($data["agencyType"] != 1) {
                    $record_data["newIndustryFieldNew"] = null;
                    $record_data["newIndustryFieldOld"] = null;
                    $record_data["newDomainImg"] = null;
                }
                $files = $this->request->file();
                if ($files) {
                    $uploadapi = new UploadApi();
                    if (array_key_exists('imgurl', $files)) {
                        $upload_result = $uploadapi->uploadOne($this->request->file('imgurl'), 'system');
                        if ($upload_result->code == 500) {
                            return \StrUtil::back($upload_result, "EpChangeEdit.callBack");
                        }
                        $record_data["newImgurl"] = $upload_result->filepath;
                    }

                    //检验附件 开户许可证
                    if (array_key_exists('bankImg', $files)) {
                        $upload_result1 = $uploadapi->uploadOne($this->request->file('bankImg'), 'system');
                        if ($upload_result1->code == 500) {
                            return \StrUtil::back($upload_result1, "EpChangeEdit.callBack");
                        }
                        $record_data["newBankImg"] = $upload_result1->filepath;
                    }

                    //检验附件 行业领域佐证材料
                    if (array_key_exists('domainImg', $files) && $data['agencyType'] == 1) {
                        $upload_result2 = $uploadapi->uploadOne($this->request->file('domainImg'), 'system');
                        if ($upload_result2->code == 500) {
                            return \StrUtil::back($upload_result2, "EpChangeEdit.callBack");
                        }
                        $record_data["newDomainImg"] = $upload_result2->filepath;
                    }

                    //检验附件 三种类型企业上传材料
                    if (array_key_exists('typeImg', $files)) {
                        $upload_result4 = $uploadapi->uploadOne($this->request->file('typeImg'), 'system');
                        if ($upload_result4->code == 500) {
                            return \StrUtil::back($upload_result4, "EpChangeEdit.callBack");
                        }
                        $record_data["newTypeImg"] = $upload_result4->filepath;
                    }

                    //检验附件 人才联络员备案表
                    if (array_key_exists('beian', $files)) {
                        $upload_result3 = $uploadapi->uploadOne($this->request->file('beian'), 'system');
                        if ($upload_result3->code == 500) {
                            return \StrUtil::back($upload_result3, "EpChangeEdit.callBack");
                        }
                        $record_data["newBeian"] = $upload_result3->filepath;
                    }
                }
                if (!$record_data["newImgurl"]) {
                    throw new ValidateException("请上传营业执照");
                }
                if ($ep->special == 0) {
                    if (!$record_data["newBankImg"] && ($ep->type == CommonConst::ENTERPRISE_NORMAL || $ep->type == CommonConst::ENTERPRISE_WJ)) {
                        throw new ValidateException("请上传开户许可证/基本存款账户信息");
                    }
                    if ($ep->type == CommonConst::ENTERPRISE_NORMAL && $data['agencyType'] == 1 && !$record_data["newDomainImg"]) {
                        throw new ValidateException("请上传行业领域佐证材料");
                    }
                    if (in_array($record_data["newEnterpriseType"], ["guishang", "gaoxinjishu", "zhuanjingtexin"]) && !$record_data["newTypeImg"]) {
                        throw new ValidateException("规上、高新技术、专精特新企业需要上传佐证材料");
                    }
                    if (!in_array($record_data["newEnterpriseType"], ["guishang", "gaoxinjishu", "zhuanjingtexin"])) {
                        $record_data["newTypeImg"] = null;
                    }
                }
                if (!$record_data["newBeian"]) {
                    throw new ValidateException("请上传人才联络员信息备案表");
                }
                EnterpriseRecord::create($record_data);
                $log = [
                    'id' => getStringId(),
                    'mainId' => $record_data['id'],
                    'category' => 'enterprise_change',
                    'type' => 10,
                    'active' => 1,
                    'state' => 1,
                    'step' => 100,
                    'stateChange' => '保存未提交',
                    'description' => '机构信息变更记录添加成功',
                    'createTime' => date("Y-m-d H:i:s", time()),
                    'createUser' => '用户'
                ];
                $success_msg = "添加成功";
                //$res = ['msg' => '添加成功', 'code' => 200, 'obj' => $record_data];
            } else {
                $record = EnterpriseRecord::find($record_id);
                $ep = Enterprise::where('id', session("user")["uid"])->find();
                $record->oldAgencyType = $ep['agencyType'];
                $record->oldName = $ep['name'];
                $record->oldIdCard = $ep['idCard'];
                $record->oldMedicalCommunityId = $ep['medicalCommunityId'];
                $record->oldIsGeneral = $ep['isGeneral'];
                $record->oldIndustryFieldNew = $ep['industryFieldNew'];
                $record->oldIndustryFieldOld = $ep['industryFieldOld'];
                $record->oldStreet = $ep['street'];
                $record->oldProvince = $ep['province'];
                $record->oldCity = $ep['city'];
                $record->oldCounty = $ep['county'];
                $record->oldProvinceName = $ep['provinceName'];
                $record->oldCityName = $ep['cityName'];
                $record->oldCountyName = $ep['countyName'];
                $record->oldAddress = $ep['address'];
                $record->oldLegal = $ep['legal'];
                $record->oldEphone = $ep['ephone'];
                $record->oldAgentName = $ep['agentName'];
                $record->oldAgentEmail = $ep['agentEmail'];
                $record->oldAgentPhone = $ep['agentPhone'];
                $record->oldEnterpriseTag = $ep['enterpriseTag'];
                $record->oldOrganizationTag = $ep['organizationTag'];
                $record->oldInstitutionTag = $ep['institutionTag'];
                $record->oldEnterpriseType = $ep['enterpriseType'];
                $record->oldBankCard = $ep['bankCard'];
                $record->oldBank = $ep['bank'];
                $record->oldBankNetwork = $ep['bankNetwork'];
                if ($record->checkState == 1) {
                    $record->newAgencyType = $data['agencyType'];
                    $record->newName = htmlspecialchars($data['name']);
                    $record->newIdCard = htmlspecialchars($data['idCard']);
                    $record->newMedicalCommunityId = htmlspecialchars($data['medicalCommunityId']);
                    $record->newIsGeneral = htmlspecialchars($data['isGeneral']);
                    if ($data["agencyType"] == 1) {
                        $record->newIndustryFieldNew = $data['industryFieldNew'];
                        $record->newIndustryFieldOld = $data['industryFieldOld'];
                    } else {
                        $record->newIndustryFieldNew = null;
                        $record->newIndustryFieldOld = null;
                    }
                    $record->newStreet = $data['street'];
                    $record->newProvince = $data['province'];
                    $record->newCity = $data['city'];
                    $record->newCounty = $data['county'];
                    $record->newAddress = $data['address'];
                    $record->newLegal = $data['legal'];
                    $record->newEphone = $data['ephone'];
                    $record->newAgentName = $data['agentName'];
                    $record->newAgentEmail = $data['agentEmail'];
                    $record->newAgentPhone = $data['agentPhone'];
                    $record->newEnterpriseTag = $data['enterpriseTag'];
                    $record->newOrganizationTag = $data['organizationTag'];
                    $record->newInstitutionTag = $data['institutionTag'];
                    $record->newEnterpriseType = $data['enterpriseType'];
                    $record->newBankCard = $data['bankCard'];
                    $record->newBank = $data['bank'];
                    $record->newBankNetwork = $data['bankNetwork'];
                } else {
                    $fields = array_filter(explode(",", $record->modify_fields));
                    for ($i = 0; $i < count($fields); $i++) {
                        $key = lcfirst(substr($fields[$i], 3));
                        $record[$fields[$i]] = $data[$key]; //仅可修改选择的字段
                    }
                }
                $record->newProvinceName = $data['province'] ? LocationApi::getNameByCode($data['province']) : null;
                $record->newCityName = $data['city'] ? LocationApi::getNameByCode($data['city']) : null;
                $record->newCountyName = $data['county'] ? LocationApi::getNameByCode($data['county']) : null;
                if (!$record["newImgurl"]) {
                    if (strtotime($record["createTime"]) < strtotime($this->compatible_time)) {
                        $where = [];
                        $where[] = ["mainId", "=", $record_id];
                        $where[] = ["api", "=", "businessLicense"];
                        $where[] = ["active", "=", 1];
                        $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                        if ($_uploadFile) {
                            $record["newImgurl"] = $_uploadFile["url"];
                        } else {
                            $record["newImgurl"] = $ep["imgurl"];
                        }
                    }
                }
                if (!$record["newBankImg"]) {
                    if (strtotime($record["createTime"]) < strtotime($this->compatible_time)) {
                        $where = [];
                        $where[] = ["mainId", "=", $record_id];
                        $where[] = ["api", "=", "businessBank"];
                        $where[] = ["active", "=", 1];
                        $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                        if ($_uploadFile) {
                            $record["newBankImg"] = $_uploadFile["url"];
                        } else {
                            $record["newBankImg"] = $ep["bankImg"];
                        }
                    }
                }
                if (!$record["newDomainImg"]) {
                    if (strtotime($record["createTime"]) < strtotime($this->compatible_time)) {
                        $where = [];
                        $where[] = ["mainId", "=", $record_id];
                        $where[] = ["api", "=", "businessDomain"];
                        $where[] = ["active", "=", 1];
                        $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                        if ($_uploadFile) {
                            $record["newDomainImg"] = $_uploadFile["url"];
                        } else {
                            $record["newDomainImg"] = $ep["domainImg"];
                        }
                    }
                }
                if (!$record["newBeian"]) {
                    if (strtotime($record["createTime"]) < strtotime($this->compatible_time)) {
                        $where = [];
                        $where[] = ["mainId", "=", $record_id];
                        $where[] = ["api", "=", "businessBeian"];
                        $where[] = ["active", "=", 1];
                        $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                        if ($_uploadFile) {
                            $record["newBeian"] = $_uploadFile["url"];
                        } else {
                            $record["newBeian"] = $ep["beian"];
                        }
                    }
                }
                $files = $this->request->file();
                if ($files) {
                    $uploadapi = new UploadApi();
                    $modify_files = array_filter(explode(",", $record->modify_files)); //["newImgurl", "newBankImg", "newDomainImg", "newTypeImg", "newBeian"];
                    if (strtotime($record->createTime) < strtotime($this->compatible_time)) {
                        //旧typeid需要转换成新的禁用文件格式
                        $oldtypes = ["1161965644164075522" => "newImgurl", "1518753449987148467" => "newImgurl", "1518328155588131269" => "newBankImg", "1518926324960220206" => "newBankImg",
                            "1518941016720463523" => "newDomainImg", "1519109971871948101" => "newBeian", "1519185486755815382" => "newBeian"];
                        foreach ($modify_files as $key => $_typeId) {
                            if ($oldtypes[$_typeId]) {
                                $modify_files[$key] = $oldtypes[$_typeId];
                            }
                        }
                    }
                    $uploadAllowed = $record->checkState == 1 || ($record->checkState != 1 && in_array("newImgurl", $modify_files)) ? true : false;
                    if (array_key_exists('imgurl', $files) && $uploadAllowed) {
                        $upload_result = $uploadapi->uploadOne($this->request->file('imgurl'), 'system');
                        if ($upload_result->code == 500) {
                            return \StrUtil::back($upload_result, "EpChangeEdit.callBack");
                        }
                        $record["newImgurl"] = $upload_result->filepath;
                    }

                    //检验附件 开户许可证
                    $uploadAllowed = $record->checkState == 1 || ($record->checkState != 1 && in_array("newBankImg", $modify_files)) ? true : false;
                    if (array_key_exists('bankImg', $files) && $uploadAllowed) {
                        $upload_result1 = $uploadapi->uploadOne($this->request->file('bankImg'), 'system');
                        if ($upload_result1->code == 500) {
                            return \StrUtil::back($upload_result1, "EpChangeEdit.callBack");
                        }
                        $record["newBankImg"] = $upload_result1->filepath;
                    }

                    //检验附件 行业领域佐证材料
                    $uploadAllowed = $record->checkState == 1 || ($record->checkState != 1 && in_array("newDomainImg", $modify_files)) ? true : false;
                    if (array_key_exists('domainImg', $files) && $uploadAllowed) {
                        $upload_result2 = $uploadapi->uploadOne($this->request->file('domainImg'), 'system');
                        if ($upload_result2->code == 500) {
                            return \StrUtil::back($upload_result2, "EpChangeEdit.callBack");
                        }
                        $record["newDomainImg"] = $upload_result2->filepath;
                    }

                    //检验附件 规上、高新技术、专精特新企业需要上传佐证材料
                    $uploadAllowed = $record->checkState == 1 || ($record->checkState != 1 && in_array("newTypeImg", $modify_files)) ? true : false;
                    if (array_key_exists('typeImg', $files) && $uploadAllowed) {
                        $upload_result4 = $uploadapi->uploadOne($this->request->file('typeImg'), 'system');
                        if ($upload_result4->code == 500) {
                            return \StrUtil::back($upload_result4, "EpChangeEdit.callBack");
                        }
                        $record["newTypeImg"] = $upload_result4->filepath;
                    }

                    //检验附件 人才联络员备案表
                    $uploadAllowed = $record->checkState == 1 || ($record->checkState != 1 && in_array("newBeian", $modify_files)) ? true : false;
                    if (array_key_exists('beian', $files) && $uploadAllowed) {
                        $upload_result3 = $uploadapi->uploadOne($this->request->file('beian'), 'system');
                        if ($upload_result3->code == 500) {
                            return \StrUtil::back($upload_result3, "EpChangeEdit.callBack");
                        }
                        $record["newBeian"] = $upload_result3->filepath;
                    }
                }
                if (!$record["newImgurl"]) {
                    throw new ValidateException("请上传营业执照");
                }
                if ($ep->special == 0) {
                    if (!$record["newBankImg"] && ($ep->type == CommonConst::ENTERPRISE_NORMAL || $ep->type == CommonConst::ENTERPRISE_WJ)) {
                        throw new ValidateException("请上传开户许可证/基本存款账户信息");
                    }
                    if ($ep->type == CommonConst::ENTERPRISE_NORMAL && $data["agencyType"] == 1 && !$record["newDomainImg"]) {
                        throw new ValidateException("请上传行业领域佐证材料");
                    }
                    if ($data["agencyType"] != 1) {
                        $record["newDomainImg"] = null;
                    }
                    if (in_array($record->newEnterpriseType, ["guishang", "gaoxinjishu", "zhuanjingtexin"]) && !$record["newTypeImg"]) {
                        throw new ValidateException("规上、高新技术、专精特新企业需要上传佐证材料");
                    }
                    if (!in_array($record->newEnterpriseType, ["guishang", "gaoxinjishu", "zhuanjingtexin"])) {
                        $record["newTypeImg"] = null;
                    }
                }
                if (!$record["newBeian"]) {
                    throw new ValidateException("请上传人才联络员信息备案表");
                }

                $record->updateTime = date("Y-m-d H:i:s");
                $record->updateUser = session("user")["uid"];
                $record->save();

                $log = [
                    'id' => getStringId(),
                    'category' => 'enterprise_change',
                    'mainId' => '',
                    'type' => 10,
                    'active' => 1,
                    'state' => 1,
                    'step' => 100,
                    'stateChange' => '保存未提交',
                    'description' => '机构信息变更记录修改成功',
                    'createTime' => date("Y-m-d H:i:s", time()),
                    'createUser' => '用户'
                ];
                $success_msg = "修改成功";
                //$res = ['msg' => '修改成功', 'code' => 200, 'obj' => $record];
            }

            TalentChecklog::create($log);
            $response_object->id = $record_id;
            $response_object->code = 200;
            $response_object->msg = $success_msg;
            return \StrUtil::back($response_object, "EpChangeEdit.callBack");
            //return json($res);
        } catch (ValidateException $e) {
            $response_object->code = 500;
            $response_object->msg = is_array($e->getError()) ? implode("<br>", $e->getError()) : $e->getError();
            return \StrUtil::back($response_object, "EpChangeEdit.callBack");
            //return json(["msg" => array_pop($error), 'code' => 500]);
        }
    }

    public function toUpdate() {
        $id = trim($this->request['id']);
        $ecr = EnterpriseRecord::findOrEmpty($id);
        $ep = Enterprise::where('id', $ecr->mainId)->find();
        $ecr["special"] = $ep["special"];
        $time = $this->compatible_time;
        if (strtotime($ecr["createTime"]) < strtotime($time)) {
            $_files = explode(",", $ecr["modify_files"]);
            $_new_files = [];
            foreach ($_files as $_file) {
                $where = [];
                $where[] = ["id", "=", $_file];
                $_filetype = CurrentcyFileType::where($where)->find();
                switch ($_filetype["api"]) {
                    case "businessLicense":
                        $_new_files[] = "newImgurl";
                        break;
                    case "businessBank";
                        $_new_files[] = "newBankImg";
                        break;
                    case "businessDomain";
                        $_new_files[] = "newDomainImg";
                        break;
                    case "businessBeian";
                        $_new_files[] = "newBeian";
                        break;
                    default:
                        $_new_files[] = $_file;
                        break;
                }
            }
            $ecr["modify_files"] = implode(",", $_new_files);
        }
        //营业执照
        if (!$ecr["newImgurl"]) {
            //兼容旧filetype
            if (strtotime($ecr["createTime"]) < strtotime($time)) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["api", "=", "businessLicense"];
                $where[] = ["active", "=", 1];
                $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                if ($_uploadFile) {
                    $ecr["newImgurl"] = $_uploadFile["url"];
                } else {
                    $ecr["newImgurl"] = $ep["imgurl"];
                }
            }
        }
        if ($ecr["newImgurl"]) {
            $pathinfo = pathinfo($ecr["newImgurl"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["imgurl_is_img"] = 1;
            }
        }
        //备案表
        if (!$ecr["newBeian"]) {
            //兼容旧filetype
            if (strtotime($ecr["createTime"]) < strtotime($time)) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["api", "=", "businessBeian"];
                $where[] = ["active", "=", 1];
                $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                if ($_uploadFile) {
                    $ecr["newBeian"] = $_uploadFile["url"];
                } else {
                    $ecr["newBeian"] = $ep["beian"];
                }
            }
        }
        if ($ecr["newBeian"]) {
            $pathinfo = pathinfo($ecr["newBeian"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["beian_is_img"] = 1;
            }
        }
        //行业领域
        if (!$ecr["newDomainImg"]) {
            //兼容旧filetype
            if (strtotime($ecr["createTime"]) < strtotime($time)) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["api", "=", "businessDomain"];
                $where[] = ["active", "=", 1];
                $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                if ($_uploadFile) {
                    $ecr["newDomainImg"] = $_uploadFile["url"];
                } else {
                    $ecr["newDomainImg"] = $ep["domainImg"];
                }
            }
        }
        if ($ecr["newDomainImg"]) {
            $pathinfo = pathinfo($ecr["newDomainImg"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["domainImg_is_img"] = 1;
            }
        }
        //规上、高新技术、专精特新企业需要上传佐证材料        
        if ($ecr["newTypeImg"]) {
            $pathinfo = pathinfo($ecr["newTypeImg"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["typeImg_is_img"] = 1;
            }
        }
        //开户许可证
        if (!$ecr["newBankImg"]) {
            //兼容旧filetype
            if (strtotime($ecr["createTime"]) < strtotime($time)) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["api", "=", "businessBank"];
                $where[] = ["active", "=", 1];
                $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                if ($_uploadFile) {
                    $ecr["newBankImg"] = $_uploadFile["url"];
                } else {
                    $ecr["newBankImg"] = $ep["bankImg"];
                }
            }
        }
        if ($ecr["newBankImg"]) {
            $pathinfo = pathinfo($ecr["newBankImg"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["bankImg_is_img"] = 1;
            }
        }
        $template = "";
        $assigns = [];
        switch ($ep->type) {
            case CommonConst::ENTERPRISE_WJ:
                $template = "/api/hospital/to_update";
                $assigns["medicalCommunities"] = \app\common\api\Nhc::getMedicalCommunityList();
                break;
            case CommonConst::ENTERPRISE_GJ:
                $template = "/api/school/to_update";
                break;
        }
        $assigns["ecr"] = $ecr;
        return view($template, $assigns);
    }

    public function submitToCheck() {
        $id = trim($this->request->post('id'));
        if (!$id) {
            return json(['msg' => '记录为空', 'code' => 500]);
        }
        $obj = EnterpriseRecord::find($id);

        if (!$obj) {
            return json(['msg' => '提交审核失败，请先填写基础信息', 'code' => 500]);
        }

        if (!in_array($obj["checkState"], [1, 3, 6])) {
            return json(['msg' => '不能重复提交审核', 'code' => 500]);
        }

        $ep = EnterpriseApi::getOne($obj->mainId);

        //20220918增加根据不同的企业类型显示不同的信息变更界面|20221014废弃使用filetype
        /* switch ($ep->special) {
          case 0:
          $org_type = 'enterpriseChange';
          break;
          case 1:
          $org_type = 'governmentChange';
          break;
          default:

          break;
          }

          $list = CurrentcyFileType::where('type', $org_type)->where('active', 1)->select();
          if (!$list || count($list) <= 0) {
          return json(['msg' => '缺少附件', 'code' => 500]);
          }
          $error_msg = "";
          foreach ($list as $k => $v) {
          if ($v['must'] == 1) {
          $count = TalentCommonFile::where('mainId', $id)->where('typeId', $v['id'])->count();
          if ($count == 0) {
          if (strlen($error_msg) == 0) {
          $error_msg = "以下为必传附件：";
          }
          $error_msg .= $v['name'] . ";";
          }
          }
          }
          if (strlen($error_msg) > 0) {
          return json(['msg' => $error_msg, 'code' => 500]);
          } */
        if ($obj['checkState'] == 3 || $obj['checkState'] == 6) {
            $obj['checkState'] = 5;
            $state = 5;
        } else {
            $obj['checkState'] = 2;
            $state = 2;
        }
        $obj->save();

        $log = [
            'id' => getStringId(),
            'category' => 'enterprise_change',
            'mainId' => $id,
            'type' => 10,
            'active' => 1,
            'state' => $state,
            'step' => 100,
            'stateChange' => "<span class='label'>待提交</span>-><span class='label label-success'>待审核</span>",
            'description' => '提交审核',
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => '用户'
        ];
        TalentChecklog::create($log);
        return json(['msg' => '提交审核成功', 'code' => 200, 'obj' => 1]);
    }

    public function toDetail() {
        $id = trim($this->request['id']);
        if (!$id) {
            return json(['msg' => '记录为空', 'code' => 500]);
        }
        $ecr = EnterpriseRecord::find($id);
        $ep = EnterpriseApi::getOne($ecr['mainId']);
        $streetList = DictApi::selectByParentCode('street');
        $ecr["special"] = $ep["special"];
        $ecr['oldStreetName'] = $streetList[$ecr['oldStreet']];
        $ecr['newStreetName'] = $streetList[$ecr['newStreet']];
        //20220918增加根据不同的企业类型显示不同的信息变更界面
        $time = $this->compatible_time;
        //营业执照
        if (!$ecr["oldImgurl"]) {
            $ecr["oldImgurl"] = $ep["imgurl"];
        }
        if ($ecr["oldImgurl"]) {
            $pathinfo = pathinfo($ecr["oldImgurl"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["oldImgurl_is_img"] = 1;
            }
        }
        if (!$ecr["newImgurl"]) {
            //兼容旧filetype
            if (strtotime($ecr["createTime"]) < strtotime($time)) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["api", "=", "businessLicense"];
                $where[] = ["active", "=", 1];
                $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                if ($_uploadFile) {
                    $ecr["newImgurl"] = $_uploadFile["url"];
                } else {
                    $ecr["newImgurl"] = $ep["imgurl"];
                }
            }
        }
        if ($ecr["newImgurl"]) {
            $pathinfo = pathinfo($ecr["newImgurl"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["newImgurl_is_img"] = 1;
            }
        }
        //备案表
        if (!$ecr["oldBeian"]) {
            $ecr["oldBeian"] = $ep["beian"];
        }
        if ($ecr["oldBeian"]) {
            $pathinfo = pathinfo($ecr["oldBeian"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["oldBeian_is_img"] = 1;
            }
        }
        if (!$ecr["newBeian"]) {
            //兼容旧filetype
            if (strtotime($ecr["createTime"]) < strtotime($time)) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["api", "=", "businessBeian"];
                $where[] = ["active", "=", 1];
                $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                if ($_uploadFile) {
                    $ecr["newBeian"] = $_uploadFile["url"];
                } else {
                    $ecr["newBeian"] = $ep["beian"];
                }
            }
        }
        if ($ecr["newBeian"]) {
            $pathinfo = pathinfo($ecr["newBeian"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["newBeian_is_img"] = 1;
            }
        }
        //行业领域
        if (!$ecr["oldDomainImg"]) {
            $ecr["oldDomainImg"] = $ep["domainImg"];
        }
        if ($ecr["oldDomainImg"]) {
            $pathinfo = pathinfo($ecr["oldDomainImg"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["oldDomainImg_is_img"] = 1;
            }
        }
        if (!$ecr["newDomainImg"]) {
            //兼容旧filetype
            if (strtotime($ecr["createTime"]) < strtotime($time)) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["api", "=", "businessDomain"];
                $where[] = ["active", "=", 1];
                $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                if ($_uploadFile) {
                    $ecr["newDomainImg"] = $_uploadFile["url"];
                } else {
                    $ecr["newDomainImg"] = $ep["domainImg"];
                }
            }
        }
        if ($ecr["newDomainImg"]) {
            $pathinfo = pathinfo($ecr["newDomainImg"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["newDomainImg_is_img"] = 1;
            }
        }
        //规上、高新技术、专精特新企业需要上传佐证材料
        if ($ecr["oldTypeImg"]) {
            $pathinfo = pathinfo($ecr["oldTypeImg"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["oldTypeImg_is_img"] = 1;
            }
        }
        if ($ecr["newTypeImg"]) {
            $pathinfo = pathinfo($ecr["newTypeImg"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["newTypeImg_is_img"] = 1;
            }
        }
        //开户许可证
        if (!$ecr["oldBankImg"]) {
            $ecr["oldBankImg"] = $ep["bankImg"];
        }
        if ($ecr["oldBankImg"]) {
            $pathinfo = pathinfo($ecr["oldBankImg"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["oldBankImg_is_img"] = 1;
            }
        }
        if (!$ecr["newBankImg"]) {
            //兼容旧filetype
            if (strtotime($ecr["createTime"]) < strtotime($time)) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["api", "=", "businessBank"];
                $where[] = ["active", "=", 1];
                $_uploadFile = TalentCommonFile::alias("tcf")->leftJoin("new_currency_filetype ft", "ft.id=tcf.typeId")->where($where)->order("tcf.createTime desc")->find();
                if ($_uploadFile) {
                    $ecr["newBankImg"] = $_uploadFile["url"];
                } else {
                    $ecr["newBankImg"] = $ep["bankImg"];
                }
            }
        }
        if ($ecr["newBankImg"]) {
            $pathinfo = pathinfo($ecr["newBankImg"]);
            if (in_array($pathinfo["extension"], ["jpeg", "jpg", "png", "gif"])) {
                $ecr["newBankImg_is_img"] = 1;
            }
        }
        switch ($ep->special) {
            case 0:
                $agencyTypeList = DictApi::selectByParentCode('agency_type');
                $tagList = DictApi::selectByParentCode('enterprise_tag');
                $typeList = DictApi::selectByParentCode('enterprise_type');
                $industryFieldNew = DictApi::selectByParentCode('industry_field');
                $industry = DictApi::findDictByCode($ecr['oldIndustryFieldOld']);
                $ecr['oldIndustryFieldOldName'] = $industry['name'];
                $industry = DictApi::findDictByCode($ecr['newIndustryFieldOld']);
                $ecr['newIndustryFieldOldName'] = $industry['name'];
                $ecr['oldEnterpriseTagName'] = $tagList[$ecr['oldEnterpriseTag']];
                $ecr['newEnterpriseTagName'] = $tagList[$ecr['newEnterpriseTag']];
                $ecr['oldEnterpriseTypeName'] = $typeList[$ecr['oldEnterpriseType']];
                $ecr['newEnterpriseTypeName'] = $typeList[$ecr['newEnterpriseType']];
                $ecr['oldIndustryFieldNewName'] = $industryFieldNew[$ecr['oldIndustryFieldNew']];
                $ecr['newIndustryFieldNewName'] = $industryFieldNew[$ecr['newIndustryFieldNew']];
                $ecr['oldAgencyTypeName'] = $agencyTypeList[$ecr['oldAgencyType']];
                $ecr['newAgencyTypeName'] = $agencyTypeList[$ecr['newAgencyType']];
                break;
            case 1:
                $tagList = DictApi::selectByParentCode('institution_tag');
                $ecr['oldInstitutionTagName'] = $tagList[$ecr['oldInstitutionTag']];
                $ecr['newInstitutionTagName'] = $tagList[$ecr['newInstitutionTag']];
                break;
            case 3:
                $tagList = DictApi::selectByParentCode('organization_tag');
                $ecr['oldOrganizationTagName'] = $tagList[$ecr['oldOrganizationTag']];
                $ecr['newOrganizationTagName'] = $tagList[$ecr['newOrganizationTag']];
                break;
            default:

                break;
        }
        $oldArea = array_filter([$ecr["oldProvinceName"], $ecr["oldCityName"], $ecr["oldCountyName"]]);
        $newArea = array_filter([$ecr["newProvinceName"], $ecr["newCityName"], $ecr["newCountyName"]]);
        $ecr["newFullLocationName"] = $newArea ? implode("", $newArea) : "";
        $ecr["oldFullLocationName"] = $newArea ? implode("", $newArea) : "";
        $template = "";
        switch ($ep->type) {
            case CommonConst::ENTERPRISE_WJ:
                $template = "/api/hospital/to_detail";
                $medicalCommunityMap = \app\common\api\Nhc::getMedicalCommunityMap();
                $ecr["newMedicalCommunityName"] = $medicalCommunityMap[$ecr["newMedicalCommunityId"]];
                $ecr["oldMedicalCommunityName"] = $medicalCommunityMap[$ecr["oldMedicalCommunityId"]];
                break;
            case CommonConst::ENTERPRISE_GJ:
                $template = "/api/school/to_detail";
                break;
        }
        return view($template, ['ecr' => $ecr]);
    }

    public function gotoChangeHeadPortraitPage() {
        $uid = $this->user["uid"];
        $userInfo = EnterpriseApi::getOne($uid);
        return view("enterprise_change_head", ["headPortrait" => $userInfo["headPortrait"]]);
    }

    public function changeHeadPortrait() {
        $response = new \stdClass();
        $response->code = 500;

        $uid = $this->user["uid"];
        $userInfo = EnterpriseApi::getOne($uid);

        if ($this->request->file()) {
            $headPortrait = $this->request->file("headPortrait");
            $upload = new \app\common\api\UploadApi();
            $result = $upload->uploadOne($headPortrait, "image", "person/photo");
            if ($result->code != 200) {
                $response->msg = $result->msg;
                return \StrUtil::back($response, "ech.callback");
            }
            if ($userInfo["headPortrait"]) {
//如果新照片符合像素要求，则删除旧照片
                $old_head_url = "storage/" . $userInfo ["headPortrait"];
                if (file_exists($old_head_url))
                    @unlink($old_head_url);
            }
            $data["id"] = $uid;
            $data["headPortrait"] = $result->filepath;
            $data["updateUser"] = $uid;
            $data["updateTime"] = date("Y-m-d H:i:s");
            EnterpriseApi::updateById($data);

            $user = new \app\common\api\UserApi($userInfo["username"], "", 2);
            $user->setSession();

            $response->code = 200;
            $response->msg = "修改成功!";
            $response->url = getStoragePath($result->filepath);
            return \StrUtil::back($response, "ech.callback");
        } else {
            $response->msg = "没有上传新头像";
            return \StrUtil::back($response, "ech.callback");
        }
    }

    //注销账号
    public function closeAccount() {
        $user = $this->user;
        $table = "un_enterpriseclose_record";
        $response = new \stdClass();
        $response->code = 500;
        $where = [];
        $where[] = ["enterpriseId", "=", $user["uid"]];
        $record = Db::table($table)->where($where)->order("createTime desc")->find();
        if ($record) {
            $record["files"] = json_decode($record["files"], true);
        }
        $ep = EnterpriseApi::getOne($user["uid"]);
        if ($record["checkState"] == 3 || !$ep) {
            $response->msg = "该账号不存在";
            return \StrUtil::back($response, "EnterpriseCenter.callback");
        }
        if ($record["checkState"] == 1 || $record["checkState"] == 9) {
            $response->msg = "您的注销申请正在审核中，请耐心等候！";
            return \StrUtil::back($response, "EnterpriseCenter.callback");
        }
        $reason = \StrUtil::getRequestDecodeParam($this->request, "reason");
        if (!$reason) {
            $response->msg = "注销原因不能为空";
            return \StrUtil::back($response, "EnterpriseCenter.callback");
        }

        $upload = new \app\common\api\UploadApi();
        $files = $this->request->file("closeAccountFiles");

        $tmp = [];
        foreach ($files as $file) {
            $result = $upload->uploadOne($file, "image", "enterprise/close_account_files");
            if ($result->code != 200) {
                $response->msg = $result->msg;
                return \StrUtil::back($response, "EnterpriseCenter.callback");
            }
            $tmp[] = $result->filepath;
        }
        if (!$tmp && !$record["files"]) {
            $response->msg = "请上传附件";
            return \StrUtil::back($response, "EnterpriseCenter.callback");
        }
        Db::startTrans();
        try {
            if (\StrUtil::isEmpOrNull($record["firstSubmitTime"])) {
                $data["firstSubmitTime"] = date("Y-m-d H:i:s");
            }
            $data["newSubmitTime"] = date("Y-m-d H:i:s");
            $data["reason"] = $reason;
            $data["files"] = $tmp ? json_encode($tmp) : $record["files"];
            $data["checkState"] = $record["checkState"] == 2 ? 9 : 1;
            if ($record["id"]) {
                $data["id"] = $record["id"];
                $data["updateTime"] = date("Y-m-d H:i:s");
                $data["updateUser"] = $user["uid"];
                $res = Db::table($table)->save($data);
            } else {
                $data["id"] = getStringId();
                $data["name"] = $ep["name"];
                $data["username"] = $ep["username"];
                $data["idCard"] = $ep["idCard"];
                $data["type"] = $ep["type"];
                $data["enterpriseId"] = $user["uid"];
                $data["createTime"] = date("Y-m-d H:i:s");
                $data["createUser"] = $user["uid"];
                $res = Db::table($table)->insert($data);
            }
            $newLog = [
                'id' => getStringId(),
                'mainId' => $data["id"],
                'category' => 'enterprise_change',
                'type' => 10,
                'typeFileId' => null,
                'active' => 1,
                'state' => 1,
                'step' => 100,
                'stateChange' => $record["checkState"] == 2 ? "<span class='label label-danger'>审核驳回</span>-><span class='label label-success'>待审核</span>" : "<span class='label label-success'>待审核</span>",
                'description' => $record["checkState"] == 2 ? '用户重新提交账户注销申请' : '用户提交账户注销申请',
                'createTime' => date("Y-m-d H:i:s"),
                'createUser' => $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统"
            ];

            $res = Db::table("new_talent_checklog")->insert($newLog);
            $response->msg = "注销申请提交成功，请耐心等待审核";
            $response->checkState = $data["checkState"];
            $response->code = 200;
            Db::commit();
            return \StrUtil::back($response, "EnterpriseCenter.callback");
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = $e->getMessage();
            return \StrUtil::back($response, "EnterpriseCenter.callback");
        }
    }

}
