<?php

namespace app\admin\controller;

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

class Enterprise extends AdminController {

    public function gotoEnterprisePage(){



        return view("", []);
    }

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

        return json($res);
    }

    public function gotoEnterpriseDetailPage(){
        $id = trim($this->request['id']);
        $ep = EnterpriseApi::getOne($id);
        if(!$ep){
            return "无此企业";
        }
        //--------设置 审核状态---------------------------------------------------
        switch ($ep['checkState']){
            case 1:
                $ep['checkStateName'] = "待审核";
                break;
            case 2:
                $ep['checkStateName'] = "审核驳回";
                break;
            case 3:
                $ep['checkStateName'] = "审核通过";
                break;
            case 4:
                $ep['checkStateName'] = "重新提交";
                break;
        }
        //-------设置账号状态----------------------------------------------------
        switch ($ep['active']){
            case 1:
                $ep['activeName'] = "账号有效";
                break;
            case 2:
                $ep['activeName'] = "冻结/拉黑";
                break;
        }
        //---------设置 街道-----------------------------------------------------
        if (\StrUtil::isNotEmpAndNull($ep['street'])) {
            $street_info = DictApi::findByParentCodeAndCode('street',$ep['street']);
    		if ($street_info != null) {
                $ep['streetName'] = $street_info['name'];
            }
		}
        //---------设置产业领域 --------------------------------------------------
        if(\StrUtil::isNotEmpAndNull($ep['industryFieldNew'])){
            $industryFieldNew = DictApi::findByParentCodeAndCode('industry_field',$ep['industryFieldNew']);
			if($industryFieldNew != null){
                $ep['industryFieldNewName'] = $industryFieldNew['name'];
            }
		}
        //---------设置行业领域 --------------------------------------------------
        if(\StrUtil::isNotEmpAndNull($ep['industryFieldOld'])){
            $industryFieldOld = DictApi::findByParentCodeAndCode($ep['industryFieldNew'] . "_field",$ep['industryFieldOld']);
            if($industryFieldOld != null){
                $ep['industryFieldOldName'] = $industryFieldOld['name'];
            }
        }
        //---------设置单位标签 --------------------------------------------------
        if(\StrUtil::isNotEmpAndNull($ep['enterpriseTag'])){
            $enterpriseTag = DictApi::findByParentCodeAndCode("enterprise_tag",$ep['enterpriseTag']);
            if($enterpriseTag != null){
                $ep['enterpriseTagName'] = $enterpriseTag['name'];
            }
        }
        //---------设置单位类型 --------------------------------------------------
        if(\StrUtil::isNotEmpAndNull($ep['enterpriseType'])){
            $enterpriseType = DictApi::findByParentCodeAndCode("enterprise_type",$ep['enterpriseType']);
            if($enterpriseType != null){
                $ep['enterpriseTypeName'] = $enterpriseType['name'];
            }
        }


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

    public function gotoExaminePage(){

        $id = trim($this->request['id']);
        $ep = EnterpriseApi::getOne($id);
        if(!$ep){
            return "无此企业";
        }
        //---------设置产业领域 --------------------------------------------------
        if(\StrUtil::isNotEmpAndNull($ep['industryFieldNew'])){
            $industryFieldNew = DictApi::findByParentCodeAndCode('industry_field',$ep['industryFieldNew']);
            if($industryFieldNew != null){
                $ep['industryFieldNewName'] = $industryFieldNew['name'];
            }
        }




        return view("", ['ep' => $ep, 'checkUser' => session('user')['name']]);
    }

    public function doExamine(){
        $id = trim($this->request['id']);
        if(!$id){
            return json(["msg" => 'ID不能为空!']);
        }
        $ep = EnterpriseApi::getOne($id);
        if(!$ep){
            return json(["msg" => '无此企业!']);
        }
        $checkState = $this->request['checkState'];
        if($checkState == null || ($checkState != 2 && $checkState != 3)){
            return json(["msg" => '请选择审核状态!']);
        }
        $checkMsg = $this->request['checkMsg'];
        if($checkState == 2){
            if (\StrUtil::isEmpOrNull($checkMsg)) {
                return json(["msg" => '请填写审核意见!']);
            }

            if (strlen($checkMsg) > 200) {
                return json(["msg" => '审核意见最多200个字符!']);
            }
        }
        try {
            $checkData = [
                'id' => $id,
                'checkState' => $checkState,
                'checkMsg' => $checkMsg,
                'checkUser' => session('user')['name'],
                'updateUser' => session('user')['uid'],
                'updateTime' => date("Y-m-d H:i:s")
            ];
            $res = EnterpriseApi::updateById($checkData);

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

            if($checkState == 2){
                $record_data['templateCode'] = "【晋江市人才服务平台】您好！您提交申请的优秀人才机构注册信息因信息填写错误或上传不完整已被退回，请及时登录申报系统查看审核意见并重新提交。";
            }
            if($checkState == 3){
                $record_data['templateCode'] = "【晋江市人才服务平台】您好！您提交申请的优秀人才机构注册信息已审核通过，可登录申报系统做相关事宜申报。";
            }

            $smsapi = new ChuanglanSmsApi();

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

            MessageRecord::create($record_data);

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

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

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

        } catch (\Exception $e){
            return json(["msg" => $e->getMessage()]);
        }
    }

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

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

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

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

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

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

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

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

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

        $objPHPExcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        //创建人
        $objPHPExcel->getProperties()->setCreator("System");
        //最后修改人
        $objPHPExcel->getProperties()->setLastModifiedBy("System");
        //标题
        $objPHPExcel->getProperties()->settitle("企业用户信息".date("ymdHis"));

        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        //设置当前的sheet
        $sheet = $objPHPExcel->getActiveSheet();
        //设置sheet的name
        $sheet->settitle('企业用户信息');
        // 所有单元格默认高度
        $sheet->getDefaultRowDimension()->setRowHeight(30);
        $sheet->getDefaultColumnDimension()->setWidth(30);


        $sheet->getstyle('A1:O1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB("87CEEB");

        $header = ["单位名称", " 统一社会信用代码","产业领域" ,"单位标签"," 所属街道", "单位地址", " 法人代表", " 单位电话", "人才联络员", "人才联络员电话", "人才联络员邮箱", "审核状态", "账号状态", "注册时间","备注"];

        foreach ($header as $key => $value) {
            $sheet->setCellValueByColumnAndRow($key+1, 1, $value);
        }

        if($res['total'] > 0){
            $row = 2;
            foreach ($res['rows'] as $k => $v){
                for ($i = 0; $i < count($header);$i++){
                    switch ($i){
                        case 0:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['name']);
                            break;
                        case 1:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['idCard']);
                            break;
                        case 2:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['industryFieldNewName']);
                            break;
                        case 3:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['enterpriseTagName']);
                            break;
                        case 4:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['streetName']);
                            break;
                        case 5:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['address']);
                            break;
                        case 6:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['legal']);
                            break;
                        case 7:
                            $sheet->setCellValueExplicitByColumnAndRow($i+1, $row, $v['ephone'], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
                            break;
                        case 8:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['agentName']);
                            break;
                        case 9:
                            $sheet->setCellValueExplicitByColumnAndRow($i+1, $row, $v['agentPhone'], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
                            break;
                        case 10:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['agentEmail']);
                            break;
                        case 11:
                            switch ($v['checkState']){
                                case 1:
                                    $sheet->setCellValueByColumnAndRow($i+1, $row, "未审核");
                                    break;
                                case 2:
                                    $sheet->setCellValueByColumnAndRow($i+1, $row, "审核驳回");
                                    break;
                                case 3:
                                    $sheet->setCellValueByColumnAndRow($i+1, $row, "审核通过");
                                    break;
                                case 4:
                                    $sheet->setCellValueByColumnAndRow($i+1, $row, "重新提交");
                                    break;
                                default:
                                    $sheet->setCellValueByColumnAndRow($i+1, $row, "");
                                    break;
                            }
                            break;
                        case 12:
                            switch ($v['active']){
                                case 1:
                                    $sheet->setCellValueByColumnAndRow($i+1, $row, "账号有效");
                                    break;
                                case 2:
                                    $sheet->setCellValueByColumnAndRow($i+1, $row, "拉黑/冻结");
                                    break;
                                default:
                                    $sheet->setCellValueByColumnAndRow($i+1, $row, "");
                                    break;
                            }
                            break;
                        case 13:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['createTime']);
                            break;
                        case 14:
                            $sheet->setCellValueByColumnAndRow($i+1, $row, $v['description']);
                            break;
                    }

                }
                $row++;
            }
        }


        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'."企业用户信息".date("ymdHis").'.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $writer->save('php://output');

    }
}