<?php
/*
|--------------------------------------------------------------------------
| 发票管理
|--------------------------------------------------------------------------
|  增删改查
|  @author liXiaoLin
|  @Date: 2021/8/7
|  @Time: 19:04
|  @Email: lixiaolin@bluearp.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Financial;

use App\Http\Controllers\BaseController;
use App\Models\OrderRefuse;
use App\Models\Orders;
use App\Services\BmmcService;
use App\Services\CommonService;
use App\Services\InvoiceService;
use App\Services\OrderService;
use App\Services\PlatformService;
use Illuminate\Http\Request;
use App\Models\InvoiceTable;
use App\Models\Pt;
use DB;
use Validator;
use Excel;
use Illuminate\Validation\Rules\In;
use BlueCity\Core\Inc\ErrorInc;


/**
 * @name 发票管理
 * Class InvoiceTableController
 * @package App\Http\Controllers\Admin
 */
class InvoiceTableController extends BaseController
{
    /**
     * @api {post} /api/Financial/invoiceTable 列表
     * @apiGroup 发票管理
     * @apiName 列表
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台管理列表
     *
     * @apiParam {int} state 状态；1：全部；2：待开发票；3：已开发票；4：已发快递
     * @apiParam {int} status 筛选状态；1：不限；2：代开发票；3：已开发票；4：已发快递
     * @apiParam {string} invoice_order 发票号
     * @apiParam {int} order_num 订单号
     * @apiParam {string} invoice_header 发票台头
     * @apiParam {int} invoice_project 发票项目
     * @apiParam {string} start_time 开始时间
     * @apiParam {string} end_time 结束时间
     * @apiParam {int} page_size  页大小
     * @apiParam {int} page  页码
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
            "error_code": 0,
            "data": {
            "show_num": {
            "dkfp": 2,//待开发票
            "ykfp": "0",//已开发票
            "kdh": "0",//快递号
            "fph": "0"//发票号
            },
            "list": [
            {
            "id": 1,
            "invoice_header": "忘机",//发票台头
            "invoice_project": "蓄电池",//发票项目
            "invoice_value": "1433.00",//发票金额
            "invoice_order": "",//发票号
            "invoice_time": "",//开票时间
            "content": "",//开票备注
            "is_invoice": 1,//状态:1新发票10已开发票20已发快递30已取消'
            "order_num": "ZC201807250519271369",//平台编号
            "creator": "",//创建人
            "create_time": "2018-07-25 17:19:27",//创建时间
            "invoice_type": 2,//发票类型；1：增票；2：普票
            "invoice_kd": null,//快递单号
            "invoice_urgency": 1,//紧急状态；1：普通；10：加急
            "invoice_pid": null,//平台id
            "client_name": "忘机",//客户姓名
            "client_tel": "17606122918",//客户电话
            "client_addr": "北京 北京市 东城区 南海诸岛",//客户地址
            "tax_num": null,//税号
            "company_addr": null,//公司地址
            "company_tel": null,//公司电话
            "bank": null,//开户行
            "bank_num": null,//账号
            "mkinvoice_type": "个人",//开票类型；1：公司；2：个人
            "invoice_pic": null,//图片
            "p_name": ""//平台名称
            },
            ....
            ]
            }
            }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function index(Request $request)
    {

        $InvoiceTable = new invoicetable;//实例化模型
        //$a = $InvoiceTable->select('id')->count();
        //dd($a);
        //1新发票10已开发票20已发快递30已取消
        if ($request->input('is_invoice') == 1) {
            $InvoiceTable = $InvoiceTable->where('is_invoice', 1);
        } elseif ($request->input('is_invoice') == 10) {
            $InvoiceTable = $InvoiceTable->where('is_invoice', 10);
        } elseif ($request->input('is_invoice') == 20) {
            $InvoiceTable = $InvoiceTable->where('is_invoice', 20);
        } elseif ($request->input('is_invoice') == 30) {
            $InvoiceTable = $InvoiceTable->where('is_invoice', 30);
        }
        if ($request->filled('invoice_order')) { //发票号
            $InvoiceTable = $InvoiceTable->where('invoice_order', 'like', '%' . $request->input('invoice_order') . '%');
        }
        if ($request->filled('order_num')) { //订单号
            $InvoiceTable = $InvoiceTable->where('order_num', 'like', '%' . $request->input('order_num') . '%');
        }
        if ($request->filled('client_tel')) {//客户电话
            $InvoiceTable = $InvoiceTable->where('client_tel', 'like', '%' . $request->input('client_tel') . '%');
        }
        if ($request->filled('bank_num')) {//账号
            $InvoiceTable = $InvoiceTable->where('bank_num', $request->input('bank_num'));
        }
        //invoice_project
        if ($request->filled('invoice_project')) {//发票项目查询
            $InvoiceTable = $InvoiceTable->where('invoice_project', $request->input('invoice_project'));
        }
        if ($request->filled('create_time')) {//时间
            $start_time = $request->input('create_time')[0];
            $end_time = $request->input('create_time')[1];
            $InvoiceTable = $InvoiceTable->where('create_time', '>', $start_time)->where('create_time', '<', $end_time);
        }
        $session = $request->get('session_token');
        if ($session['admin_groupnew']!=7) {//账号
            $InvoiceTable = $InvoiceTable->where('invoice_table.company_id', $session['company_id']);
        }

        $page_size = (int)$request->input('page_size', 20);
        $page = (int)$request->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }

        $offset = ($page - 1) * $page_size;
        $count = $InvoiceTable->count();
        $list = $InvoiceTable->leftJoin('pt', 'pt.id', '=', 'invoice_table.invoice_pid')->select('invoice_table.*', 'pt.p_paytype', 'pt_name')->orderBy('invoice_urgency', 'DESC')->orderBy('is_invoice', 'DESC')->offset($offset)->limit($page_size)->get();


        $showCount = InvoiceTable::selectRaw("is_invoice,count('id') as num")->groupBy('is_invoice')->get()->toArray();

        foreach ($showCount as $k => $v) {
            if ($v['is_invoice'] == 1) {
                $state1 = $v['num'];
            }
            if ($v['is_invoice'] == 10) {
                $state2 = $v['num'];
            }
            if ($v['is_invoice'] == 20) {
                $state3 = $v['num'];
            }
            if ($v['is_invoice'] == 30) {
                $state4 = $v['num'];
            }
        }
        $dkfp = $state1 ?? '0';//代开发票 1
        $ykfp = $state2 ?? '0';//已开发票 10
        $kdh = $state3 ?? '0';//快递号 20
        $fph = $state4 ?? '0';//发票号----------有争议需修改
        $showMenu = [
            ['show_name' => "全部", 'show_num' => '--','status'=>0],
            ['show_name' => "待开发票", 'show_num' => $dkfp,'status'=>1],
            ['show_name' => "已开发票", 'show_num' => $ykfp,'status'=>10],
            ['show_name' => "快递号", 'show_num' => $kdh,'status'=>20],
            ['show_name' => "已撤销（删除）", 'show_num' => $fph,'status'=>30],
        ];
        $data['show_num'] = $showMenu;
        $data['invoice_project'] = [['type'=>1,'name'=>'汽车电瓶'],['type'=>2,'name'=>'蓄电池'],['type'=>3,'name'=>'车膜']];
        $all_button = BmmcService::wherebutton($request->input('token'), $request->input('Pri_id'),$request->input('Login_id'));
        $export = BmmcService::getTopButton('AddEntry','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $invoiceType = PlatformService::getInvoiceType();//付款公司
        $invoiceTypeName = InvoiceService::getInvoiceTypeName();
        $mkinvoiceTypeName = InvoiceService::getMkinvoiceTypeName();
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            foreach ($list as $k => $v) {
                $buttonData = [];
                if($v['is_invoice']!=30) {
                    $buttonData[] = 'restentry,EditEntry,DelEntry,Urgency';
                }
                $button = BmmcService::getListButton($buttonData,$all_button);
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];
                $list[$k]['pay_type'] = $invoiceType[$v['p_paytype']]??'未设定';
                $list[$k]['mkinvoice_typename'] = $mkinvoiceTypeName[$v['mkinvoice_type']]??'未设定';
                $list[$k]['invoice_typename'] = $invoiceTypeName[$v['invoice_type']]??'未设定';
            }
            $data['show_num'] = $showMenu;//顶部分类数量
            $data['list'] = $list;    //数据
            $data['page'] = [//页码信息
                'page' => $request->input('page', 1),
                'page_size' => $page_size,
                'count' => $count,
                'allPage' => ceil($count / $page_size)
            ];

            return response()->json(['Data' => $data, 'ErrorCode' => '1', 'ErrorMessage' => '请求成功']);

        } else {
            $data['list'] = [];
            return response()->json(['Data' => $data, 'ErrorCode' => '3', 'ErrorMessage' => '暂无数据']);

        }
    }



    /**
     * @api {post} /api/Financial/invoiceTable/restentry 发票重置
     * @apiGroup 发票管理
     * @apiName 发票重置
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台管理列表
     *
     * @apiParam {int} id 发票编号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
        "ErrorCode": 1,
        "Data":'',
        "ErrorMessage":"操作成功"

        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function restentry(Request $request)
    {
        if (intval($request->input('id')) == 0) {
            return $this->error('ID参数缺失', ErrorInc::INVALID_PARAM);
        }
        $invoice = InvoiceTable::where('id', $request->input('id'))->first();
        if (!$invoice) {
            return $this->error('无法找到数据', ErrorInc::DATA_EMPTY);
        }
        $invoice->is_invoice = '1';
        $invoice->create_time = date('Y-m_d H:i:s');
        DB::beginTransaction();
//        $invoice = CommonService::dataToArray($invoice);
//        unset($invoice['id']);
//        $res = InvoiceTable::insert($invoice);
        $res = $invoice->save();
        $data['is_invoice'] = 30;
        $rea = InvoiceTable::where('id',$request->input('id'))->update($data);
        if ($res && $rea) {
            DB::commit();
            InvoiceTable::where('id',$request->input('id'))->update($data);
            $content = '重置，平台单号：' . $invoice['order_num'];
            $sys_num = OrderService::getOrderBy('order_num', $invoice['order_num'],['sys_num']);
            $this->insertingLog("重置,", $sys_num, $content, '发票管理', $request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功');

        } else {
            DB::rollBack();
            return $this->error('操作失败', ErrorInc::MYSQL_STEP_FAILED);

        }
    }


    /**
     * @api {post} /api/Financial/invoiceTable/edit 发票修改界面
     * @apiGroup 发票管理
     * @apiName 发票修改界面
     * @apiVersion 1.0.0
     *
     * @apiDescription 发票修改界面
     *
     * @apiParam {int} id 发票编号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *   {
        "error_code": 0,
        "data": {
        "uid": "1",
        "username": "12154545",
        "name": "吴系挂",
        "groupid": 2 ,
        "reg_time": "1436864169",
        "last_login_time": "0",
        }
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function edit(Request $request)
    {
        $input = $request->all();
        $checkKey = CommonService::checkKey(['id', 'invoice_pid','pay_type'],$input,array('id'=>'数据编号','invoice_pid'=>'订单平台','pay_type'=>'结款公司'));
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $id = $request->input('id');
        $res = InvoiceTable::where('id', $id)->first();
        if (!$res) {
            return $this->error('无法找到数据', ErrorInc::DATA_EMPTY);
        }
        $platform = PlatformService::getFieldsById($request->input('invoice_pid'), ['p_paytype']);
        $pay_type = $platform;
        if ($pay_type == 1) {
            $invoice_order = DB::table('invoice_num')->where(['status' => 1, 'is_del' => 1])->orderBy('id', 'ASC')->value('invoice_order');
        } else {
            $invoice_order = DB::table('invoice_num')->where(['status' => 1, 'is_del' => 1, 'sys_company' => $pay_type])->orderBy('id', 'ASC')->value('invoice_order');
        }

        if ($invoice_order && $res['is_invoice'] == 1) {
            $res['invoice_order'] = $invoice_order;
        }

        return $this->success('获取成功', $res);
    }

    /**
     * @api {post} /api/Financial/invoiceTable/checkNumber 发票修验证
     * @apiGroup 发票管理
     * @apiName 发票修验证
     * @apiVersion 1.0.0
     *
     * @apiDescription 发票修验证
     *
     * @apiParam {string} order_num 平台单号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *   {
        "error_code": 0,
        "ErrorMessage":"验证成功",
        "data": []
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"平台单号不能为空","Data":[]}
     *
     */
    public function checkNumber(Request $request)
    {
        $message = [
            'order_num.required' => '平台单号不能为空',
            'order_num.unique' => '平台单号已存在',
        ];
        $rules = [
            'order_num' => 'required|unique:invoice_table,order_num,' . $request->input('order_num'),
        ];
        $Validator = Validator::make($request->all(), $rules, $message);
        if ($Validator->fails()) {
            return $this->error($Validator->errors()->first(), ErrorInc::INVALID_PARAM);
        }
        return $this->success('验证成功');
    }

