<?php

namespace app\admin\controller;

use app\admin\common\AdminController;
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;

class EnterpriseChangeRecord extends AdminController {


    public function gotoEnterpriseChangeRecordPage(){
        $talentTypeList = DictApi::findChildDictByCode("enterprise_tag");
        $industryFieldNewList = DictApi::findChildDictByCode("industry_field");
        $streetList = DictApi::findChildDictByCode("street");

        return view("",['enterprise_tag' => $talentTypeList,'industryFieldNew' => $industryFieldNewList,'street' => $streetList]);
    }

    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']];
            }
        }

        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;
            default:
                $ecr['checkStateName'] = '';
                break;
        }


        switch ($ep->special){
            case 0:
                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'];
                }

                return view("",['ecr' => $ecr]);
                break;
            case 1:
                return view("goto_enterprise_change_detail_page1", ['ecr' => $ecr]);
                break;
            default:

                break;
        }


    }

    public function gotoEnterpriseChangeExaminePage(){
        $id = trim($this->request['id']);
        if(!$id){
            return json(["msg" => 'ID不能为空!']);
        }
        $ecr = EnterpriseApi::getOneRecord($id);

        return view("",['ecr' => $ecr]);
    }

    public function doExamine(){
        $id = trim($this->request['id']);
        if(!$id){
            return json(["msg" => 'ID不能为空!','code' => 500]);
        }
        $ecr = EnterpriseApi::getOneRecord($id);
        if(!$ecr){
            return json(["msg" => '原始数据不存在!','code' => 500]);
        }
        $checkState = trim($this->request['checkState']);
        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 (\StrUtil::isNotEmpAndNull($checkMsg) && strlen($checkMsg)>200) {
            return json(["msg" => '审核意见最多200个字符!','code' => 500]);
        }
        if ($ecr['checkState']!=2 && $ecr['checkState']!=3 && $ecr['checkState']!=5) {
            return json(["msg" => '不在审核范围内!','code' => 500]);
        }
        //如果为审核驳回，更新表中的审核状态 和 审核意见， 直接返回结果
        if ($checkState == 3) {
            $ecr->checkState = 3;
            $ecr->checkMsg = $checkMsg;
            $ecr->updateUser = session('user')['uid'];
            $ecr->updateTime = date("Y-m-d H:i:s");
            $ecr->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);

            $company = CompanyApi::getOne(session('user')['companyId']);

            TalentChecklog::create([
                'id' => getStringId(),
                'category' => 'enterprise_change',
                'mainId' => $ecr['id'],
                'type' => 10,
                'typeField' => null,
                'active' => 1,
                'state' => 3,
                'step' => 101,
                'stateChange' => "<span class='label label-info'>审核驳回</span>",
                'description' => $checkMsg,
                'createTime' => date("Y-m-d H:i:s",time()),
                'createUser' => session('user')['name']."({$company['name']})"
            ]);
            return json(["msg" => '操作成功!',"code" => 200]);
		}else{
            $ecr->checkState = 4;
            $ecr->checkMsg = $checkMsg;
            $ecr->updateUser = session('user')['uid'];
            $ecr->updateTime = date("Y-m-d H:i:s");
            $ecr->save();

            $ep = EnterpriseApi::getOne($ecr['mainId']);
            $ep->name = $ecr['newName'];
            $ep->idCard = $ecr['newIdCard'];
            $ep->enterpriseTag = $ecr['newEnterpriseTag'];
            $ep->street = $ecr['newStreet'];
            $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");
            //查询此次上传的文件
            $list = TalentCommonFile::where('mainId',$ecr['id'])->select()->toArray();
            if(count($list) > 0){
                foreach ($list as $k => $v){
                    $fileInfo = CurrentcyFileType::where('id',$v['typeId'])->select()->toArray();
                    if(count($fileInfo) > 0){
                        foreach ($fileInfo as $item) {
                            switch ($item['api']){
                                case 'businessLicense':
                                    $ep->imgurl = $v['url'];
                                    break;
                                case 'businessBank':
                                    $ep->bankImg = $v['url'];
                                    break;
                                case 'businessDomain':
                                    $ep->domainImg = $v['url'];
                                    break;
                                case 'businessBeian':
                                    $ep->beian = $v['url'];
                                    break;
                            }
                        }
                    }
                }
            }
            //同步人才库与津贴库  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);

            $company = CompanyApi::getOne(session('user')['companyId']);

            TalentChecklog::create([
                'id' => getStringId(),
                'category' => 'enterprise_change',
                'mainId' => $ecr['id'],
                'type' => 10,
                'typeField' => null,
                'active' => 1,
                'state' => 4,
                'step' => 101,
                'stateChange' => "<span class='label label-info'>审核通过</span>",
                'description' => $checkMsg,
                'createTime' => date("Y-m-d H:i:s",time()),
                'createUser' => session('user')['name']."({$company['name']})"
            ]);

            return json(["msg" => '操作成功!',"code" => 200]);
        }

    }
}