<?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;

class Api extends EnterpriseController {

    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');
            foreach ($list as $k => &$v){
                $v['newIndustryFieldNewName'] = $industryFieldNew[$v['newIndustryFieldNew']];
                $v['newEnterpriseType'] = $typeList[$v['newEnterpriseType']];
                $v['newStreetName'] = $streetList[$v['newStreet']];
            }
        }

        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 = [
            'enterprise_id' => $ep['id'],
            'newName' => $ep['name'],
            'newIdCard' => $ep['idCard'],
            'newStreet' => $ep['street'],
            'newAddress' => $ep['address'],
            'newLegal' => $ep['legal'],
            'newEphone' => $ep['ephone'],
            'newAgentName' => $ep['agentName'],
            'newAgentEmail' => $ep['agentEmail'],
            'newAgentPhone' => $ep['agentPhone'],
            'type' => $ep['type'],
            'newEnterpriseTag' => $ep['enterpriseTag'],
            'newEnterpriseType' => $ep['enterpriseType'],
            'newIndustryFieldNew' => $ep['industryFieldNew'],
            'newIndustryFieldOld' => $ep['industryFieldOld'],
            'newBankCard' => $ep['bankCard'],
            'newBank' => $ep['bank'],
            'newBankNetwork' => $ep['bankNetwork']
        ];

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

        //20220918增加根据不同的企业类型显示不同的信息变更界面
        switch ($ep->special){
            case 0:
                return view("", ['ecr' => $ecr]);
                break;
            case 1:
                return view("to_add1", ['ecr' => $ecr]);
                break;
            default:

                break;
        }


    }

    public function upsert(){
        $data = [
            'id' => \StrUtil::getRequestDecodeParam($this->request,'enterprise_id'),
            'name' => \StrUtil::getRequestDecodeParam($this->request,'newName'),//单位名称
            'idCard' => \StrUtil::getRequestDecodeParam($this->request,'newIdCard'),//统一社会信用代码
            'agentName' => \StrUtil::getRequestDecodeParam($this->request,'newAgentName'),//人才联络员
            'agentPhone' => \StrUtil::getRequestDecodeParam($this->request,'newAgentPhone'),//人才联络员电话
            'legal' => \StrUtil::getRequestDecodeParam($this->request,'newLegal'),//法人
            'street' => \StrUtil::getRequestDecodeParam($this->request,'newStreet'),//镇街
            'address' => \StrUtil::getRequestDecodeParam($this->request,'newAddress'),//地址
            'type' => intval($this->request['type']),
            'enterpriseTag' => \StrUtil::getRequestDecodeParam($this->request,'newEnterpriseTag'),//单位标签
            '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')//网点
        ];

        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();
            switch ($ep->special){
                case 0:
                    validate(\app\common\validate\Enterprise::class)->batch(true)->scene('change')->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_data = [
                    'id' => getStringId(),
                    'mainId' => $data['id'],
                    'type' => $data['type'],
                    'oldName' => $ep['name'],
                    'oldIdCard' => $ep['idCard'],
                    'oldIndustryFieldNew' => $ep['industryFieldNew'],
                    'oldIndustryFieldOld' => $ep['industryFieldOld'],
                    'oldStreet' => $ep['street'],
                    'oldAddress' => $ep['address'],
                    'oldLegal' => $ep['legal'],
                    'oldEphone' => $ep['ephone'],
                    'oldAgentName' => $ep['agentName'],
                    'oldAgentEmail' => $ep['agentEmail'],
                    'oldAgentPhone' => $ep['agentPhone'],
                    'oldEnterpriseTag' => $ep['enterpriseTag'],
                    'oldEnterpriseType' => $ep['enterpriseType'],
                    'oldBankCard' => $ep['bankCard'],
                    'oldBank' => $ep['bank'],
                    'oldBankNetwork' => $ep['bankNetwork'],
                    'newName' => htmlspecialchars($data['name']),
                    'newIdCard' => htmlspecialchars($data['idCard']),
                    'newIndustryFieldNew' => $data['industryFieldNew'],
                    'newIndustryFieldOld' => $data['industryFieldOld'],
                    'newStreet' => $data['street'],
                    'newAddress' => $data['address'],
                    'newLegal' => $data['legal'],
                    'newEphone' =>  $data['ephone'],
                    'newAgentName' => $data['agentName'],
                    'newAgentEmail' => $data['agentEmail'],
                    'newAgentPhone' => $data['agentPhone'],
                    'newEnterpriseTag' => $data['enterpriseTag'],
                    '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"]
                ];
                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' => '用户'
                ];
                $res = ['msg' => '添加成功', 'code' => 200, 'obj' => $record_data];
            } else {
                $record = EnterpriseRecord::find($record_id);
                $ep = Enterprise::where('id',session("user")["uid"])->find();
                $record->oldName = $ep['name'];
                $record->oldIdCard = $ep['idCard'];
                $record->oldIndustryFieldNew = $ep['industryFieldNew'];
                $record->oldIndustryFieldOld = $ep['industryFieldOld'];
                $record->oldStreet = $ep['street'];
                $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->oldEnterpriseType = $ep['enterpriseType'];
                $record->oldBankCard = $ep['bankCard'];
                $record->oldBank = $ep['bank'];
                $record->oldBankNetwork = $ep['bankNetwork'];
                $record->newName = htmlspecialchars($data['name']);
                $record->newIdCard = htmlspecialchars($data['idCard']);
                $record->newIndustryFieldNew = $data['industryFieldNew'];
                $record->newIndustryFieldOld = $data['industryFieldOld'];
                $record->newStreet = $data['street'];
                $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->newEnterpriseType = $data['enterpriseType'];
                $record->newBankCard = $data['bankCard'];
                $record->newBank = $data['bank'];
                $record->newBankNetwork = $data['bankNetwork'];
                $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' => '用户'
                ];

                $res = ['msg' => '修改成功', 'code' => 200, 'obj' => $record];
            }

            TalentChecklog::create($log);

            return json($res);
        } catch (ValidateException $e){
            $error = $e->getError();
            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();

        switch ($ep->special){
            case 0:
                return view("", ['ecr' => $ecr]);
                break;
            case 1:
                return view("to_update1", ['ecr' => $ecr]);
                break;
            default:

                break;
        }
    }

    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($obj['checkState'] != 1 && $obj['checkState'] != 3){
            return json(['msg' => '不能重复提交审核', 'code' => 500]);
        }

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

        //20220918增加根据不同的企业类型显示不同的信息变更界面
        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'] = 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['oldStreetName'] = $streetList[$ecr['oldStreet']];
        $ecr['newStreetName'] = $streetList[$ecr['newStreet']];
        //20220918增加根据不同的企业类型显示不同的信息变更界面
        switch ($ep->special){
            case 0:
                $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']];



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

                break;
        }

    }
}