<?php

namespace App\Services\Api\MobileWeb;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\DB;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\CommonService;

// 账单列表
class BillingModuleService extends Model
{
    // 列表查询
    public static function index($request, $show_count = 10)
    {
        if (!isset($request['user_type'])) {
            $request['user_type'] = 1;
        }
        if ($request['type'] == 1) { //未出账单，查询gone_settlement_list
            // 查询列表
            $list_data = DB::table('settlement_list as seli')
                ->leftJoin('order_list as orli', 'orli.serial_number', '=', 'seli.serial_number')
                ->where('seli.ser_id', $request['admin_id']) //服务商id
                ->where('wat_num', '')
                ->where('seli.is_delete', 1)
                ->where('list_service_type', 5)
                ->whereIn('sett_status', [1, 60, 63])
                ->where(function ($query) use ($request) {
                    // 安装人员
                    if (!empty($request['install_id']) && $request['user_type'] == 1) {
                        $query->where('install_id', $request['install_id']);
                    }
                    // 业务来源id
                    if (!empty($request['p_id'])) {
                        $query->where('p_id', $request['p_id']);
                    }
                    // 状态
                    if (!empty($request['stauas'])) {
                        $query->where('stauas', $request['stauas']);
                    }
                    // 锁定状态
                    if (!empty($request['lock_state'])) {
                        $query->where('lock_state', $request['lock_state']);
                    }
                })
                ->where(function ($query) use ($request) { //创建时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($request['create_time_start']) && !empty($request['create_time_end'])) {
                        $query->whereBetween('create_time', [$request['create_time_start'], $request['create_time_end'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($request['create_time_start'])) {
                            $query->where('create_time', '>=', $request['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($request['create_time_end'])) {
                                $query->where('create_time', '<=', $request['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->select('seli.id', 'seli.order_num', 'seli.create_time', 'seli.sys_num', 'seli.serial_number', 'list_id', 'crma_id', 'orli.p_id', 'all_price')
                ->orderby('setfeeds_time', 'asc')
                ->paginate($show_count);
            $page['count'] = 0;
            $page['page'] = 0;
            $page['page_size'] = $show_count;
            $page['allPage'] = 0;
            $data['list'] = [];
            $data['page'] = $page;
            $list_items = $list_data->items();
            if ($list_items) {
                $list_items = objectToArray($list_items);
                $p_id = array_unique(array_column($list_items, 'p_id')); //来源id
                $crma_id = array_unique(array_column($list_items, 'crma_id')); //施工工艺id
                // 查询平台信息
                $find_pt_data = DB::table('pt')
                    ->whereIn('id', $p_id)
                    ->pluck('pt_name', 'id')->toArray();
                // 查询施工工艺信息
                $find_craft_data = DB::table('craft_manage')
                    ->whereIn('crma_id', $crma_id)
                    ->pluck('crma_name', 'crma_id')->toArray();
                foreach ($list_items as $key => $value) {
                    // 业务来源
                    if (isset($find_pt_data[$value['p_id']])) {
                        $list_items[$key]['pt_name'] = $find_pt_data[$value['p_id']];
                    } else {
                        $list_items[$key]['pt_name'] = '';
                    }
                    // 施工工艺
                    if (isset($find_craft_data[$value['crma_id']])) {
                        $list_items[$key]['crma_name'] = $find_craft_data[$value['crma_id']];
                    } else {
                        $list_items[$key]['crma_name'] = '';
                    }
                    $list_items[$key]['orders_vehicle'] = DB::table('orders_vehicle')
                        ->where('is_delete', 1)
                        ->where('sys_num', $value['sys_num'])
                        ->select('id', 'sys_num', 'vein_id', 'vein_name', 'vepo_id', 'vepo_name', 'vein_image')
                        ->get()->toArray();
                    unset($list_items[$key]['crma_id']);
                    unset($list_items[$key]['p_id']);
                }
                $page['count'] = $list_data->total(); //总数据个数
                $page['page'] = $list_data->currentPage(); //当前页面页码
                $page['page_size'] = $show_count; //一页显示多少个
                $page['allPage'] = $list_data->lastPage(); //表示最后一页的页码
                $data['list'] = $list_items;
                $data['page'] = $page;
            }
        } elseif ($request['type'] == 2) { //已出账单，查询gone_statements_list
            // 查询列表
            $list_data = DB::table('statements_list as stli')
                ->leftJoin('service_center as sece', 'sece.wat_num', '=', 'stli.stl_wat')
                ->leftJoin('company_data as com', 'stli.company_id', '=', 'com.cm_id')
                ->where('stl_serid', $request['admin_id']) //服务商id
                ->where('stl_type', '!=', 4) //服务商id
                ->where(function ($query) use ($request) {
                    // 状态
                    if (!empty($request['stauas'])) {
                        $query->where('stauas', $request['stauas']);
                    }
                    // 锁定状态
                    if (!empty($request['lock_state'])) {
                        $query->where('lock_state', $request['lock_state']);
                    }
                })
                ->where(function ($query) use ($request) { //创建时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($request['create_time_start']) && !empty($request['create_time_end'])) {
                        $query->whereBetween('create_time', [$request['create_time_start'], $request['create_time_end'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($request['create_time_start'])) {
                            $query->where('create_time', '>=', $request['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($request['create_time_end'])) {
                                $query->where('create_time', '<=', $request['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->select('stl_id', 'stl_wat', 'stl_startime', 'stl_endtime', 'stl_type', 'stl_money', 'stl_ticket', 'whether_inv', 'stl_invoice_number', 'stl_expressage_number', 'com.cm_name as company_name')
                ->orderby('stl_type', 'asc')
                ->orderby('stl_endtime', 'desc')
                ->paginate($show_count);//, 'invoice'
            $page['count'] = 0;
            $page['page'] = 0;
            $page['page_size'] = $show_count;
            $page['allPage'] = 0;
            $data['list'] = [];
            $data['page'] = $page;
            $list_items = $list_data->items();
            if ($list_items) {
                $list_items = objectToArray($list_items);
                $stl_wat = array_column($list_items, 'stl_wat');
                $pic_data = DB::table('pictures')
                    ->whereIn('sett_wat_num', $stl_wat)
                    ->pluck('upload_pictures', 'sett_wat_num')
                    ->toArray();
                $pic_data = objectToArray($pic_data);
                foreach ($list_items as $key => $value) {
                    if (isset($pic_data[$value['stl_wat']])) {
                        $list_items[$key]['upload_pictures'] = $pic_data[$value['stl_wat']];
                    } else {
                        $list_items[$key]['upload_pictures'] = '';
                    }
//                    if ($value['invoice'] == 3) { //发票1增票2普票3不开票
//                        $list_items[$key]['whether_inv'] = 3;
//                    }
                    if ($value['stl_type'] == 1) { //结算状态：1未结算（商家未确认）2结算中（商家已确认）3已结算４未处理
                        $list_items[$key]['stl_type_name'] = '未结算';
                    } elseif ($value['stl_type'] == 2) {
                        $list_items[$key]['stl_type_name'] = '结算中';
                    } elseif ($value['stl_type'] == 3) {
                        $list_items[$key]['stl_type_name'] = '已结算';
                    } elseif ($value['stl_type'] == 4) {
                        $list_items[$key]['stl_type_name'] = '未处理';
                    }
                    if ($value['whether_inv'] == 1) { //结算状态：1未结算（商家未确认）2结算中（商家已确认）3已结算４未处理
                        $list_items[$key]['whether_inv_name'] = '已收票';
                    } elseif ($value['whether_inv'] == 2) {
                        $list_items[$key]['whether_inv_name'] = '未开票';
                    } elseif ($value['whether_inv'] == 3) {
                        $list_items[$key]['whether_inv_name'] = '不开票';
                    }
                    if (empty($value['stl_invoice_number'])) { //结算状态：1未结算（商家未确认）2结算中（商家已确认）3已结算４未处理
                        $list_items[$key]['whether_inv_name'] = '未开票';
                        $list_items[$key]['whether_inv'] = 2;
                    } else {
                        $list_items[$key]['whether_inv_name'] = '已开票';
                        $list_items[$key]['whether_inv'] = 1;
                    }
                    unset($list_items[$key]['invoice']);
                }
                $page['count'] = $list_data->total(); //总数据个数
                $page['page'] = $list_data->currentPage(); //当前页面页码
                $page['page_size'] = $show_count; //一页显示多少个
                $page['allPage'] = $list_data->lastPage(); //表示最后一页的页码
                $data['list'] = $list_items;
                $data['page'] = $page;
            }
        }

        if ($data['list']) {
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $data];
        } else {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '暂无数据', 'Data' => $data];
        }
    }

    // 查看凭证
    public static function checkVoucher($request)
    {
        $find_upload_pictures = DB::table('pictures')
            ->where('sett_wat_num', $request['stl_wat'])
            ->value('upload_pictures');
        if ($find_upload_pictures) {
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $find_upload_pictures];
        } else {
            return ['ErrorCode' => 500, 'ErrorMessage' => '暂无数据', 'Data' => ''];
        }
    }

    // 查看详情
    public static function checkInfo($request)
    {
        $list_items = DB::table('settlement_list as seli')
            ->leftJoin('order_list as orli', 'orli.serial_number', '=', 'seli.serial_number')
            ->where('seli.ser_id', $request['admin_id']) //服务商id
            ->where('wat_num', $request['stl_wat'])
            // ->where('seli.is_delete', 1)
            ->select('orli.id', 'seli.order_num', 'seli.create_time', 'seli.sys_num', 'seli.serial_number', 'crma_id', 'all_price', 'orli.p_id')
            ->orderby('id', 'desc')
            ->get()->toArray();
        if ($list_items) {
            $list_items = objectToArray($list_items);
            $p_id = array_unique(array_column($list_items, 'p_id')); //来源id
            $crma_id = array_unique(array_column($list_items, 'crma_id')); //施工工艺id
            // 查询平台信息
            $find_pt_data = DB::table('pt')
                ->whereIn('id', $p_id)
                ->pluck('pt_name', 'id')->toArray();
            // 查询施工工艺信息
            $find_craft_data = DB::table('craft_manage')
                ->whereIn('crma_id', $crma_id)
                ->pluck('crma_name', 'crma_id')->toArray();
            foreach ($list_items as $key => $value) {
                // 业务来源
                if (isset($find_pt_data[$value['p_id']])) {
                    $list_items[$key]['pt_name'] = $find_pt_data[$value['p_id']];
                } else {
                    $list_items[$key]['pt_name'] = '';
                }
                // 施工工艺
                if (isset($find_craft_data[$value['crma_id']])) {
                    $list_items[$key]['crma_name'] = $find_craft_data[$value['crma_id']];
                } else {
                    $list_items[$key]['crma_name'] = '';
                }
                $list_items[$key]['orders_vehicle'] = DB::table('orders_vehicle')
                    ->where('is_delete', 1)
                    ->where('sys_num', $value['sys_num'])
                    ->select('id', 'sys_num', 'vein_id', 'vein_name', 'vepo_id', 'vepo_name', 'vein_image')
                    ->get()->toArray();
            }
            $data['list'] = $list_items;
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $data];
        } else {
            return ['ErrorCode' => 500, 'ErrorMessage' => '暂无数据', 'Data' => ''];
        }
    }

    // 确认账单
    public static function affirmBill($request,$ip)
    {
        $find_data = DB::table('statements_list')
            ->where('stl_id', $request['id'])
            ->first();
        $find_data = CommonService::dataToArray($find_data);
        $request['admin_id'] = $find_data['stl_serid'];
        $request['wat_num'] = $find_data['stl_wat'];
        // 查询成员账号表数据
        $find_adm_data = DB::table('admin')
            ->where('id', $request['admin_id'])
            ->select('company_name', 'admin_acc')
            ->first();
        $find_adm_data = CommonService::dataToArray($find_adm_data);
        // 查询结算单列表数据
        $find_stli_data = DB::table('statements_list')
            ->where('stl_wat', $request['wat_num']) //结算单号
            ->select('stl_money', 'stl_ticket', 'stl_type', 'stl_serid', 'stl_monthpay', 'company_id','stl_category')
            ->first();
        $find_stli_data = CommonService::dataToArray($find_stli_data);
        if ($find_stli_data['stl_type'] != 1) {
            return ['ErrorCode' => 500, 'ErrorMessage' => '只有未结算的单据可以点击确认账单', 'Data' => []];
        }
        // 服务商账单金额明细（服务中心账目管理数据）
        $add_sece_data['wat_num'] = $request['wat_num']; //结算流水号
        $add_sece_data['ser_id'] = $request['admin_id']; //服务中心
        $add_sece_data['company_name'] = $find_adm_data['company_name']; //结算对象名称
        $add_sece_data['apply_for_name'] = $find_adm_data['admin_acc']; //申请人
        $add_sece_data['apply_for_money'] = $find_stli_data['stl_money'] - $find_stli_data['stl_ticket']; //申请金额 = 结算单金额 - 执行罚款金额
        $add_sece_data['apply_for_time'] = date('Y-m-d H:i:s'); //申请时间
        $settlement_num = '';
        if (Request::filled('settlement_num')) {
            $settlement_num = $request['settlement_num'];
        }
        $add_sece_data['settlement_num'] = $settlement_num;
        $add_sece_data['company_id'] = $find_stli_data['company_id'];
        $add_sece_data['stl_category'] = $find_stli_data['stl_category']; //1月结2零散3周结
//        $user_info = CommonService::webgetUserInfo($request['api_token']);

        // 查询工单结算表数据
        $find_seli_data = DB::table('settlement_list')
            ->where('wat_num', $request['wat_num'])
            ->select('list_id')
            ->get()->toArray();
        $serial_number = array_column($find_seli_data, 'list_id');

        DB::beginTransaction();
        // 新增服务商账单金额明细（服务中心账目管理数据）
        $add_sece_id = DB::table('service_center')->insert($add_sece_data);
        // 工单结算表
        $edit_seli_data['sett_status'] = 20; //工单结算状态：1未审核10未结算20结算中30已完成40作废50已追回
        // 更改服务工单结算表
        $edit_seli_res = DB::table('settlement_list')
            ->where('wat_num', $request['wat_num'])
            ->update($edit_seli_data);

        // 结算单列表（账单表->账单报表数据）
        $edit_stli_data['stl_type'] = 2; //结算状态1：未结算（商家未确认）；2：结算中（商家已确认）；3：已结算　４:未处理 5:待发货
        // 更改结算单列表（账单表->账单报表数据）
        $edit_stli_res = DB::table('statements_list')
            ->where('stl_wat', $request['wat_num'])
            ->update($edit_stli_data);

        // 更改服务工单列表
        $edit_orli_data["account_status"] = 20;
        CommonService::startmysql();
        $edit_orli_res = DB::table('order_list')
            ->whereIn('serial_number', $serial_number)
            ->update($edit_orli_data);
        CommonService::addLog('获取订单', CommonService::showmysql(), $request['wat_num'],'affirmBill-web');
        if ($add_sece_id && $edit_seli_res && $edit_stli_res && $edit_orli_res) {
            $session = $request['session'];
            CommonService::inserting_log('确认账单，',$request['wat_num'].'--'.$add_sece_id,'确认账单','账单管理web',$session,$ip);//日志
            DB::commit();
            // czrzLog("确认账单", $request['wat_num'], "移动端确认账单", "账单管理", request::ip(), $user_info->install_name);
            return ['ErrorCode' => 1, 'ErrorMessage' => '确认账单成功', 'Data' => []];
        } else {
            DB::rollback();
            return ['ErrorCode' => 500, 'ErrorMessage' => '失败', 'Data' => [$add_sece_id,$edit_seli_res,$edit_stli_res,$edit_orli_res]];
        }
    }

    // 上传发票
    public static function uploadInvoice($request)
    {
        // 查询结算单列表（账单表->账单报表数据）是否有单号
        $find_stli_data = DB::table('statements_list')
            ->where('stl_wat', $request['wat_num'])
            ->select('stl_invoice_number', 'stl_expressage_number')
            ->first();
        $find_stli_data = objectToArray($find_stli_data);
        if (!empty($find_stli_data['stl_invoice_number']) && !empty($find_stli_data['stl_expressage_number'])) {
            return ['ErrorCode' => 1, 'ErrorMessage' => $find_stli_data, 'Data' => []];
        } else {
            if (empty($request['stl_invoice_number']) || empty($request['stl_expressage_number'])) {
                return ['ErrorCode' => ErrorInc::INVALID_PARAM, 'ErrorMessage' => '请输入发票单号和快递单号', 'Data' => []];
            }
            $edit_stli_data['stl_invoice_number'] = $request['stl_invoice_number']; //发票单号
            $edit_stli_data['stl_expressage_number'] = $request['stl_expressage_number']; //快递单号
            $edit_stli_res = DB::table('statements_list')
                ->where('stl_wat', $request['wat_num'])
                ->update($edit_stli_data);
            if ($edit_stli_res) {
                return ['ErrorCode' => 1, 'ErrorMessage' => $edit_stli_data, 'Data' => []];
            } else {
                return ['ErrorCode' => 500, 'ErrorMessage' => '失败', 'Data' => []];
            }
        }
    }
}
