<?php
namespace App\Http\Controllers\Api\SystemsManage;

use Illuminate\Http\Request;
use App\Http\Models\Api\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\SystemsManage\VerifyPerformanceController;
use App\Http\Models\Api\Export;

// 财务系统 -- 业绩明细
class PerformanceController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;
    // wor_state 工单状态8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止 12锁定13.速电撤销回收14工单冲单
    protected $search_wor_state = [8,9,10,11];//搜索的工单状态
    // 工单类型：1系统工单2外派工单3速电派单4虚拟加盟店
    protected $search_wocl_wor_type = [1,2,3];

    // 列表(派单时间没有  查询出来的是所有的工单信息)
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyPerformanceController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $list_data = DB::table('work_order as wo')
            ->leftjoin('work_client as wc', 'wc.wocl_wor_id', '=', 'wo.wor_id')
            ->where('wor_cid', $user_info->adm_cid)
            ->where('wor_shop_id', $user_info->adm_shop_id)
            ->where('wor_delete', 1)
            ->where('wor_collection_bill', 1)
            ->whereIn('wor_state', $this->search_wor_state)
            ->whereIn('wocl_wor_type', $this->search_wocl_wor_type)
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['achieve_start_time']) && !empty($search_data['achieve_end_time'])) {
                    $query->whereBetween('wor_achieve_time', [$search_data['achieve_start_time'],$search_data['achieve_end_time'].' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['achieve_start_time'])) {
                        $query->where('wor_achieve_time', '>=', $search_data['achieve_start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['achieve_end_time'])) {
                            $query->where('wor_achieve_time', '<=', $search_data['achieve_end_time'].' 23:59:59');
                        }
                    }
                }
            }) //完成时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_shop_id'])) {
                    $query->where('wor_service_shop_id', $search_data['wor_service_shop_id']);
                }
            }) //门店名称
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_adm_id'])) {
                    $query->where('wor_service_adm_id', $search_data['wor_service_adm_id']);
                }
            }) //技师姓名
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_type'])) {
                    $query->where('wor_service_type', $search_data['wor_service_type']);
                }
            }) //服务类型
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_sepr_id'])) {
                    $query->where('wor_service_sepr_id', $search_data['wor_service_sepr_id']);
                }
            }) //服务项目
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_state'])) {
                    $query->where('wor_state', $search_data['wor_state']);
                }
            }) //状态
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_number'])) {
                    $query->where('wor_number', 'like', '%'.$search_data['wor_number'] . '%')
                    ->orWhere('wor_order_number', 'like', '%'.$search_data['wor_number'] . '%');
                }
            }) //工单号
            ->select('wor_id', 'wor_number', 'wor_order_number', 'wor_achieve_time', 'wor_goo_amount', 'wor_actual_price', 'wor_service_type', 'wor_service_sepr_id', 'wor_service_shop_id', 'wor_service_adm_id', 'wor_state', 'wor_create_time', 'wor_plus_minus','wocl_wor_type')
            ->orderBy('wor_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                $wor_id[] = $value->wor_id;
                $service_sepr_id[] = $value->wor_service_sepr_id;
                $service_shop_id[] = $value->wor_service_shop_id;
                $service_adm_id[] = $value->wor_service_adm_id;
            }
            $wor_id = array_unique($wor_id);
            $service_sepr_id = array_unique($service_sepr_id);
            $service_shop_id = array_unique($service_shop_id);
            $service_adm_id = array_unique($service_adm_id);

            // 追加客户单位
            $client = DB::table('work_client')
                ->whereIn('wocl_wor_id', $wor_id)
                ->select('wocl_wor_id', 'wocl_channel_unit')
                ->get();

            // 追加服务项目,服务项目金额
            $service_sepr = DB::table('service_project')
                ->whereIn('sepr_id', $service_sepr_id)
                ->select('sepr_id', 'sepr_name', 'sepr_money')
                ->get();
            // 追加门店名称
            $service_shop = DB::table('shop')
                ->whereIn('shop_id', $service_shop_id)
                ->select('shop_id', 'shop_store_name')
                ->get();
            // 追加技师姓名 技师联系电话
            $service_adm = DB::table('admin')
                ->whereIn('adm_id', $service_adm_id)
                ->select('adm_id', 'adm_name', 'adm_phone')
                ->get();
        } else {
            $client = [];
            $service_sepr = [];
            $service_shop = [];
            $service_adm = [];
        }

        // 统计业绩提成总额
        $amount = DB::table('work_order as wo')
            ->leftjoin('work_client as wc', 'wc.wocl_wor_id', '=', 'wo.wor_id')
            ->leftjoin('service_project as sepr', 'sepr.sepr_id', '=', 'wo.wor_service_sepr_id')
            ->where('wor_cid', $user_info->adm_cid)
            ->where('wor_shop_id', $user_info->adm_shop_id)
            ->where('wor_delete', 1)
            ->where('wor_collection_bill', 1)
            ->whereIn('wor_state', $this->search_wor_state)
            ->whereIn('wocl_wor_type', $this->search_wocl_wor_type)
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['achieve_start_time']) && !empty($search_data['achieve_end_time'])) {
                    $query->whereBetween('wor_achieve_time', [$search_data['achieve_start_time'],$search_data['achieve_end_time'].' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['achieve_start_time'])) {
                        $query->where('wor_achieve_time', '>=', $search_data['achieve_start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['achieve_end_time'])) {
                            $query->where('wor_achieve_time', '<=', $search_data['achieve_end_time'].' 23:59:59');
                        }
                    }
                }
            }) //完成时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_shop_id'])) {
                    $query->where('wor_service_shop_id', $search_data['wor_service_shop_id']);
                }
            }) //门店名称
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_adm_id'])) {
                    $query->where('wor_service_adm_id', $search_data['wor_service_adm_id']);
                }
            }) //技师姓名
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_type'])) {
                    $query->where('wor_service_type', $search_data['wor_service_type']);
                }
            }) //服务类型
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_sepr_id'])) {
                    $query->where('wor_service_sepr_id', $search_data['wor_service_sepr_id']);
                }
            }) //服务项目
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_state'])) {
                    $query->where('wor_state', $search_data['wor_state']);
                }
            }) //状态
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_number'])) {
                    $query->where('wor_number', 'like', '%'.$search_data['wor_number'] . '%')
                    ->orWhere('wor_order_number', 'like', '%'.$search_data['wor_number'] . '%');
                }
            }) //工单号
            ->select(DB::raw('sum(sepr_money) as sepr_money,count(wor_id) as achieve_amount'))
            ->first();

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据
        $data_info['client'] = $client;                //客户单位信息
        $data_info['service_sepr'] = $service_sepr;                //服务项目信息
        $data_info['service_shop'] = $service_shop;                //门店信息
        $data_info['service_adm'] = $service_adm;                //技师信息
        $data_info['amount'] = $amount->sepr_money;                //业绩提成总额
        $data_info['achieve_amount'] = $amount->achieve_amount;//完成工单总量

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据', 'list_button'=>$list_button]);
        }
    }

    // 导出
    public function export(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $data = DB::table('work_order as wor')
            ->leftJoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->leftjoin('admin as adm', 'adm.adm_id', '=', 'wor.wor_service_adm_id')
            ->leftjoin('shop as shop', 'shop.shop_id', '=', 'wor.wor_service_shop_id')
            ->leftjoin('service_project as sepr', 'sepr.sepr_id', '=', 'wor.wor_service_sepr_id')
            ->where('wor_cid', $user_info->adm_cid)
            ->where('wor_shop_id', $user_info->adm_shop_id)
            ->where('wor_delete', 1)
            ->where('wor_collection_bill', 1)
            ->whereIn('wor_state', $this->search_wor_state)
            ->whereIn('wocl_wor_type', $this->search_wocl_wor_type)
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['achieve_start_time']) && !empty($search_data['achieve_end_time'])) {
                    $query->whereBetween('wor_achieve_time', [$search_data['achieve_start_time'],$search_data['achieve_end_time'].' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['achieve_start_time'])) {
                        $query->where('wor_achieve_time', '>=', $search_data['achieve_start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['achieve_end_time'])) {
                            $query->where('wor_achieve_time', '<=', $search_data['achieve_end_time'].' 23:59:59');
                        }
                    }
                }
            }) //完成时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_shop_id'])) {
                    $query->where('wor_service_shop_id', $search_data['wor_service_shop_id']);
                }
            }) //门店名称
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_adm_id'])) {
                    $query->where('wor_service_adm_id', $search_data['wor_service_adm_id']);
                }
            }) //技师姓名
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_type'])) {
                    $query->where('wor_service_type', $search_data['wor_service_type']);
                }
            }) //服务类型
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_service_sepr_id'])) {
                    $query->where('wor_service_sepr_id', $search_data['wor_service_sepr_id']);
                }
            }) //服务项目
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_state'])) {
                    $query->where('wor_state', $search_data['wor_state']);
                }
            }) //状态
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['wor_number'])) {
                    $query->where('wor_number', 'like', '%'.$search_data['wor_number'] . '%')
                    ->orWhere('wor_order_number', 'like', '%'.$search_data['wor_number'] . '%');
                }
            }) //工单号
            ->select('wor_number', 'wor_order_number', 'shop_store_name', 'wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wor_achieve_time', 'wor_goo_amount', 'wor_actual_price', 'wor_service_type', 'sepr_name', 'sepr_money', 'wor_state', 'adm_name', 'adm_phone', 'wor_plus_minus', 'wocl_client_id','wocl_wor_type')
            ->orderBy('wor_id', 'desc')
            ->get()->toArray();
        if (!empty($data)) {
            // 将对象转化为数组
            $data = json_decode(json_encode($data), true);
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->where('chun_shop_id', $user_info->adm_shop_id)
                ->where('chun_state', '1')
                ->select('chun_id', 'chun_unit_name')
                ->get();
            $channel = json_decode(json_encode($channel), true);
            foreach ($channel as $k => $v) {
                $channel_name[$v['chun_id']] = $v['chun_unit_name'];
            }
            foreach ($data as $key => $value) {
                if ($value['wor_service_type'] == 4) {
                    $data[$key]['wor_actual_price'] = '-' . $value['wor_actual_price'] / 100;
                } else {
                    $data[$key]['wor_actual_price'] = $value['wor_actual_price'] / 100;
                }
                //服务项目金额
                $data[$key]['sepr_money'] = $value['sepr_money'] / 100;
                // 服务类型
                if ($value['wor_service_type'] == '1') {
                    $data[$key]['wor_service_type'] = '服务单';
                }
                if ($value['wor_service_type'] == '2') {
                    $data[$key]['wor_service_type'] = '销售单';
                }
                if ($value['wor_service_type'] == '3') {
                    $data[$key]['wor_service_type'] = '换货单';
                }
                if ($value['wor_service_type'] == '4') {
                    $data[$key]['wor_service_type'] = '退货单';
                }
                if ($value['wor_service_type'] == '5') {
                    $data[$key]['wor_service_type'] = '发货单';
                }
                if ($value['wor_service_type'] == '6') {
                    $data[$key]['wor_service_type'] = '结清单';
                }
                if ($value['wor_service_type'] == '7') {
                    $data[$key]['wor_service_type'] = '救援单';
                }
                // 审核状态
                if ($value['wor_state'] == 1) {
                    $data[$key]['wor_state'] = '新订单';
                }
                if ($value['wor_state'] == 2) {
                    $data[$key]['wor_state'] = '未派单';
                }
                if ($value['wor_state'] == 3) {
                    $data[$key]['wor_state'] = '待接单/已派单';
                }
                if ($value['wor_state'] == 4) {
                    $data[$key]['wor_state'] = '未出发/已接单';
                }
                if ($value['wor_state'] == 5) {
                    $data[$key]['wor_state'] = '预约/已预约';
                }
                if ($value['wor_state'] == 6) {
                    $data[$key]['wor_state'] = '出发/已出发';
                }
                if ($value['wor_state'] == 7) {
                    $data[$key]['wor_state'] = '抵达';
                }
                if ($value['wor_state'] == 8) {
                    $data[$key]['wor_state'] = '完成待审核';
                }
                if ($value['wor_state'] == 9) {
                    $data[$key]['wor_state'] = '驳回/完成已驳回';
                }
                if ($value['wor_state'] == 10) {
                    $data[$key]['wor_state'] = '完成已通过';
                }
                if ($value['wor_state'] == 11) {
                    $data[$key]['wor_state'] = '终止';
                }
                if ($value['wor_state'] == 12) {
                    $data[$key]['wor_state'] = '锁定';
                }
                if ($value['wor_state'] == 13) {
                    $data[$key]['wor_state'] = '速电撤销回收';
                }
                // 客户单位名称
                if (isset($channel_name[$value['wocl_client_id']])) {
                    $data[$key]['wocl_channel_unit'] = $channel_name[$value['wocl_client_id']];
                } else {
                    if ($data[$key]['wocl_wor_type'] == 3) {
                        $data[$key]['wocl_channel_unit'] = '速电快保';
                    } else {
                        $data[$key]['wocl_channel_unit'] = '';
                    }
                }
                unset($data[$key]['wor_plus_minus']);
                unset($data[$key]['wocl_client_id']);
                unset($data[$key]['wocl_wor_type']);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'没有符合条件的数据']);
        }

        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }
        $streamFileRand = '业绩明细' . time() . rand(1000, 9999) . '业绩明细.xls';
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' . $streamFileRand;
        $where['action_name'] = '业绩明细';
        $where['field_name'] = ['工单单号', '订单单号', '门店名称', '客户单位', '客户姓名', '客户电话', '完成时间', '商品数量', '工单金额', '订单类型', '服务项目', '金额', '状态', '技师姓名', '联系电话'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($pathName)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }
}
