<?php

namespace App\Services\AfterOrder;

use App\Services\Business\WashOrderBasicService;
use App\Services\Business\WashOrderService;
use App\Services\CommonService;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;


class AfterOrderService extends Service
{

    /**
     * 获取售后进度状态
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-10
     * @param  boolean          $type [description]
     * @return [type]                 [description]
     */
    public static function getStateName($type=false){
        //状态1处理中2待审核3驳回4已完成
        $data = [['type'=>0,'name'=>'日常反馈'],['type'=>1,'name'=>'处理中'],['type'=>2,'name'=>'已完成'],['type'=>3,'name'=>'已驳回'],['type'=>4,'name'=>'已完成'],['type'=>5,'name'=>'已撤销']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param string $type 服务类型数据
     * @param string $typeName 服务类型数据
     * @retrun /multitype:array
     * @author dou 2023-05-31 031 上午 11:47:59
     * |---------------------------------------------------------------------------------
     */
    public static function getTypeData ( $type , $typeName ){
        $typeData = trim($type);
        $typeData = explode(',', $typeData);
        $return = [];

        foreach($typeData as $k => $v){
            $return[] = $typeName[$v]??'未定义';
        }
        $return = implode(',', $return);
        return $return;
    }
   /*
    * @name 退货进度
    * @retrun array
    * @author Ma 2023/9/12 15:49
    *
   */
    public static function getReturnName($type){
        $data = [['id'=>0,'name'=>'--'],['id'=>1,'name'=>'未回收'],['id'=>2,'name'=>'部分回收'],['id'=>3,'name'=>'已回收'],['id'=>4,'name'=>'供货商回收']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    /*
     * @name 退款方式
     * @retrun array
     * @author Ma 2023/9/12 15:49
     *
    */
    public static function getRefundMethodName($type){
        $data = [['id'=>0,'name'=>'--'],['id'=>1,'name'=>'线下打款'],['id'=>2,'name'=>'原账号退回']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    /*
     * @name 退款状态
     * @retrun array
     * @author Ma 2023/9/12 15:49
     *
    */
    public static function getRefundStatusName($type){
        $data = [['id'=>0,'name'=>'--'],['id'=>1,'name'=>'未退款'],['id'=>2,'name'=>'已退款']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    /*
     * @name 退款审核状态
     * @retrun array
     * @author Ma 2023/9/12 15:49
     *
    */
    public static function getStatusName($type){
        $data = [['id'=>0,'name'=>'全部'],['id'=>1,'name'=>'待审核'],['id'=>2,'name'=>'通过'],['id'=>3,'name'=>'驳回']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    //列表
    public static function index($user_info, $request){
        $shop_id = $user_info->adm_shop_id;
        $list_data = DB::table('after_work_log as a')
            ->leftjoin('wash_after_sale_list as wa', 'wa.afsl_id', '=', 'a.awlo_afsl_id')
            ->leftjoin('wash_after_sale_client as w', 'w.afsc_afsl_id', '=', 'wa.afsl_id')
            ->where('afsl_shop_id',$user_info->adm_shop_id)
            ->where('awlo_adm_del',2)
            ->where('awlo_adm_type',2)
            ->where('awlo_type',2)
            ->where('awlo_adm_id',$user_info->adm_id)
            ->where(function ($query) use ($request) {
                if (!empty($request['keywords'])) {
                    $query->where('afsl_after_number', 'like', '%' . $request['keywords'] . '%');
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['awlo_state'])) {
                    if ($request['awlo_state'] == 1) {//状态1处理中2待审核3驳回4已完成
                        $query->whereIn('awlo_state', [1]);
                    }
                    if ($request['awlo_state'] == 2) {//处理中 包含1处理中 2审核中
                        $query->whereIn('awlo_state', [2,4]);
                    }
                } else {
                    $query->whereIn('awlo_state', [1,2,4]);
                }
            })
            ->select('afsc_client_id', 'afsc_name', 'afsc_phone', 'afsc_car_num', 'afsc_car_brand_series', 'afsl_remark', 'awlo_state', 'awlo_id', 'afsl_after_number')
            ->orderBy('awlo_id', 'desc')
            ->paginate(10);
        $list = $list_data->items();
        // 获取当前列表下的按钮
        $list_button = getAppletListButton($request['api_token'], $request['pri_id']);

        if ($list) {
            $typeName = self::getStateName(true);//获取支付方式名称
            foreach ($list as $key => $value) {//return [$value->retgo_id];
                if (!empty($value->awlo_state)) {
                    $list[$key]->awlo_state_name = self::getTypeData($value->awlo_state, $typeName);
                } else {
                    $list[$key]->awlo_state_name = '';
                }
                $buttonData = [];
                if ($value->awlo_state == 1) {
                    $buttonData[] = 'dealwith';
                }
                $button = CommonService::getAppletListButton($buttonData,$list_button);
                $list[$key]->button_one = $button['button_one']??[];
                $list[$key]->button_two = $button['button_two']??[];
                $list[$key]->button_three = $button['button_three']??[];
            }
        }
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = 10;        //一页显示多少个
        $data['data'] = $list;                              //返回数据

        return ['code'=>200, 'msg'=>'success', 'data'=>$data];
    }

    /**
     * 售后单详情
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-11
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function info($user_info,$request){
        $list_data = DB::table('after_work_log as a')
            ->leftjoin('wash_after_sale_list as wa', 'wa.afsl_id', '=', 'a.awlo_afsl_id')
            ->leftjoin('wash_after_sale_client as w', 'w.afsc_afsl_id', '=', 'wa.afsl_id')
            ->where('awlo_id',$request['awlo_id'])
            ->select('afsc_client_id', 'afsc_name', 'afsc_phone', 'afsc_car_num', 'afsc_car_brand_series', 'afsl_remark', 'awlo_state', 'awlo_id', 'afsl_pic', 'afsl_id', 'afsl_ware_id', 'awlo_pic_data', 'afsl_parts')
            ->first();
        // 获取当前列表下的按钮
        $list_button = getAppletListButton($request['api_token'], $request['pri_id']);
        $buttonData = [];
        if ($list_data->awlo_state == 1) {
            $buttonData[] = 'dealwith';
        }
        $list_data->adm_data = DB::table('after_work_log as a')
            ->leftjoin('admin', 'adm_id', '=', 'awlo_adm_id')
            ->where('awlo_afsl_id',$list_data->afsl_id)
            ->where('awlo_adm_del', 2)
            ->where('awlo_adm_type', 2)
            ->select('awlo_id', 'awlo_adm_name', 'awlo_text', 'awlo_create_name', 'awlo_pic_data', 'awlo_work_parts', 'adm_phone')
            ->groupBy('awlo_adm_id')
            ->get()->toArray();
        $list_data->work_log = DB::table('after_work_log as a')
            ->where('awlo_afsl_id',$list_data->afsl_id)
            ->select('awlo_id', 'awlo_adm_name', 'awlo_text', 'awlo_create_name', 'awlo_pic_data', 'awlo_work_parts', 'awlo_adm_type', 'awlo_reject_reason')
            ->orderBy('awlo_create_time', 'desc')
            ->get()->toArray();
        $goods_data = DB::table('wash_after_sale_items')
            ->where('afsi_type', 2)
            ->where('afsi_afsl_id', $list_data->afsl_id)
            ->get()->toArray();
        $list_data->goods_data = $goods_data;
        $list_data->shipment = '';
        if ($goods_data && $list_data->afsl_ware_id) {
            $dis_data = DB::table('dispatch_bill')
                ->where('dego_order_type', 3)
                ->where('dego_wor_id', $list_data->afsl_id)
                ->first();
            if ($dis_data) {
                if ($dis_data->dego_type == 2) {
                    $list_data->shipment = 1;
                } else {
                    $list_data->shipment = 2;
                }
            }
        }
        $typeName = self::getStateName(true);//获取支付方式名称
        if (!empty($list_data->awlo_state)) {
            $list_data->awlo_state_name = self::getTypeData($list_data->awlo_state, $typeName);
        } else {
            $list_data->awlo_state_name = '';
        }
        $button = CommonService::getAppletListButton($buttonData,$list_button);
        $list_data->button_one = $button['button_one']??[];
        $list_data->button_two = $button['button_two']??[];
        $list_data->button_three = $button['button_three']??[];
        if ($list_data) {
            return ['code'=>200, 'msg'=>'success', 'data'=>$list_data];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>''];
        }
    }

    /**
     * 处理售后
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-10
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function dealwith($user_info, $request) {
        // 查询信息
        $find_data = DB::table('after_work_log')
            ->where('awlo_id', $request['awlo_id'])
            ->select('awlo_state', 'awlo_afsl_id')
            ->first();

        if (empty($find_data)) {
            return ['code'=>ErrorInc::REQUEST_INAPTNESS, 'msg'=>'当前售后单不存在！', 'data'=>''];
        }
        if ($find_data->awlo_state != 1) {
            return ['code'=>ErrorInc::REQUEST_INAPTNESS, 'msg'=>'当前售后单不是未处理状态！', 'data'=>''];
        }
        // 提交处理记录
        $new_work_data['awlo_shop_id'] = $user_info->adm_shop_id;
        $new_work_data['awlo_afsl_id'] = $find_data->awlo_afsl_id;
        $new_work_data['awlo_text'] = $request['awlo_text'];
        $new_work_data['awlo_pic_data'] = json_encode($request['awlo_pic_data'], true);
        $new_work_data['awlo_adm_id'] = $user_info->adm_id;
        $new_work_data['awlo_adm_name'] = $user_info->adm_name;
        $new_work_data['awlo_state'] = 0;//1未处理2处理中3审核中4已完成
        $new_work_data['awlo_adm_type'] = 2;//1后台人员2指派技师
        $new_work_data['awlo_create_id'] = $user_info->adm_id;
        $new_work_data['awlo_create_name'] = $user_info->adm_name;
        $new_work_data['awlo_type'] = 1;//1日常反馈2提交售后
        $new_work_data['awlo_create_time'] = date('Y-m-d H:i:s');
        $add_work_data_res = DB::table('after_work_log')->insert($new_work_data);
        
        if ($add_work_data_res) {
            return ['code'=>200, 'msg'=>'提交成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'提交失败', 'data'=>''];
        }
    }

    /**
     * 处理售后
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-10
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function complete($user_info, $request) {
        // 查询信息
        $find_data = DB::table('after_work_log')
            ->where('awlo_id', $request['awlo_id'])
            ->select('awlo_state', 'awlo_afsl_id')
            ->first();

        if (empty($find_data)) {
            return ['code'=>ErrorInc::REQUEST_INAPTNESS, 'msg'=>'当前售后单不存在！', 'data'=>''];
        }
        if ($find_data->awlo_state != 1) {
            return ['code'=>ErrorInc::REQUEST_INAPTNESS, 'msg'=>'当前售后单不是未处理状态！', 'data'=>''];
        }
        $find_dis = DB::table('dispatch_bill')
            ->whereIn('dego_type', [1,2])
            ->where('dego_order_type', 3)
            ->where('dego_wor_id', $find_data->awlo_afsl_id)
            ->select('dego_type')
            ->first();
        if ($find_dis) {
            if ($find_dis->dego_type == 2) {//已出库
                # code...
            } else {
                return ['code'=>500, 'msg'=>'请先取货', 'data'=>''];
            }
        }
        $update_data['awlo_pic_data'] = json_encode($request['awlo_pic_data'], true);
        $update_data['awlo_work_parts'] = json_encode($request['awlo_work_parts'], true);
        $update_data['awlo_state'] = 2;
        $update_data['awlo_text'] = $request['awlo_text'];
        $update_data['awlo_update_id'] = $user_info->adm_id;
        $update_data['awlo_update_name'] = $user_info->adm_name;
        $update_data['awlo_create_time'] = date('Y-m-d H:i:s');
        $update_data['awlo_update_time'] = date('Y-m-d H:i:s');
        $update_res = DB::table('after_work_log')
            ->where('awlo_id', $request['awlo_id'])
            ->update($update_data);
        $uncomplete_data = DB::table('after_work_log')
            ->where('awlo_state', 1)
            ->exists();
        if (!$uncomplete_data) {
            $update['afsl_state'] = 3;
            $update_res = DB::table('wash_after_sale_list')
                ->where('awlo_id', $find_data->awlo_afsl_id)
                ->update($update);
        }
        if ($update_res) {
            return ['code'=>200, 'msg'=>'提交成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'提交失败', 'data'=>''];
        }
    }
}