    /**
     * @api {post} /api/Financial/invoiceTable/EditEntry 编辑发票
     * @apiGroup 发票管理
     * @apiName 编辑发票
     * @apiVersion 1.0.0
     *
     * @apiDescription 编辑发票
     *
     * @apiParam {int} id       id号
     * @apiParam {int}  invoice_pid  平台id
     * @apiParam {string}  client_name  客户姓名
     * @apiParam {string} client_tel   客户电话
     * @apiParam {string} client_addr    客户地址
     * @apiParam {string} invoice_header  发票台头
     * @apiParam {string} invoice_project 发票项目
     * @apiParam {int} invoice_type    发票类型
     * @apiParam {int} mkinvoice_type  开票类型
     * @apiParam {string} invoice_value   发票金额
     * @apiParam {string} order_num       平台单号
     * @apiParam {string} tax_num         税号
     * @apiParam {string} company_addr    公司地址
     * @apiParam {string} company_tel     公司电话
     * @apiParam {string} bank            开户行
     * @apiParam {string} bank_num        账号
     * @apiParam {string} content         开票备注
     * @apiParam {string} pay_type        付款账号
     * @apiParam {string} invoice_order   发票号
     * @apiParam {string} invoice_time    开票时间
     * @apiParam {string} invoice_kd      快递单号
     * @apiParam {string} invoice_pic     发票图片
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *   {
        "error_code": 0,
        "ErrorMessage":"成功",
        "data": []
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"平台单号不能为空","Data":[]}
     *
     */
    public function update(Request $request)
    {
        $input = $request->only('id', 'invoice_kd', 'pay_type', 'order_num', 'client_name', 'client_tel', 'client_addr', 'invoice_order', 'invoice_type', 'invoice_header', 'invoice_project', 'invoice_value', 'content', 'company_addr', 'bank', 'company_tel', 'bank_num', 'tax_num', 'invoice_pic', 'is_invoice', 'mkinvoice_type','invoice_time');
        $message = [
            'order_num.required' => '平台单号不能为空',
            //'order_num.unique' => '平台单号已存在',
            'client_name.required' => '客户姓名不能为空',
            'client_tel.required' => '客户电话不能为空',
            'client_tel.regex' => '客户电话格式错误',
            'client_addr.required' => '客户地址不能为空',
            'invoice_type.required' => '必须选择发票类型',
            'invoice_header.required' => '发票台头不能为空',
            'invoice_project.required' => '必须选择发票项目',
            'invoice_value.required' => '发票金额不能为空',
            'invoice_value.numeric' => '发票金额必须为数字',
            'invoice_value.id' => '数据编号不能为空',
        ];
        $rules = [
            'id' => 'required',
            'order_num' => 'required',
            //'order_num' => 'required|unique:invoice_table,order_num,' . $request->input('id'),
            'client_name' => 'required',
            'client_tel' => 'required|regex:/^1[0-9]{10}$/',
            'client_addr' => 'required',
            'invoice_type' => 'required',
            'mkinvoice_type' => 'required',
            'invoice_header' => 'required',
            'invoice_project' => 'required',
            'invoice_value' => 'required|numeric',
        ];
        $Validator = Validator::make($request->all(), $rules, $message);

        if ($Validator->fails()) {
            $error = CommonService::validatorToString($Validator);
            return $this->error($error, ErrorInc::INVALID_PARAM);
        }
        //提交发票信息
        $id = $input['id'];
        $invoice_orders = $request->input('invoice_order');
        $res = InvoiceTable::where('id', $id)->first();
        if ($input['is_invoice'] != 1) {
            if (($res['invoice_header'] != $input['invoice_header']) || ($res['invoice_type'] != $input['invoice_type']) || ($res['mkinvoice_type'] != $input['mkinvoice_type']) || ($res['invoice_project'] != $input['invoice_project'])) {

                return $this->error('发票抬头，发票类型，发票项目，开票类型不可编辑', ErrorInc::INVALID_PARAM);
            }
        }
        if (!preg_match("/^[a-zA-Z0-9\-\(\)]+$/", $input['order_num'])) {

            return $this->error('原始单号存在特殊符号', ErrorInc::INVALID_PARAM);
        }

        $order = OrderService::getOrderByOrderNumber($input['order_num']);
        if (!$order) {
            return $this->error('平台单号不存在', ErrorInc::INVALID_PARAM);
        }
//            $sys_num = Orders::where('order_num', $input['order_num'])->value('order_num');

        if ($invoice_orders != '' && $input['pay_type'] == '未设定') {
            return $this->error('请去平台设置付款账号', ErrorInc::INVALID_PARAM);
        }

        $invoice_order = InvoiceService::findInvoiceNumBy('invoice_order', $invoice_orders);
//            $invoice_order = DB::table('invoice_num')->where('invoice_order', $invoice_orders)->value("invoice_order");
        if ($invoice_order || $invoice_orders == '') {
            $invoice_id = InvoiceService::checkExistInvoiceOrder($invoice_orders, $id);
            if ($request->input('invoice_order') != '' && $invoice_id) {

                return $this->error('发票号已使用', ErrorInc::INVALID_PARAM);
            }

            $is_del = $invoice_order["is_del"];
            if ($request->input('invoice_order') != '' && $is_del == 2) {

                return $this->error('发票号已作废', ErrorInc::INVALID_PARAM);
            }
            $sys_company = $invoice_order["sys_company"];
            switch ($input['pay_type']) {
                case '蓝城付款':
                    $input['pay_type']=5;
                    break;
                case '速电付款':
                    $input['pay_type']=2;
                    break;
                case '个人付款':
                    $input['pay_type']=6;
                    break;
            }
            if ($sys_company == $input['pay_type'] || $invoice_orders == '') {
                $invoice_kd = InvoiceService::checkExistExpressNO($input['invoice_kd'], $id);
                if ($input['invoice_kd'] != '' && $invoice_kd) {
                    return $this->error('快递单号已存在', ErrorInc::INVALID_PARAM);
                }

                if ($invoice_orders != '' && $input['invoice_kd'] == '') {
                    $input['is_invoice'] = '10';
                }
                if ($input['invoice_kd'] != '') {
                    $input['is_invoice'] = '20';
                }

                if ($request->filled('invoice_pic')) {
                    /*if ($res['invoice_pic'] != '') {
                        $old_url = $res['invoice_pic'];
                    } else {
                        $old_url = '';
                    }*/
                    $file = $request->input('invoice_pic');
                    /*$curl_data = $this->curl_uplodefile(2, './Uploads/invoicepicture/' . date('Ym'), $file, $old_url);
                    if ($curl_data != 'error') {
                        $input['invoice_pic'] = $curl_data;
                    } else {
                        return $this->error('图片上传失败', ErrorInc::FILE_UPLOAD_FAILED);
                    }*/

                    $input['invoice_pic'] = $file;

                } else {
                    unset($input['invoice_pic']);
                }
                unset($input['id']);
                unset($input['p_paytype']);
                unset($input['pay_type']);
                unset($input['type']);
                unset($input['token']);
                $res = InvoiceTable::where('id', $id)->update($input);

                if ($res) {
                    if ($request->filled('invoice_order')) {
                        $id = $invoice_order["id"];
                        if ($id) {
                            if ($input['is_invoice'] !== 1) {
                                $data['status'] = '2';
                            } else {
                                $data['status'] = '1';
                            }
                            $data['sys_num'] = $input['order_num'];
                            InvoiceService::updateInvoiceNum($data, ['invoice_order'=> $input['invoice_order']]);
                        }
                    }
                    $sys_num = $order["sys_num"];
                        $this->insertingLog("编辑发票，", $sys_num, "平台单号：" . $input['order_num'], "发票管理", $request->ip(), $request->get('session_token')['admin_acc']);
                    return $this->success($input['order_num'].':操作成功');
                } else {
                    return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
                }
            } else {
                return $this->error('发票号对应公司和单号对应公司不一致', ErrorInc::INVALID_PARAM);
            }

        } else {
            return $this->error('发票号不存在', ErrorInc::INVALID_PARAM);
        }
    }

