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

namespace App\Http\Controllers\Financial;

use App\Http\Controllers\BaseController;
use App\Services\CommonService;
use App\Services\InvoiceService;
use App\Services\PlatformService;
use Illuminate\Http\Request;
use App\Models\Admin;
use Maatwebsite\Excel\Facades\Excel;
use \Exception;
use Illuminate\Support\Facades\DB;
use BlueCity\Core\Inc\ErrorInc;

class InvoiceNumController extends BaseController
{

    /**
     * @api {post}  /api/Financial/invoiceNum 列表页
     * @apiGroup 发票号管理
     * @apiName 列表页
     * @apiVersion 1.0.0
     *
     * @apiDescription 列表页
     *
     * @apiParam {int} id  平台ID
     * @apiParam {int} state         使用状态 1:未使用; 2:已使用
     * @apiParam {string} invoice_order 发票号
     * @apiParam {string} start_time    开始时间
     * @apiParam {string} end_time      结束时间
     * @apiParam {string} sys_num       系统单号
     * @apiParam {int} is_del        是否作废 1:已作废;2:未作废
     * @apiParam {int} company       公司 0:不限;5:蓝城;2:速电;6:个人
     * @apiParam {int} page_size  页大小
     * @apiParam {int} page  页码
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "errorCode": 1,
        "errorMessage": "成功",
        "data": {
        "page": {//页码数据
        "page": 1,    //当前页码
        "page_size": 20,//每页显示条数
        "count": 479     //总条数
        },
        count_arr:{
        qb:5,     //全部
        wsy:1,   //未使用
        ysy:2,   //已使用
        }
        "list": [
        {
        "id": 1456,                           //id
        "invoice_order": 87756685,            //发票号
        "create_admin": "亢静保",              //添加人
        "create_time": "2019-05-15 13:07:51", //添加时间
        "sys_num": "260069315926959143",      //关联订单号
        "status": 2,                          //1未使用  2已使用
        "is_del": 1,                          //1正常   2已作废
        "sys_company": 5,                     //忽略
        "company": "蓝城"                     //对应公司
        }
        ]
        }
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */

