<?php
namespace app\em\controller;

use app\admin\controller\Base;
use app\em\model\EmCert;
use app\em\model\EmInvoice;
use app\em\model\EmPayment;
use app\em\validate\AddCertValidate;
use think\Exception;
use think\facade\Request;

//缴费凭证
class Cert extends Base
{
    //显示表单
    public function create(){

        $payment_id = Request::param('payment_id');
        $this->assign('payment_id',$payment_id);

        //将缴费应缴金额传递给模板
        $balance = (new EmInvoice())->alias('ei')
                                    ->leftJoin(['em_payment_invoice'=>'epi'],'epi.invoice_id=ei.invoice_id')
                                    ->where('epi.payment_id','=',$payment_id)
                                    ->where('ei.payment_balance','>',0)
                                    ->sum('ei.payment_balance');
        $this->assign('balance',$balance?:0);

        $this->assign('types',EmPayment::getAllType());
        return $this->fetch();
    }

    //保存凭证
    public function store(){
        $data = Request::post();

        $validate = new AddCertValidate();
        $scene = 'type1';
        if($data['type'] == 3){
            $scene = 'type2';
        }

        if(!$validate->scene($scene)->check($data)){
            return json(['status'=>0,'message'=>$validate->getError()]);
        }

        //获取certId
        $data['cert_id'] = $this->createCertId();

        //保存凭证
        $certModel = new EmCert();
        if($certModel->save($data)){
            return json(['status'=>1,'message'=>'添加凭证成功']);
        } else {
            throw new Exception('添加凭证失败');
        }
    }

    //查看列表
    public function certs(){
        $payment_id = Request::param('payment_id');
        $list = EmCert::with('file')->where('payment_id','=',$payment_id)->order('cert_id asc')->select();
        foreach ($list as &$item){
            if(!empty($item->file->src)){
                $item->file->src = ltrim($item->file->src,'.');
            }
            $item->typeTitle = EmPayment::getTypeByTypeId($item->type);
        }
        $this->assign('data',$list);
        return $this->fetch('list');
    }

    //创建凭证id
    private function createCertId(){
        $inv = EmCert::field('id')->order('id desc,create_time desc')->find();
        if(!$inv) $id = 1;
        else $id = $inv->id + 1;
        return "CT".date('Ymd').zero($id);
    }
}