<?php

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

class CertSettle extends Base
{
    //显示表单
    public function create()
    {
        $settle_id = Request::param('settle_id');

        $balance = (new EmInvoice())->alias('ei')
            ->leftJoin(['em_settle_invoice'=>'epi'],'epi.invoice_id=ei.invoice_id')
            ->where('epi.settle_id','=',$settle_id)
            ->where('ei.settle_balance','>',0)
            ->sum('ei.settle_balance');
        $this->assign('balance',$balance?:0);
        $this->assign('settle_id', $settle_id);
        $this->assign('types', EmPayment::getAllType());
        return $this->fetch();
    }

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

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

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

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

        //保存凭证
        $certModel = new EmCertSettle();
        if ($certModel->save($data)) {
            //更新缴费单状态
            (new Settle())->updateStatus($data['settle_id']);
            return json(['status' => 1, 'message' => '添加凭证成功']);
        } else {
            throw new Exception('添加凭证失败');
        }
    }

    //查看列表
    public function certs()
    {
        $settle_id = Request::param('settle_id');
        $list = EmCertSettle::with('file')->where('settle_id', '=', $settle_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 = EmCertSettle::field('id')->order('id desc,create_time desc')->find();
        if (!$inv) $id = 1;
        else $id = $inv->id + 1;
        return "JSCT" . date('Ymd') . zero($id);
    }
}