    public function index(Request $request)
    {
        //页码数据
        $page_size = (int)$request->input('page_size', 10);
        $page = (int)$request->input('page', 1);

        $where = $this->parseCondition($request);
//        dump($where);
        $data = InvoiceService::searchIvoiceNum($where, ['*'], $page, $page_size);
        $data = InvoiceService::formatInvoiceNumContent($request->input('token'), $request->input('Pri_id'), $data);
        $list = $data['list'];
        if ($list) {
            return $this->success('获取成功', $data);
        } else {
            $data['list'] = [];
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $data);
        }
    }

    private function parseCondition($request)
    {
        $where = [];
        //类型      0 全部  1 未使用  2 已使用
        if ($request->filled('state') && (int)$request->input('state', 0) != 0) {
            $where['status'] = (int)$request->input('state');
        }
        $session = $request->get('session_token');
        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $where['company_id'] = $session['company_id'];
        }

        //发票号
        if ($request->filled('invoice_order')) {
            $where['invoice_order_rlike'] = $request->input('invoice_order');
        }
        if($request->filled('creatData')){//创建时间
            $creatData = $request->input('creatData');
            $creatData['creatData'][1] = date("Y-m-d", strtotime($creatData['creatData'][1] . " +1 day"));
            $where['gone_orders.create_time_between'] = $creatData['creatData'];
        }

        //关联订单号
        if ($request->filled('sys_num')) {
            $where['sys_num_rlike'] = $request->input('sys_num');
        }

        //是否作废 0不限   1 未作废   2 已作废
        if ($request->filled('is_del') && (int)$request->input('is_del', 0) != 0) {
            $where['is_del'] = (int)$request->input('is_del');
        }

        //公司  0 不限    5 蓝城  2 速电   6 个人
        if ($request->filled('company') && (int)$request->input('company', 0) != 0) {
            $where['sys_company'] = (int)$request->input('company');
        }
        $where = CommonService::jointWhere($where);
        return $where;
    }

    public function export(Request $request)
    {
        $where = $this->parseCondition($request);
        //导出 excel
        $data = InvoiceService::searchIvoiceNum($where, ['*'], 1, 0);
        $list = $data['list'];
        if (!$list->isEmpty()) {
            $excelData = $this->Into_Out_Excel($list->toArray());

            $this->success('成功', $excelData);
        } else {
            return response()->json($this->Into_Out_Excel([]));
        }
    }

    /**
     * @api {post}  /api/Financial/invoiceNum/store 添加
     * @apiGroup 发票号管理
     * @apiName 添加
     * @apiVersion 1.0.0
     *
     * @apiDescription 添加
     *
     * @apiParam {int} company   5:蓝城;2:速电;6:个人
     * @apiParam {string} num_start 开始发票号
     * @apiParam {string} num_end   结束发票号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "添加成功",
        "Data":''
        ]
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */

    public function store(Request $request)
    {
        $company = (int)$request->input('company');
        if (!$request->filled('num_start') || !$request->filled('num_end') || !in_array($company, [8, 9, 10])) {

            return $this->error('参数错误', ErrorInc::INVALID_PARAM);
        }
        $str1 = $request->input('num_start');
        $str2 = $request->input('num_end');
        if ($str1 > $str2) {
            return $this->error('开始发票号大于结束发票号', ErrorInc::INVALID_PARAM);
        }
        if (!preg_match("/^[0-9]*$/", $str1)) {
            return $this->error('开始发票号存在特殊符号', ErrorInc::INVALID_PARAM);
        }

        if (!preg_match("/^[0-9]*$/", $str2)) {
            return $this->error('结束发票号存在特殊符号', ErrorInc::INVALID_PARAM);
        }
        $exist = InvoiceService::checkNumExist($str1, $str2);
        if ($exist) {
            return $this->error('原始发票号已存在', ErrorInc::REPEAT_SUBMIT);
        }
        //添加发票号
        $data = [];
        for ($i = $str1; $i <= $str2; $i++) {
            //return 'sss';
            $temp = [];
            $temp['invoice_order'] = $i;
            $temp['create_time'] = date("Y-m-d H:i:s");
            $temp['create_admin'] = $request->get('session_token')['admin_acc'];
            $temp['sys_company'] = $company;
            $temp['company_id'] = $request->get('session_token')['company_id'];
            $data[] = $temp;

        }
        $res = InvoiceService::createInvoiceNum($data);
        if ($res) {
            InvoiceService::createInvoicePart([
                'section_start' => $str1,
                'section_end' => $str2,
                'create_time' => date("Y-m-d H:i:s"),
                'create_admin' => $request->get('session_token')['admin_acc'],
                'company_id' => $request->get('session_token')['company_id'],
                'ass_company' => $company
            ]);
            // $this->inserting_log("添加发票号，",$str1."-".$str2," 关联公司：".$company,"发票号管理");//日志
            $invoiceType = PlatformService::getInvoiceType();
            $content = "添加发票号，关联公司：" . $invoiceType[$company] . "，号码范围：" . $str1 . "-" . $str2;
            $this->insertingLog('添加,', '', $content, '发票号管理', $request->ip(), $request->get("session_token")['admin_acc']);
            return $this->success('添加成功');
        } else {
            return $this->error('添加失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @api {post}  /api/Financial/invoiceNum/edit 修改界面
     * @apiGroup 发票号管理
     * @apiName 修改界面
     * @apiVersion 1.0.0
     *
     * @apiDescription 修改界面
     *
     * @apiParam {string} number 发票号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "成功",
        "Data": "速电"
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"无此票号","Data":[]}
     *
     */

    public function edit(Request $request)
    {
        if($request->filled('number')) {
            $order = $request->input('number');
            $invoiceOrder = InvoiceService::findInvoiceNumBy('invoice_order', $order);
            if (!$invoiceOrder) {
                return $this->error('无此票号', ErrorInc::DATA_EMPTY);
            } else {
                $invoiceType = PlatformService::getInvoiceType();
                $company = $invoiceOrder['sys_company'];
                $oldcompany = $invoiceType[$company] ?? '未发现对应公司';
                return $this->success('成功', $oldcompany);
            }
        }else{
            return $this->error('发票号必填', ErrorInc::INVALID_PARAM);
        }
    }

    /**
     * @api {post}  /api/Financial/invoiceNum/update 编辑
     * @apiGroup 发票号管理
     * @apiName 编辑
     * @apiVersion 1.0.0
     *
     * @apiDescription 编辑
     *
     * @apiParam {int} company   5:蓝城;2:速电;6:个人
     * @apiParam {string} number 发票号
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "操作成功",
        "Data":''
        ]
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */

    public function update(Request $request)
    {
        $input = $request->all();
        $checkKey=CommonService::checkKey(['number', 'company'],$input,array('number'=>'发票单号','company'=>'开票公司'));
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $num = $request->input('number');
        $company = (int)$request->input('company', 0);

        $invoice = InvoiceService::findInvoiceNumBy('invoice_order', $num);
        if (!$invoice) {
            return $this->error('未查到该号码', ErrorInc::DATA_EMPTY);
        }

        $invoice_order = $invoice['invoice_order'];
        $invoiceType = PlatformService::getInvoiceType();
        $oldcompany = $invoiceType[$invoice['sys_company']] ?? '未发现对应公司';
        if ($invoice_order && in_array($company, [2, 5, 6])) {
            //搜索 发票号段 然后进行编辑
            $section = InvoiceService::findSection($invoice_order);
            $res = InvoiceService::updateInvoice($invoice_order, $company);
            if ($res) {
                $mewcompany = $invoiceType[$company] ?? '未发现对应公司';
                $content = "编辑发票号，管联公司：" . $oldcompany . "->".$mewcompany."，号码范围：" . $section['section_start'] . "-" . $section['section_end'];
                $this->insertingLog('编辑,', '', $content, '发票号管理', $request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('操作成功');
            } else {
                return $this->error('添加失败', ErrorInc::MYSQL_FAILED);
            }

        } else {
            $this->error('参数错误', ErrorInc::DATA_EMPTY);
        }
    }

    /**
     * @api {post}  /api/Financial/invoiceNum/handleInvoice 处理
     * @apiGroup 发票号管理
     * @apiName 处理
     * @apiVersion 1.0.0
     *
     * @apiDescription 处理
     *
     * @apiParam {int} id   数据id
     * @apiParam type 1:恢复  2:作废
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {
        "ErrorCode": 1,
        "ErrorMessage": "操作成功",
        "Data":''
        ]
        }
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function handleInvoice(Request $request)
    {
        $input = $request->all();
        $befor = InvoiceService::_beforhandleInvoice( $input , 2);
        if(isset($befor['ErrorCode'])){
            return $befor;
        }else{
            $res = InvoiceService::handleInvoice($input['id'], 2);
            $order = $befor['invoice_order'];
            $str = "作废";
            $content = "操作：" . $str . "，" . $order;
            $this->insertingLog("处理，", "", $content, "发票号管理", $request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功 '.$str);
        }
    }

    public function handleInvoiceH(Request $request)
    {
        $input = $request->all();
        $befor = InvoiceService::_beforhandleInvoice( $input , 1);
        if(isset($befor['ErrorCode'])){
            return $befor;
        }else{
            $res = InvoiceService::handleInvoice($input['id'], 1);
            $order = $befor['invoice_order'];
            $str = "恢复";
            $content = "操作：" . $str . "，" . $order;
            $this->insertingLog("处理，", "", $content, "发票号管理", $request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功 '.$str);
        }
    }

    //导出excel
    public function Into_Out_Excel($data)
    {
        $name = 'invoicenum' . date('YmdHis');
        Excel::create($name, function ($excel) use ($data) {
            $excel->sheet('sheet1', function ($sheet) use ($data) {
                $sheet->setWidth(array('A' => 16, 'B' => 16, 'C' => 14, 'D' => 20, 'E' => 20, 'F' => 14, 'G' => 16, 'H' => 16))->setFontSize(12);
                $company = [5 => '蓝城', 2 => '速电', 6 => '个人'];

                $sheet->cell('A1', '序号(不可更改)');
                $sheet->cell('B1', '发票号');
                $sheet->cell('C1', '创建人');
                $sheet->cell('D1', '创建时间');
                $sheet->cell('E1', '关联平台单号');
                $sheet->cell('F1', '对应公司');
                $sheet->cell('G1', '使用状态');
                $sheet->cell('H1', '是否作废');
                if (!empty($data)) {
                    foreach ($data as $key => $value) {
                        $i = $key + 2;
                        $sheet->cell('A' . $i, $value['id']);
                        $sheet->cell('B' . $i, $value['invoice_order']);
                        $sheet->cell('C' . $i, $value['create_admin']);
                        $sheet->cell('D' . $i, $value['create_time']);
                        $sheet->cell('E' . $i, "\t" . $value['sys_num'] . "\t");
                        $sheet->cell('F' . $i, $company[$value['sys_company']] ?? '其他');
                        $sheet->cell('G' . $i, $value['status'] == 1 ? '未使用' : '已使用');
                        $sheet->cell('H' . $i, $value['is_del'] == 1 ? '正常' : '已作废');
                    }
                }
            });
        })->save('xls', public_path('excel'));
        return ['ErrorCode' => 1, 'ErrorMeassage' => "成功", 'Data' => $this->baseurl() . 'excel/' . $name . '.xls'];
    }
}