    /**
     * @api {post} /api/Financial/invoiceTable/store 添加发票
     * @apiGroup 发票管理
     * @apiName 添加发票
     * @apiVersion 1.0.0
     *
     * @apiDescription 添加发票
     *
     * @apiParam {int}  invoice_pid  平台id
     * @apiParam {string}  client_name  客户姓名
     * @apiParam {string} client_tel   客户电话
     * @apiParam {string} client_addr    客户地址
     * @apiParam {string} invoice_header  发票台头
     * @apiParam {string} invoice_project 发票项目
     * @apiParam {int} invoice_type    发票类型
     * @apiParam {int} mkinvoice_type  开票类型
     * @apiParam {string} invoice_value   发票金额
     * @apiParam {string} order_num       平台单号
     * @apiParam {string} tax_num         税号
     * @apiParam {string} company_addr    公司地址
     * @apiParam {string} company_tel     公司电话
     * @apiParam {string} bank            开户行
     * @apiParam {string} bank_num        账号
     * @apiParam {string} content         开票备注
     * @apiParam {string} pay_type        付款账号
     * @apiParam {string} invoice_order   发票号
     * @apiParam {string} invoice_time    开票时间
     * @apiParam {string} invoice_kd      快递单号
     * @apiParam {string} invoice_pic     发票图片
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *   {
    "error_code": 0,
    "ErrorMessage":"成功",
    "data": []
    }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"平台单号不能为空","Data":[]}
     *
     */
    public function store(Request $request)
    {
        $input = $request->all();
        $input['creator'] = $request->get('session_token')['admin_acc'];
        unset($input['token']);
        unset($input['Login_id']);
        unset($input['Pri_id']);//删除
        if (!preg_match("/^[a-zA-Z0-9\-\(\)]+$/", $input['order_num'])) {
            return $this->error('原始单号存在特殊符号', ErrorInc::INVALID_PARAM);
        } else {
            $message = [
                'order_num.required' => '平台单号不能为空',
                'order_num.unique' => '平台单号已存在',
                'client_name.required' => '客户姓名不能为空',
                'client_tel.required' => '客户电话不能为空',
                'client_tel.regex' => '客户电话格式错误',
                'client_addr.required' => '客户地址不能为空',
                'invoice_type.required' => '必须选择发票类型',
                'invoice_header.required' => '发票台头不能为空',
                'invoice_project.required' => '必须选择发票项目',
                'invoice_value.required' => '发票金额不能为空',
                'invoice_value.numeric' => '发票金额必须为数字',
            ];
            $rules = [
                'order_num' => 'required|unique:invoice_table,order_num',
                'client_name' => 'required',
                'client_tel' => 'required|regex:/^1[0-9]{10}$/',
                'client_addr' => 'required',
                'invoice_type' => 'required',
                'mkinvoice_type' => 'required',
                'invoice_header' => 'required',
                'invoice_project' => 'required',
                'invoice_value' => 'required|numeric',
            ];
            $Validator = Validator::make($request->all(), $rules, $message);
            if ($Validator->fails()) {
                return $this->error($Validator->errors()->first(), ErrorInc::INVALID_PARAM);
            }
            $sys_num = OrderService::getOrderByOrderNumber($input['order_num']);
//            $sys_num = Orders::where('order_num', $input['order_num'])->first();

            if ($sys_num && ($sys_num['return_num'] == 15) && ($request->input('type') != 1)) {
                return $this->error('该订单已开电子发票，是否改为纸质发票？', ErrorInc::INVALID_PARAM);
            }
            if ($sys_num) {
                $order_num = InvoiceTable::where('order_num', $input['order_num'])
                    ->where('is_invoice', '!=', 30)
                    ->value("id");//还没理解透先放下
                if ($order_num) {
                    return $this->error('原始单号已存在', ErrorInc::INVALID_PARAM);
                } else {
                    if ($input['mkinvoice_type'] == '2') {
                        unset($input['tax_num']);
                        unset($input['company_addr']);
                        unset($input['company_tel']);
                        unset($input['bank']);
                        unset($input['bank_num']);
                        unset($input['pay_type']);
                    }
                    $input['invoice_pid'] = $sys_num['p_id'];

                    if ($request->filled('invoice_pic')) {
                        $file = $request->input('invoice_pic');
                        $input['invoice_pic'] = $file;
                    }
                    unset($input['type']);
                    unset($input['pay_type']);
                    unset($input['invoice_kd']);
                    unset($input['invoice_order']);
                    unset($input['create_time']);
                    unset($input['invoice_pic']);
                    $input['company_id'] = $request->get('session_token')['company_id'];
                    $res = InvoiceTable::insert($input);
                    if ($res) {
                        if ($sys_num['return_num'] == 15) {
                            Orders::where('order_num', $input['order_num'])->update(['return_num' => 10]);;
                        }

                        $this->insertingLog("添加发票，", $sys_num, "平台单号：" . $input['order_num'], "发票管理", $request->ip(), $request->get('session_token')['admin_acc']);//日志

                        return $this->success('添加成功');
                    } else {
                        return $this->error('添加失败', ErrorInc::MYSQL_FAILED);
                    }
                }
            } else {
                return $this->error('平台单号不存在', ErrorInc::DATA_EMPTY);
            }
        }
    }

