<?php
namespace app\common\controller;
use think\facade\View;
use think\facade\Session;
use think\facade\Db;
use app\common\variable\MsgCode;
use app\common\validate\CompanyAttestation as CompanyAttestationValidate;
use think\exception\ValidateException;
use app\common\model\Company as CompanyModel;
use app\common\model\CompanyAttestation as CompanyAttestationModel;
/**
 * 
 */
class CompanyAttestation extends Base
{
	public static function saveCompanyAttestation($D)
	{
        /**
         * 公司基本信息
         */
        $CompanyModel=CompanyModel::where(['id'=>$D['company_id']])->find();
        /**
         * 公司认证记录
         */
        if ($CompanyModel) {
            switch ($CompanyModel->attestation) {
                case 1:
                    return parent::ajaxReturn('企业当前正在审核中',MsgCode::$error);
                case 3:
                    return parent::ajaxReturn('企业已通过认证',MsgCode::$error);
            }
        }else return parent::ajaxReturn('请先完善企业信息',MsgCode::$error);

        $CompanyAttestationModel=CompanyAttestationModel::where(['cid'=>$CompanyModel->id])->find();
        if ($CompanyAttestationModel) {
            $D['id']=$CompanyAttestationModel->id;
        }else{
            $CompanyAttestationModel=new CompanyAttestationModel;
        }
        /**
         * 公司认证信息验证
         */
        try {
            validate(CompanyAttestationValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(),MsgCode::$error);
        }
        $CompanyAttestationModel->cid                   =   $CompanyModel->id;
        $CompanyAttestationModel->uscc                  =   trimall($D['uscc']);
        $CompanyAttestationModel->business_license      =   $D['business_license'];
        $CompanyAttestationModel->status                =   0;
        $CompanyModel->attestation=1;
      
        // 启动事务
        Db::startTrans();
        try {
            $CompanyModel->save();
            $CompanyAttestationModel->save();
            // 提交事务
            Db::commit();
            return parent::ajaxReturn('提交成功，等待审核');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('提交失败，请重试',MsgCode::$error);
        }
	}
    public static function getAttestationInfo($company_id)
    {
        $Find=CompanyAttestationModel::alias('a')->where(['a.cid'=>$company_id])->join('company company','company.id=a.cid')->field('a.*,company.title as company_name,a.business_license as url')
            ->withAttr('url',function($v,$data){
                return $v?config('web.imgurl').$v:'';
            })->withAttr('uscc',function($v,$data){
                return $v && $data['status']!==2?substr_replace($v,'**********',4,10):$v;
            })->find();
        return $Find;
    }
}