<?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\Api\Common\{CommonService};

// 评价列表
class ServiceEvaluationService extends Model
{
    // 列表查询
    public static function index($request, $show_count = 10)
    {
        // 查询列表 
        $list_data = DB::table('evaluation_form as evfo')
            ->leftJoin('order_list as orli', 'orli.order_num', '=', 'evfo.plat_number')
            ->where('evfo.ser_id', $request['admin_id']) //服务商id
            ->where('orli.is_delete', 1)
            ->select('serial_number', 'eval_leval', 'eval_content', 'eval_content_show', 'eval_time', 'evfo_score', 'eval_sety_id', 'eval_parent_sety_id', 'eval_grandparent_sety_id', 'eval_label')
            ->orderby('eval_time', 'desc')
            ->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);
            $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;
        }

        // 查询好评统计数据
        $good_reputation_count = DB::table('evaluation_form')
            ->where('ser_id', $request['admin_id']) //服务商id
            ->where('eval_parent_sety_id',  701)
            ->select(DB::raw('count(*) as count, eval_parent_sety_id'))
            ->groupBy('eval_parent_sety_id')
            ->get()->toArray();
        $data['good_reputation_count'] = $good_reputation_count;
        // 查询差评统计数据
        $good_negative_comment_count = DB::table('evaluation_form')
            ->where('ser_id', $request['admin_id']) //服务商id
            ->where('eval_parent_sety_id', 704)
            ->select(DB::raw('count(*) as count, eval_parent_sety_id'))
            ->groupBy('eval_parent_sety_id')
            ->get()->toArray();
        $data['good_negative_comment_count'] = $good_negative_comment_count;
        $data['comprehensive_evaluation'] = 98; //综合评分
        $data['service_score'] = 95; //服务评分
        $data['compare_evaluation'] = 95; //与行业相比
        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.list_id')
            ->where('seli.ser_id', $request['admin_id']) //服务商id
            ->where('wat_num', $request['stl_wat'])
            ->where('is_delete', 1)
            ->select('seli.id', 'seli.order_num', 'seli.create_time', 'seli.sys_num', 'list_id', 'crma_id', 'orli_actual_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)
    {
        // 查询成员账号表数据
        $find_adm_data = DB::table('admin')
            ->where('id', $request['admin_id'])
            ->select('company_name', 'admin_acc')
            ->first();
        $find_adm_data = objectToArray($find_adm_data);
        // 查询结算单列表数据
        $find_stli_data = DB::table('statements_list')
            ->where('stl_wat', $request['wat_num']) //结算单号
            ->select('stl_money', 'stl_ticket', 'stl_type')
            ->first();
        $find_stli_data = objectToArray($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;

        // 工单结算表
        $edit_seli_data['sett_status'] = 20; //工单结算状态1:未审核；10：未结算；20：结算中；30：已完成；40：作废;50:已追回

        // 结算单列表（账单表->账单报表数据）
        $edit_stli_data['stl_type'] = 2; //结算状态1：未结算（商家未确认）；2：结算中（商家已确认）；3：已结算　４:未处理 5:待发货

        // 查询工单结算表数据
        $find_seli_data = DB::table('settlement_list')
            ->where('wat_num', $request['wat_num'])
            ->select('list_id')
            ->get()->toArray();
        $find_seli_data = objectToArray($find_seli_data);
        $list_id = "";
        foreach ($find_seli_data as $k => $v) {
            $list_id .= ",'" . $v['list_id'] . "'";
        }
        $list_id = ltrim($list_id, ',');
        $edit_orli_data["account_status"] = 20;

        $user_info = CommonService::webgetUserInfo($request['api_token']);

        DB::beginTransaction();

        // 新增服务商账单金额明细（服务中心账目管理数据）
        $add_sece_id = DB::table('service_center')->insert($add_sece_data);
        // 更改服务工单结算表
        $edit_seli_res = DB::table('settlement_list')
            ->where('wat_num', $request['wat_num'])
            ->update($edit_seli_data);
        // 更改结算单列表（账单表->账单报表数据）
        $edit_stli_res = DB::table('statements_list')
            ->where('stl_wat', $request['wat_num'])
            ->update($edit_stli_data);
        // 更改服务工单列表
        $edit_orli_res = DB::table('order_list')
            ->whereRaw("serial_number in (" . $list_id . ")")
            ->update($edit_orli_data);
        if ($add_sece_id && $edit_seli_res && $edit_stli_res && $edit_orli_res) {
            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' => []];
        }
    }

    // 上传发票
    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' => []];
            }
        }
    }
}