    /**
     * @api {post} /api/Financial/invoiceTable/delete 删除发票
     * @apiGroup 发票管理
     * @apiName 删除发票
     * @apiVersion 1.0.0
     *
     * @apiDescription 删除发票
     *
     * @apiParam {int} id id号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *   {
        "error_code": 0,
        "ErrorMessage":"成功",
        "data": []
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"删除失败","Data":[]}
     *
     */
    public function destroy(Request $request)
    {
        if(!$request->filled('id')){
            return $this->error('缺少数据编号', ErrorInc::DATA_EMPTY);exit;
        }
        $id = $request->input('id');
        $invoice = InvoiceTable::where('id', $id)->first();
        if (!$invoice) {
            return $this->error('未找到内容', ErrorInc::DATA_EMPTY);
        }
        $invoice_pic = $invoice['invoice_pic'];
        $data['is_invoice'] = 30;
        $result = InvoiceTable::where('id', $id)->update($data);
        if ($result) {
            $sys_num = OrderService::getOrderBy('order_num', $invoice['order_num'],['sys_num']);
            $this->insertingLog('删除，', $sys_num, "平台单号：" . $invoice['order_num'], '发票管理', $request->ip(), $request->get('session_token')['admin_acc']);//日志

            return $this->success('删除成功');
        } else {
            return $this->error('删除失败', ErrorInc::MYSQL_FAILED);
        }
    }


