<?php

namespace app\admin\controller;

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

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

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

    public function gotoEnterpriseChangeRecordPage() {

        $template = "";
        $assigns = [];
        switch ($this->user["type"]) {
            case CommonConst::ENTERPRISE_WJ:
                $template = "/enterprise_change_record/hospital/goto_enterprise_change_record_page";
                $where[] = ["status", "<>", 3];
                $assigns["medicalCommunities"] = \app\common\api\Nhc::getMedicalCommunityList();
                break;
            case CommonConst::ENTERPRISE_GJ:
                $template = "/enterprise_change_record/school/goto_enterprise_change_record_page";
                break;
            default:
                $talentTypeList = DictApi::findChildDictByCode("enterprise_tag");
                $industryFieldNewList = DictApi::findChildDictByCode("industry_field");
                $streetList = DictApi::findChildDictByCode("street");
                $assigns = ['enterprise_tag' => $talentTypeList, 'industryFieldNew' => $industryFieldNewList, 'street' => $streetList];
                break;
        }

        return view($template, $assigns);
    }

    public function findEnterpriseChangeRecordByPage() {
        $res = EnterpriseApi::getRecordList($this->request);

        return json($res);
    }

    public function gotoEnterpriseChangeDetailPage() {
        $id = trim($this->request['id']);
        if (!$id) {
            return json(["msg" => 'ID不能为空!']);
        }
        $ecr = EnterpriseApi::getOneRecord($id);
        $ep = EnterpriseApi::getOne($ecr['mainId']);
        if (\StrUtil::isNotEmpAndNull($ecr['oldStreet']) || \StrUtil::isNotEmpAndNull($ecr['newStreet'])) {
            $streetList = DictApi::selectByParentCode("street");
            if (\StrUtil::isNotEmpAndNull($ecr['oldStreet'])) {
                $ecr['oldStreetName'] = $streetList[$ecr['oldStreet']];
            }
            if (\StrUtil::isNotEmpAndNull($ecr['newStreet'])) {
                $ecr['newStreetName'] = $streetList[$ecr['newStreet']];
            }
        }
        $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:
                    $ecr['rs'] = $rsapi->I040102($ecr['newIdCard']);
                    break;
                case 1:
                    $ecr['rs'] = $rsapi->I080101($ep['newIdCard']);
                    break;
                case 2:
                    $ecr['rs'] = $rsapi->I030501($ep['newName'], $ep['newIdCard']);
                    break;
            }
            $api_model_data = [
                'uid' => $ecr['newIdCard'],
                'action' => 'change_record_check',
                'content' => serialize($ecr['rs']),
                'createTime' => time()
            ];
            ApiData::create($api_model_data);
        } else {
            $ecr['rs'] = unserialize($check_info['content']);
        }

        switch ($ecr['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;
            case 6:
                $ecr['checkStateName'] = '初审驳回';
                break;
            case 7:
                $ecr['checkStateName'] = '初审通过';
                break;
            default:
                $ecr['checkStateName'] = '';
                break;
        }

        /* $where = [];
          $where[] = ['tcf.mainId', '=', $id];
          $files = TalentCommonFile::alias("tcf")->field("tcf.*,cft.api")->leftJoin("new_currency_filetype cft", "cft.id=tcf.typeId")->where($where)->select();
          $_files = [];
          foreach ($files as $k => $v) {
          $extension = pathinfo($v["url"])["extension"];
          if (in_array($extension, ["jpeg", "jpg", "png", "gif"])) {
          $v["is_img"] = 1;
          } else {
          $v["is_img"] = 0;
          }
          $v['url'] = getStoragePath($v['url']);
          $_files[$v["api"]][] = $v;
          } */
        $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;
            }
        }
        $ecr["special"] = $ep->special;
        switch ($ep->special) {
            case 0:
                if (\StrUtil::isNotEmpAndNull($ecr['oldAgencyType']) || \StrUtil::isNotEmpAndNull($ecr['newAgencyType'])) {
                    $agencyTypeList = DictApi::selectByParentCode("agency_type");
                    if (\StrUtil::isNotEmpAndNull($ecr['oldAgencyType'])) {
                        $ecr['oldAgencyTypeName'] = $agencyTypeList[$ecr['oldAgencyType']];
                    }
                    if (\StrUtil::isNotEmpAndNull($ecr['newAgencyType'])) {
                        $ecr['newAgencyTypeName'] = $agencyTypeList[$ecr['newAgencyType']];
                    }
                }
                if (\StrUtil::isNotEmpAndNull($ecr['oldEnterpriseTag']) || \StrUtil::isNotEmpAndNull($ecr['newEnterpriseTag'])) {
                    $talentTypeList = DictApi::selectByParentCode("enterprise_tag");
                    if (\StrUtil::isNotEmpAndNull($ecr['oldEnterpriseTag'])) {
                        $ecr['oldEnterpriseTagName'] = $talentTypeList[$ecr['oldEnterpriseTag']];
                    }
                    if (\StrUtil::isNotEmpAndNull($ecr['newEnterpriseTag'])) {
                        $ecr['newEnterpriseTagName'] = $talentTypeList[$ecr['newEnterpriseTag']];
                    }
                }
                if (\StrUtil::isNotEmpAndNull($ecr['oldIndustryFieldNew']) || \StrUtil::isNotEmpAndNull($ecr['newIndustryFieldNew'])) {
                    $industryFieldNewList = DictApi::selectByParentCode("industry_field");
                    if (\StrUtil::isNotEmpAndNull($ecr['oldIndustryFieldNew'])) {
                        $ecr['oldIndustryFieldNewName'] = $industryFieldNewList[$ecr['oldIndustryFieldNew']];
                    }
                    if (\StrUtil::isNotEmpAndNull($ecr['newIndustryFieldNew'])) {
                        $ecr['newIndustryFieldNewName'] = $industryFieldNewList[$ecr['newIndustryFieldNew']];
                    }
                }
                if (\StrUtil::isNotEmpAndNull($ecr['oldIndustryFieldOld'])) {
                    $industry = DictApi::findDictByCode($ecr['oldIndustryFieldOld']);
                    $ecr['oldIndustryFieldOldName'] = $industry['name'];
                }
                if (\StrUtil::isNotEmpAndNull($ecr['newIndustryFieldOld'])) {
                    $industry = DictApi::findDictByCode($ecr['newIndustryFieldOld']);
                    $ecr['newIndustryFieldOldName'] = $industry['name'];
                }
                if (\StrUtil::isNotEmpAndNull($ecr['oldEnterpriseType'])) {
                    $industry = DictApi::findDictByCode($ecr['oldEnterpriseType']);
                    $ecr['oldEnterpriseTypeName'] = $industry['name'];
                }
                if (\StrUtil::isNotEmpAndNull($ecr['newEnterpriseType'])) {
                    $industry = DictApi::findDictByCode($ecr['newEnterpriseType']);
                    $ecr['newEnterpriseTypeName'] = $industry['name'];
                }
                break;
            case 1:
                if (\StrUtil::isNotEmpAndNull($ecr['oldInstitutionTag']) || \StrUtil::isNotEmpAndNull($ecr['newInstitutionTag'])) {
                    $tagList = DictApi::selectByParentCode("institution_tag");
                    if (\StrUtil::isNotEmpAndNull($ecr['oldInstitutionTag'])) {
                        $ecr['oldInstitutionTagName'] = $tagList[$ecr['oldInstitutionTag']];
                    }
                    if (\StrUtil::isNotEmpAndNull($ecr['newInstitutionTag'])) {
                        $ecr['newInstitutionTagName'] = $tagList[$ecr['newInstitutionTag']];
                    }
                }
                break;
            case 3:
                if (\StrUtil::isNotEmpAndNull($ecr['oldOrganizationTag']) || \StrUtil::isNotEmpAndNull($ecr['newOrganizationTag'])) {
                    $tagList = DictApi::selectByParentCode("organization_tag");
                    if (\StrUtil::isNotEmpAndNull($ecr['oldOrganizationTag'])) {
                        $ecr['oldOrganizationTagName'] = $tagList[$ecr['oldOrganizationTag']];
                    }
                    if (\StrUtil::isNotEmpAndNull($ecr['newOrganizationTag'])) {
                        $ecr['newOrganizationTagName'] = $tagList[$ecr['newOrganizationTag']];
                    }
                }
                break;
            default:

                break;
        }

        $template = "";
        switch ($this->user["type"]) {
            case CommonConst::ENTERPRISE_WJ:
                $medicalCommunityList = \app\common\api\Nhc::getMedicalCommunityMap();
                $template = "/enterprise_change_record/hospital/goto_enterprise_change_detail_page";
                $ecr["newMedicalCommunityName"] = $medicalCommunityList[$ecr["newMedicalCommunityId"]];
                $ecr["oldMedicalCommunityName"] = $medicalCommunityList[$ecr["oldMedicalCommunityId"]];
                break;
            case CommonConst::ENTERPRISE_GJ:
                $template = "/enterprise_change_record/school/goto_enterprise_change_detail_page";
                break;
        }
        return view($template, ['ecr' => $ecr]);
    }

    public function gotoEnterpriseChangeExaminePage() {
        $id = trim($this->request['id']);
        if (!$id) {
            return json(["msg" => 'ID不能为空!']);
        }
        $ecr = EnterpriseApi::getOneRecord($id);
        $ep = EnterpriseApi::getOne($ecr['mainId']);
        $lastLog = \app\common\api\TalentLogApi::getLastLog($id, 10);

        if ($lastLog["active"] == 0 && $lastLog["category"] == "enterprise_change") {
            $ecr["checkState"] = $lastLog["state"];
            $ecr["checkMsg"] = $lastLog["description"];
        }

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

        $modify_fields = [];
        foreach ($fields as $key => $value) {
            $oldFieldName = "old" . $key;
            $newFieldName = "new" . $key;
            //if ($ecr[$oldFieldName] != $ecr[$newFieldName]) {
            $modify_fields[$newFieldName] = ["field" => $newFieldName, "name" => $value, "checked" => false];
            //}
        }
        if ($ecr["modify_fields"]) {
            $_modify_fields = explode(",", $ecr["modify_fields"]);
            foreach ($_modify_fields as $_field) {
                if ($modify_fields[$_field]) {
                    $modify_fields[$_field]["checked"] = true;
                } else {
                    $modify_fields[$_field] = ["field" => $_field, "name" => $fields[substr($_field, 3)], "checked" => true];
                }
            }
        }
        /* $currencyType = $ep["special"] == 0 ? "enterpriseChange" : "governmentChange";
          $where = [];
          $where[] = ["type", "=", $currencyType];
          $where[] = ["active", "=", 1];

          $fileTypes = \app\admin\model\CurrencyFiletype::where($where)->order("sn asc")->column("name", "id");

          $where = [];
          $where[] = ['mainId', '=', $id];
          $uploadTypeIds = TalentCommonFile::distinct(true)->field("typeId")->where($where)->column("typeId"); */
        $oldtypes = ["1161965644164075522" => "newImgurl", "1518753449987148467" => "newImgurl", "1518328155588131269" => "newBankImg", "1518926324960220206" => "newBankImg",
            "1518941016720463523" => "newDomainImg", "1519109971871948101" => "newBeian", "1519185486755815382" => "newBeian"];
        $modify_files = [];
        foreach ($files as $key => $value) {
            $modify_files[$key] = ["field" => $key, "name" => $value, "checked" => false];
        }
        if ($ecr["modify_files"]) {
            $_modify_files = explode(",", $ecr["modify_files"]);
            foreach ($_modify_files as $_file) {
                if ($modify_files[$_file]) {
                    $modify_files[$_file]["checked"] = true;
                } else {
                    if (strtotime($ecr["createTime"]) < strtotime($this->compatible_time)) {
                        //兼容旧的typeid
                        $_file = $oldtypes[$_file];
                    }
                    $modify_files[$_file] = ["field" => $_file, "name" => $files[$_file], "checked" => true];
                }
            }
        }

        return view("", ['ecr' => $ecr, '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不能为空!', 'code' => 500]);
        }
        $ecr = EnterpriseApi::getOneRecord($id);
        if (!$ecr) {
            return json(["msg" => '原始数据不存在!', 'code' => 500]);
        }

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

        $checkState = trim($this->request['checkState']);
        $files = $this->request["files"];
        $fields = $this->request["fields"];
        if ($checkState == null || ($checkState != 4 && $checkState != 3)) {
            return json(["msg" => '请选择审核状态!', 'code' => 500]);
        }
        $checkMsg = trim($this->request['checkMsg']);
        //如果审核状态为 审核驳回， 需要填写审核意见
        if ($checkState == 3 && \StrUtil::isEmpOrNull($checkMsg)) {
            return json(["msg" => '审核驳回时，需要填写审核意见!', 'code' => 500]);
        }
        if ($checkState == 3 && !$files && !$fields) {
            return json(["msg" => '审核驳回时，需要选择可修改的字段或者附件!', 'code' => 500]);
        }
        if (\StrUtil::isNotEmpAndNull($checkMsg) && strlen($checkMsg) > 1000) {
            return json(["msg" => '审核意见最多1000个字符!', 'code' => 500]);
        }
        if ($ecr['checkState'] != 2 && $ecr['checkState'] != 5 && $ecr['checkState'] != 7) {
            return json(["msg" => '不在审核范围内!', 'code' => 500]);
        }
        $lastLog = \app\common\api\TalentLogApi::getLastLog($id, 10);
        $companyName = session('user')["companyName"] ?: session('user')["rolename"];
        if ($checkState == 4) {
            $fields = null;
            $files = null;
        }
        if ($oriCheckState == 7 || $ecr["type"] == 2) {
            $stateChangeStr = $checkState == 4 ? "<span class='label label-info'>审核通过</span>" : "<span class='label label-danger'>审核驳回</span>";
            $newCheckState = $checkState;
        } else {
            $stateChangeStr = $checkState == 4 ? "<span class='label label-info'>初审通过</span>" : "<span class='label label-danger'>初审驳回</span>";
            $newCheckState = $checkState == 4 ? 7 : 6;
        }
        if ($doSubmit) {
            //如果为审核驳回，更新表中的审核状态 和 审核意见， 直接返回结果
            if ($checkState == 3) {
                $ecr->checkState = $newCheckState;
                $ecr->checkMsg = $checkMsg;
                $ecr->updateUser = session('user')['uid'];
                $ecr->updateTime = date("Y-m-d H:i:s");
                $ecr->modify_fields = $fields ? implode(",", $fields) : null;
                $ecr->modify_files = $files ? implode(",", $files) : null;
                $ecr->save();
                //发送短信
                $record_data = [
                    'id' => getStringId(),
                    'bizId' => getStringId(),
                    'userId' => $ecr['mainId'],
                    'type' => 2,
                    'smsType' => 2,
                    'name' => $ecr['newName'],
                    'phone' => $ecr['newAgentPhone'],
                    'templateCode' => "【晋江市人才服务平台】您好！您提交申请的晋江市现代产业体系人才机构用户/机构信息变更因信息填写错误或材料不完整已被退回，请及时登录“晋江市人才综合服务申报平台”根据审核意见修改并重新提交。。",
                    'params' => '机构信息变更',
                    'state' => 1,
                    'sendingDate' => date("Y-m-d H:i:s", time()),
                    'createTime' => date("Y-m-d H:i:s", time())
                ];

                $smsapi = new ChuanglanSmsApi();

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

                MessageRecord::create($record_data);

                if ($lastLog["active"] === 0 && $lastLog["category"] == "enterprise_change") {
                    TalentChecklog::update([
                        'id' => $lastLog["id"],
                        'active' => 1,
                        'state' => $newCheckState,
                        'stateChange' => $stateChangeStr,
                        'description' => $checkMsg,
                        'updateTime' => date("Y-m-d H:i:s", time()),
                        'updateUser' => session('user')['name'] . "({$companyName})"
                    ]);
                } else {
                    TalentChecklog::create([
                        'id' => getStringId(),
                        'category' => 'enterprise_change',
                        'mainId' => $ecr['id'],
                        'type' => 10,
                        'typeFileId' => null,
                        'active' => 1,
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => $stateChangeStr,
                        'description' => $checkMsg,
                        'createTime' => date("Y-m-d H:i:s", time()),
                        'createUser' => session('user')['name'] . "({$companyName})"
                    ]);
                }
                return json(["msg" => '操作成功!', "code" => 200]);
            } else {
                $ecr->checkState = $newCheckState;
                $ecr->checkMsg = $checkMsg;
                $ecr->updateUser = session('user')['uid'];
                $ecr->updateTime = date("Y-m-d H:i:s");
                $ecr->modify_fields = null;
                $ecr->modify_files = null;
                $ecr->save();
                if ($newCheckState == 4) {
                    $ep = EnterpriseApi::getOne($ecr['mainId']);
                    $ep->name = $ecr['newName'];
                    $ep->idCard = $ecr['newIdCard'];
                    $ep->medicalCommunityId = $ecr['newMedicalCommunityId'];
                    $ep->isGeneral = $ecr['newIsGeneral'];
                    $ep->agencyType = $ecr['newAgencyType'];
                    $ep->enterpriseTag = $ecr['newEnterpriseTag'];
                    $ep->organizationTag = $ecr['newOrganizationTag'];
                    $ep->institutionTag = $ecr['newInstitutionTag'];
                    $ep->street = $ecr['newStreet'];
                    $ep->province = $ecr['newProvince'];
                    $ep->city = $ecr['newCity'];
                    $ep->county = $ecr['newCounty'];
                    $ep->provinceName = $ecr['newProvinceName'];
                    $ep->cityName = $ecr['newCityName'];
                    $ep->countyName = $ecr['newCountyName'];
                    $ep->address = $ecr['newAddress'];
                    $ep->legal = $ecr['newLegal'];
                    $ep->ephone = $ecr['newEphone'];
                    $ep->agentName = $ecr['newAgentName'];
                    $ep->agentEmail = $ecr['newAgentEmail'];
                    $ep->agentPhone = $ecr['newAgentPhone'];
                    $ep->industryFieldNew = $ecr['newIndustryFieldNew'];
                    $ep->industryFieldOld = $ecr['newIndustryFieldOld'];
                    $ep->enterpriseType = $ecr['newEnterpriseType'];
                    $ep->bankCard = $ecr['newBankCard'];
                    $ep->bankNetwork = $ecr['newBankNetwork'];
                    $ep->bank = $ecr['newBank'];
                    $ep->updateUser = session('user')['uid'];
                    $ep->updateTime = date("Y-m-d H:i:s");
                    $ep->imgurl = $ecr['newImgurl'] ?: $ep->imgurl;
                    $ep->bankImg = $ecr['newBankImg'] ?: $ep->bankImg;
                    $ep->domainImg = $ecr['newDomainImg'] ?: $ep->domainImg;
                    $ep->typeImg = $ecr['newTypeImg'];
                    $ep->beian = $ecr['newBeian'] ?: $ep->beian;
                    //同步人才库与津贴库  TODO
                    $ep->save();
                    //发送短信
                    $record_data = [
                        'id' => getStringId(),
                        'bizId' => getStringId(),
                        'userId' => $ecr['mainId'],
                        'type' => 2,
                        'smsType' => 2,
                        'name' => $ecr['newName'],
                        'phone' => $ecr['newAgentPhone'],
                        'templateCode' => "【晋江市人才服务平台】您好！您提交申请的现代产业体系人才{$checkMsg}已审核通过，可登录申报系统做相关事宜申报。",
                        'params' => '机构信息变更',
                        'state' => 1,
                        'sendingDate' => date("Y-m-d H:i:s", time()),
                        'createTime' => date("Y-m-d H:i:s", time())
                    ];

                    $smsapi = new ChuanglanSmsApi();

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

                    MessageRecord::create($record_data);
                }
                if ($lastLog["active"] === 0 && $lastLog["category"] == "enterprise_change") {
                    TalentChecklog::update([
                        'id' => $lastLog["id"],
                        'active' => 1,
                        'state' => $newCheckState,
                        'stateChange' => $stateChangeStr,
                        'description' => $checkMsg,
                        'updateTime' => date("Y-m-d H:i:s", time()),
                        'updateUser' => session('user')['name'] . "({$companyName})"
                    ]);
                } else {
                    TalentChecklog::create([
                        'id' => getStringId(),
                        'category' => 'enterprise_change',
                        'mainId' => $ecr['id'],
                        'type' => 10,
                        'typeFileId' => null,
                        'active' => 1,
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => $stateChangeStr,
                        'description' => $checkMsg,
                        'createTime' => date("Y-m-d H:i:s", time()),
                        'createUser' => session('user')['name'] . "({$companyName})"
                    ]);
                }
                return json(["msg" => '操作成功!', "code" => 200]);
            }
        } else {
            $ecrUpdData["id"] = $ecr['id'];
            $ecrUpdData["updateUser"] = session('user')['uid'];
            $ecrUpdData["updateTime"] = date("Y-m-d H:i:s");
            $ecrUpdData["modify_fields"] = $fields ? implode(",", $fields) : null;
            $ecrUpdData["modify_files"] = $files ? implode(",", $files) : null;
            \app\enterprise\model\EnterpriseRecord::update($ecrUpdData);

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

    public function export() {
        $columns = ["账号类型",
            "原单位名称", "原社会信用代码", "原法人代表", "原所属街道", "原单位地址", "原单位电话", "原单位银行账号", "原单位开户银行", "原单位开户银行网点", "原机构（单位）标签", "原机构类型", "原产业领域", "原行业领域", "原企业标签", "原企业类型", "原经办人", "原经办人电话", "原经办人邮箱",
            "新单位名称", "新社会信用代码", "新法人代表", "新所属街道", "新单位地址", "新单位电话", "新单位银行账号", "新单位开户银行", "新单位开户银行网点", "新机构（单位）标签", "新机构类型", "新产业领域", "新行业领域", "新企业标签", "新企业类型", "新经办人", "新经办人电话", "新经办人邮箱",
            "申报时间", "审核状态", "备注"];

        $rows = EnterpriseApi::getExportList($this->request);
        $exportDatas = [];
        foreach ($rows as $row) {
            if ($row)
                $typeName = $exportDatas[] = [
                    $row["typeName"],
                    $row["oldName"], $row["oldIdCard"], $row["oldLegal"], $row["oldStreetName"], $row["oldAddress"], $row["oldEphone"], $row["oldBankCard"], $row["oldBank"], $row["oldBankNetwork"], $row["oldAgencyTagName"], $row["oldAgencyTypeName"], $row["oldIndustryFieldNewName"], $row["oldIndustryFieldOldName"], $row["oldEnterpriseTagName"], $row["oldEnterpriseTypeName"], $row["oldAgentName"], $row["oldAgentPhone"], $row["oldAgentEmail"],
                    $row["newName"], $row["newIdCard"], $row["newLegal"], $row["newStreetName"], $row["newAddress"], $row["newEphone"], $row["newBankCard"], $row["newBank"], $row["newBankNetwork"], $row["newAgencyTagName"], $row["newAgencyTypeName"], $row["newIndustryFieldNewName"], $row["newIndustryFieldOldName"], $row["newEnterpriseTagName"], $row["newEnterpriseTypeName"], $row["newAgentName"], $row["newAgentPhone"], $row["newAgentEmail"],
                    $row["createTime"], $row["checkStateName"], $row["checkMsg"]
                ];
        }
        if ($rows) {
            export($columns, $exportDatas, "机构信息变更列表");
            exit();
        }
        return json(["msg" => "没有可以导出的内容"]);
    }

    public function findFieldsAndFiles() {
        $id = trim($this->request['id']);
        $ecr = EnterpriseApi::getOneRecord($id);
        $ep = EnterpriseApi::getOne($ecr['mainId']);
        if (!$ecr || !$ep || !$id) {
            return json(["msg" => '没有对应的企业变更信息!']);
        }

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

        $modify_fields = [];
        foreach ($fields as $key => $value) {
            $oldFieldName = "old" . $key;
            $newFieldName = "new" . $key;
            //if ($ecr[$oldFieldName] != $ecr[$newFieldName]) {
            $modify_fields[$newFieldName] = ["field" => $newFieldName, "name" => $value, "checked" => false];
            //}
        }
        if ($ecr["modify_fields"]) {
            $_modify_fields = explode(",", $ecr["modify_fields"]);
            foreach ($_modify_fields as $_field) {
                if ($modify_fields[$_field]) {
                    $modify_fields[$_field]["checked"] = true;
                } else {
                    $modify_fields[$_field] = ["field" => $_field, "name" => $fields[substr($_field, 3)], "checked" => true];
                }
            }
        }
        $oldtypes = ["1161965644164075522" => "newImgurl", "1518753449987148467" => "newImgurl", "1518328155588131269" => "newBankImg", "1518926324960220206" => "newBankImg",
            "1518941016720463523" => "newDomainImg", "1519109971871948101" => "newBeian", "1519185486755815382" => "newBeian"];
        $modify_files = [];
        foreach ($files as $key => $value) {
            $modify_files[$key] = ["field" => $key, "name" => $value, "checked" => false];
        }
        if ($ecr["modify_files"]) {
            $_modify_files = explode(",", $ecr["modify_files"]);
            foreach ($_modify_files as $_file) {
                if ($modify_files[$_file]) {
                    $modify_files[$_file]["checked"] = true;
                } else {
                    if (strtotime($ecr["createTime"]) < strtotime($this->compatible_time)) {
                        //兼容旧的typeid
                        $_file = $oldtypes[$_file];
                    }
                    $modify_files[$_file] = ["field" => $_file, "name" => $files[$_file], "checked" => true];
                }
            }
        }
        return json(["code" => 200, "files" => $modify_files, "fields" => $modify_fields]);
    }

    public function updateFieldsAndFiles() {
        try {
            $params = $this->request->param();
            $id = $params["id"];
            $ecr = EnterpriseApi::getOneRecord($id);
            if (!$ecr) {
                throw new \think\Exception("没有对应的企业变更信息");
            }
            if (!in_array($ecr["checkState"], [3, 6])) {
                throw new \think\Exception("不是驳回状态，不能修改驳回字段！");
            }
            if ($ecr["checkState"] == 3 && !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 (\app\enterprise\model\EnterpriseRecord::update($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 = ["newImgurl" => "企业营业执照", "newBankImg" => "开户许可证/基本存款账户信息", "newBeian" => "人才联络员信息备案表"];
            } else if ($type == CommonConst::ENTERPRISE_WJ) {
                $fields = ["Name" => "医院名称", "IdCard" => "登记号", "Legal" => "法人代表", "MedicalCommunityId" => "医共体", "IsGeneral" => "是否总院", "Ephone" => "医院电话", "Province" => "地址省", "City" => "地址市", "County" => "地址县\区", "Address" => "医院地址",
                    "BankCard" => "银行账号", "Bank" => "开户银行", "BankNetwork" => "开户银行网点",
                    "AgentName" => "人才联络员姓名", "AgentPhone" => "人才联络员电话", "AgentEmail" => "人才联络员邮箱"];
                $files = ["newImgurl" => "医疗机构执业许可证", "newBankImg" => "开户许可证/基本存款账户信息", "newBeian" => "人才联络员信息备案表"];
            } else if ($type == CommonConst::ENTERPRISE_GJ) {
                $fields = ["Name" => "学校名称", "IdCard" => "统一社会信用代码", "Legal" => "法人代表", "Ephone" => "学校电话", "Province" => "地址省", "City" => "地址市", "County" => "地址县\区", "Address" => "学校地址",
                    "AgentName" => "人才联络员姓名", "AgentPhone" => "人才联络员电话", "AgentEmail" => "人才联络员邮箱"];
                $files = ["newImgurl" => "办学许可证、法人证书或登记证书", "newBeian" => "人才联络员信息备案表"];
            } else {
                $fields = ["Name" => "企业名称", "IdCard" => "统一社会信用代码", "Legal" => "法人代表", "Address" => "企业地址", "Street" => "所属街道", "Ephone" => "企业电话", "BankCard" => "企业银行账号", "Bank" => "企业开户银行", "BankNetwork" => "企业开户银行网点",
                    "AgencyType" => "机构类型", "IndustryFieldNew" => "产业领域", "IndustryFieldOld" => "行业领域", "EnterpriseTag" => "企业标签", "EnterpriseType" => "企业类型",
                    "AgentName" => "人才联络员姓名", "AgentPhone" => "人才联络员电话", "AgentEmail" => "人才联络员邮箱"];
                $files = ["newImgurl" => "企业营业执照", "newBankImg" => "开户许可证/基本存款账户信息", "newDomainImg" => "行业领域佐证材料", "newBeian" => "人才联络员信息备案表", "newTypeImg" => "规上、高新技术、专精特新企业上传材料"];
            }
        } 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 = ["newImgurl" => "法人证或批文", "newBankImg" => "开户许可证/基本存款账户信息", "newBeian" => "人才联络员备案表"];
        }
        return ["fields" => $fields, "files" => $files];
    }

}
