<?php
/**
 * 发票服务
 *
 * @author lixiaolin
 * @Date: 2021/4/2
 * @Time: 下午13:50
 * @Email: lixiaolin@bluearp.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Models\InvoiceTable;
use App\Models\User;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class InvoiceService extends Service
{
    public static $instance;
    private $modelMain = null;

    public function __construct()
    {
        if (!$this->modelMain) $this->modelMain = new InvoiceTable();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**|---------------------------------------------------------------------------------
     * @name 作废以及恢复前验证
     * @param array $input 请求参数
     * @retrun /multitype:array
     * @author dou 2021/10/15 17:15
     * |---------------------------------------------------------------------------------
    */
    public static function _beforhandleInvoice ( $input , $type = 1){
        if(!isset($input['id'])){
            return ['ErrorCode'=>ErrorInc::INVALID_PARAM,'ErrorMessage'=>'缺少数据编号','Data'=>[]];
        }
        $invoice = self::findInvoiceNumBy('id', $input['id']);
        if(!$invoice){
            return ['ErrorCode'=>ErrorInc::DATA_EMPTY,'ErrorMessage'=>'无对应数据','Data'=>[]];
        }else{
            if($invoice['is_del'] == $type){
                return ['ErrorCode'=>1,'ErrorMessage'=>'操作成功','Data'=>[]];
            }else{
                return $invoice;
            }
        }
    }

    public static function handleInvoice($id, $state) {
        return Db::table('invoice_num')->where('id', $id)->update(['is_del' => $state]);
    }

    public static function searchIvoiceNum($where, $columns = array('*'), $page = 1, $pageSize = 20)
    {
        if ($page <= 0) {
            $page = 1;
        }
        $count = Db::table('invoice_num');
        if($where!=''){
            $count = $count->whereRaw($where);
        }
        $count = $count->count();
        $totalPage = ceil($count / $pageSize);
        $list = Db::table('invoice_num');
        if($where!=''){
            $list = $list->whereRaw($where);
        }
        $list = $list->select($columns)->orderBy('id', 'desc');
        if ($pageSize > 0) {
            $offset = ($page - 1) * $pageSize;

            $list = $list
                ->offset($offset)
                ->limit($pageSize);
        }
        $list = $list->get();
        $result = [];
        $result['page'] = ['totalPage' => $totalPage, 'count' => $count, 'page' => $page, 'page_size' => $pageSize];
        $result['list'] = $list;

        return $result;
    }

    public static function formatInvoiceNumContent($token, $Pri_id, $data) {
        $list = $data['list'];
        $all_button = BmmcService::whereButton($token,$Pri_id);
        $export = BmmcService::getTopButton('addInvoice,editInvoice','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $invoiceType = PlatformService::getInvoiceType();
        $statusName = self::getStatusName();
        $delName = self::getDelName();
        if (!$list->isEmpty()) {
            $temp = $list->toArray();
            unset($list);
            $list = $temp;
            foreach ($list as $k => $val) {
                $buttonData = [];
                if($val['is_del'] == '1'){
                    $buttonData[] = 'handleInvoice';
                }if($val['is_del'] == '2'){
                    $buttonData[] = 'handleInvoiceH';
                }
                $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]['company'] = $invoiceType[$val['sys_company']]??'其他';
                $list[$k]['statusName'] = $statusName[$val['status']]??'未确认';
                $list[$k]['delName'] = $delName[$val['is_del']]??'未确认';
            }
            //统计数量
//            $count_data = Db::table('invoice_num')->selectRaw('status,count(id) as num')->groupBy('status')->get()->toArray();
//            $arr = ['wsy' => 0, 'ysy' => 0, 'qb' => 0];
//            foreach ($count_data as $key => $val) {
//                if ($val['status'] == 1) {
//                    $arr['wzz'] = $val['num'];
//                } else {
//                    $arr['yzz'] = $val['num'];
//                }
//            }
//            $arr['qb'] = $arr['wsy'] + $arr['ysy'];
//            $data['count_arr'] = $arr;
            $data['list'] = $list;
        }
        $invoiceType = PlatformService::getInvoiceType(false);
        unset($invoiceType[0]);
        $invoiceType = CommonService::resetListKey($invoiceType);
        $data['invoiceType'] = $invoiceType;
        $data['status'] = self::getStatusName(false);
        $data['is_del'] = self::getDelName(false);
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取发票使用状态名称
     * @retrun /multitype:array
     * @author dou 2021/10/15 10:46
     * |---------------------------------------------------------------------------------
    */
    public static function getStatusName ( $type = true ){
        $statusName = array(array('type'=>'1','name'=>'未使用'),array('type'=>'2','name'=>'已使用'));
        if($type == 1){
            $statusName = array_column($statusName, 'name','type');
        }
        return $statusName;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取发票状态名称
     * @retrun /multitype:array
     * @author dou 2021/10/15 14:01
     * |---------------------------------------------------------------------------------
    */
    public static function getDelName ( $type = true ){
        $delName = array(array('type'=>'1','name'=>'未删除'),array('type'=>'2','name'=>'已删除'));
        if($type == 1){
            $delName = array_column($delName, 'name','type');
        }
        return $delName;
    }

    /**|---------------------------------------------------------------------------------
     * @name 发票类型名称
     * @retrun /multitype:array
     * @author dou 2021/10/15 18:47
     * |---------------------------------------------------------------------------------
    */
    public static function getInvoiceTypeName ( $type = true ){
        $invoiceTypeName = array(array('type'=>'1','name'=>'增票'),array('type'=>'2','name'=>'普票'));
        if($type == 1){
            $invoiceTypeName = array_column($invoiceTypeName, 'name','type');
        }
        return $invoiceTypeName;
    }

    /**|---------------------------------------------------------------------------------
     * @name 开票类型名称
     * @retrun /multitype:array
     * @author dou 2021/10/15 19:38
     * |---------------------------------------------------------------------------------
    */
    public static function getMkinvoiceTypeName ( $type = true ){
        $mkinvoiceTypeName = array(array('type'=>'1','name'=>'公司'),array('type'=>'2','name'=>'个人'));
        if($type == 1){
            $mkinvoiceTypeName = array_column($mkinvoiceTypeName, 'name','type');
        }
        return $mkinvoiceTypeName;
    }

    public static function checkNumExist($start, $end)
    {
        return Db::table('invoice_num')->whereBetween('invoice_order', [$start, $end])->first();
    }

    public static function createInvoiceNum($data)
    {
        return Db::table('invoice_num')->insert($data);
    }

    public static function createInvoicePart($data)
    {
        return Db::table('invoice_part')->insert($data);
    }

    public static function findInvoiceNum($invoiceNum)
    {
        return Db::table('invoice_num')->find($invoiceNum);
    }

    public static function findInvoiceNumBy($key, $val)
    {
        return Db::table('invoice_num')->where($key, $val)->first();
    }

    public static function findInvoiceNumByOrder($invoiceOrder)
    {
        return Db::table('invoice_num')->where('invoice_order', $invoiceOrder)->first();
    }

    public static function checkExistInvoiceOrder($invoice_order, $notID = 0) {
        if ($notID > 0) {
            return InvoiceTable::where('invoice_order', $invoice_order)->where('id', '!=', $notID)->first();
        }

        return InvoiceTable::where('invoice_order', $invoice_order)->first();
    }

    public static function checkExistExpressNO($expressNO, $notID = 0) {
        if ($notID > 0) {
            return InvoiceTable::where('invoice_kd', $expressNO)->where('id', '!=', $notID)->first();
        }

        return InvoiceTable::where('invoice_kd', $expressNO)->first();
    }

    public static function updateInvoiceNum($data, $where) {
        return DB::table("invoice_num")->where($where)->update($data);
    }

    public static function findSection($invoice_order)
    {
        return Db::table('invoice_part')
            ->where('section_start', '<=', $invoice_order)
            ->where('section_end', '>=', $invoice_order)
            ->select('section_start', 'section_end')
            ->first();
    }

    public static function updateInvoice($invoice_order, $company)
    {
        $section = self::findSection($invoice_order);
        if ($section) {
            Db::table('invoice_num')
                ->whereBetween('invoice_order', [$section['section_start'], $section['section_end']])
                ->update(['sys_company' => $company]);
            Db::table('invoice_part')
                ->where('section_start', '=', $section['section_start'])
                ->where('section_end', '=', $section['section_end'])
                ->update(['ass_company' => $company]);
            return true;
        }

        return false;
    }
}