    /**
     * @api {post} /api/Financial/invoiceTable/Urgency 发票加急
     * @apiGroup 发票管理
     * @apiName 发票加急
     * @apiVersion 1.0.0
     *
     * @apiDescription 发票加急
     *
     * @apiParam {int} id id号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *   {
        "error_code": 0,
        "ErrorMessage":"操作成功",
        "data": []
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"操作成功","Data":[]}
     *
     */
    public function Urgency(Request $request)
    {
        if(!$request->filled('id')){
            return $this->error('缺少数据编号', ErrorInc::DATA_EMPTY);exit;
        }
        $id = $request->input('id');
        if ($id) {
            $invoice = InvoiceTable::where('id', $id)->first();
            if (!$invoice) {
                return $this->error('未找到内容', ErrorInc::DATA_EMPTY);
            }
            $res = InvoiceTable::where('id', $id)->update(['invoice_urgency' => '10']);
            if ($res) {
                $sys_num = OrderService::getOrderBy('order_num', $invoice['order_num'],['sys_num']);
                $order_num = $invoice["order_num"];
                $this->insertingLog("发票加急，", $sys_num, "平台单号：" . $order_num, "发票管理", $request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
            }
        }
    }


    //生成图片路径
    public function creact_url()
    {
        $streamFileRand = date('YmdHis') . str_pad(rand(1000, 9999), 3, '0', STR_PAD_LEFT);    //产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $upPath = './Uploads/invoicepicture/' . date('Ym');
        if (!is_dir($upPath)) {
            mkdir($upPath, '777');
        }
        $streamFilename = $upPath . "/" . $streamFileRand . ".png";
        if (file_exists($streamFilename)) {
            $this->creact_url();
        } else {
            return $streamFilename;
        }
    }
}
