<?php

/**
|--------------------------------------------------------------------------
 * 售后服务
|--------------------------------------------------------------------------
| 售后服务处理逻辑
 * @author DouBin
 * @Date: 2021/08/05
 * @Time: 上午 10:16
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Services;
use App\Models\Admin;
use App\Models\PtPrice;
use App\Models\SettlementThree;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use DB;

class SettlementThreeService extends Service{

    /**|---------------------------------------------------------------------------------
     * @name 根据指定条件获取结算单数据
     * @param string $key 键
     * @param string $value 值
     * @param array $select 待查询参数
     * @param string $type 待查询参数
     * @retrun multitype:array
     * @author dou 2021/8/9 23:21
     * |---------------------------------------------------------------------------------
    */
    public static function getSettlementThreeBy ( $key , $value , $select = [] , $type = 'get' ){
        $db = new SettlementThree();
        if(in_array($key, ['id','list_id'])){
            $type = 'first';
        }
        if( $type == 'first' && count($select) == 1){
            $type = 'value';
        }
        $list = CommonService::getMysqlData($db, [$key=>$value],$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取列表信息
     * @param array $input 请求参数
     * @param array $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/9/13 18:32
     * |---------------------------------------------------------------------------------
    */
    public static function getList ( $input , $session ){
        $page_size = $input['page_size']??10;
        if(!isset($input['three_status']) || $input['three_status']===''){
            return ['Data' => [], 'ErrorMessage' => '缺少参数three_status', 'ErrorCode' => ErrorInc::INVALID_PARAM];
        }
        /*------------------------------------------判定请求状态是否在允许范围内开始----------------------------------------*/
        if(!in_array($input['three_status'], [0,1,10,20,30,40])){
            return ['Data' => [], 'ErrorMessage' => '参数错误three_status', 'ErrorCode' => ErrorInc::FAILED_PARAM];
        }
        /*------------------------------------------判定请求状态是否在允许范围内结束----------------------------------------*/
        $db = new SettlementThree();
        $db = $db->leftJoin('settlement_list', 'settlement_list.list_id', '=', 'settlement_three.list_id')->leftJoin('user', 'user.id', '=', 'settlement_three.customer_id');
        /*-------------------------------------------------拼接查询条件开始----------------------------------------------*/
        $where = [];
        if (!$input['source_type'] || $input['source_type']!=1) {
            $common = self::getCommonWhere($session);//获取公用查询条件
            foreach ($common as $k => $v) {
                $where[$k] = $v;
            }
        }
        $three_status = self::getStatusWhere($input['three_status'] , $session);//获取状态查询条件
        foreach( $three_status as $k => $v ){
            $where[$k] = $v;
        }
        if(isset($input['wat_num'])){//结算单号
            $where['gone_settlement_three.wat_num'] = $input['wat_num'];
        }
        if(isset($input['sys_num'])){//系统单号
            $where['gone_settlement_three.sys_num_like'] = $input['sys_num'];
        }
        if(isset($input['order_num'])){//搜索平台单号
            $where['gone_settlement_three.order_num_like'] = $input['order_num'];
        }
        if(isset($input['p_id'])){//搜索所属平台id
            $where['gone_settlement_three.p_id'] = $input['p_id'];
        }
        if(isset($input['shr_name'])){//搜索用户姓名
            $where['shr_name_like'] = $input['shr_name'];
        }
        if(isset($input['shr_phone'])){//搜索用户联系方式
            $where['shr_phone_like'] = $input['shr_phone'];
        }
        if(isset($input['creactDate'])){//创建时间
            $input['creactDate'][1] = date("Y-m-d", strtotime($input['creactDate'][1] . " +1 day"));
            $where['gone_settlement_three.create_time_between'] = $input['creactDate'];
        }

        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $where['gone_settlement_three.company_id'] = $session['company_id'];
        }

        /*-------------------------------------------------拼接查询条件结束----------------------------------------------*/
        if($where) {
            $where = CommonService::jointWhere($where);
            $db = $db->whereRaw($where);
        }
        $data['number_money'] = $db->sum('p_price');//总金额
        $data['showcount'] = self::getStatusBar($session);//获取操作权限可展示订单状态栏

        $is_excel = $input['is_excel']??'0';
        if ($is_excel == 1) {
            DB::connection()->enableQueryLog();#开启执行日志
        }

        $paginate = $db->select('settlement_three.*','shr_sheng','shr_shi','shr_xian','shr_adress','shr_name','shr_phone','p_price','all_price','list_service_type')->orderBy('settlement_three.create_time','desc')->paginate($page_size);

        //导出所需语句
        $data['sqls'] = DB::getQueryLog()[1];
       // dump($data['sqls']);
        $all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
        $export = BmmcService::getTopButton('applicationSub,ajaxSql,export','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $list = CommonService::dataToArray($paginate->items());
        if($list) {
            $data['list'] = self::jointListData($input, $session, $list, $all_button);//获取列表信息明细说明
        }else{
            $data['list'] = [];
        }
        $data['page'] = [
            'count' => $paginate->total(),
            'page' => $paginate->currentPage(),
            'page_size' => $page_size,
            'allPage' => $paginate->lastPage()
        ];
        return ['Data' => $data, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
    }

    /**|---------------------------------------------------------------------------------
     * 拼接列表数据
     * @param string $session 用户信息
     * @param array $input 请求数据
     * @param array $list 订单数据
     * @param array $all_button 按钮信息
     * @retrun /multitype:array
     * @author dou 2021/9/14 14:30
     * |---------------------------------------------------------------------------------
    */
    public static function jointListData ( $input , $session , $list , $all_button ){
        $ser_id = array_column($list, 'ser_id');
        $db = new Admin();
        $companyData = $db::whereIn('id',$ser_id)->pluck('company_name','id');
        $companyData = CommonService::dataToArray($companyData);
        $orderStau = OrderService::getOrderStatusName();//获取订单状态名
        $goodpic = PjBrandsService::getAllPic('name');//获取商品品牌图片 放在此处减少循环调取次数
        $three_statusname = self::getSettlementThreeStatusName(1);
        foreach($list as $k => $v){
            $list[$k]['company_name'] = $companyData[$v['ser_id']]??'暂无';
            $list[$k]['status_name'] = $orderStau[$v['list_service_type']];
            $list[$k]['three_statusname'] = $three_statusname[$v['three_status']];
            /*-------------------------------------------获取对应商品信息开始---------------------------------------------*/
            $msgArr = OrderService::getOrderMsg('', $goodpic,$v['msg_id']);
            $list[$k]['goods_id'] = $msgArr['goods_id'];
            $list[$k]['goods_name'] = $msgArr['goods_name'];
            $list[$k]['goods_num'] = $msgArr['goods_num'];
            $list[$k]['goods_price'] = $msgArr['goods_price'];
            $list[$k]['goods_brand'] = $msgArr['goods_brand'];
            $list[$k]['goods_name_log'] = $msgArr['goods_name_log'];
            $list[$k]['goods_pic_path'] = $msgArr['goods_pic_path'];
            /*-------------------------------------------获取对应商品信息结束---------------------------------------------*/
            $buttonData = [];
            $buttonData[] = 'remarks';
            if ($v['three_status'] == 1) {//我要编辑
                $buttonData[] = 'examine';
            }
            if (($v['three_status'] == 10) || ($v['three_status'] == 40)){
                $buttonData[] = 'editEntry';
            }
            $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']??[];
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 公用查询条件
     * @param array $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/9/14 10:54
     * |---------------------------------------------------------------------------------
    */
    public static function getCommonWhere ( $session ){
        $where = [];
        $where['list_service_type_searchlt'] = 50;

        return $where;
    }

    /**|---------------------------------------------------------------------------------
     * @name 状态查询条件
     * @param array $session 操作人信息
     * @param string $three_status 查询状态
     * @retrun /multitype:array
     * @author dou 2021/9/14 11:04
     * |---------------------------------------------------------------------------------
    */
    public static function getStatusWhere ( $three_status , $session ){
        $where = [];
        if(in_array($three_status, [1,10,20,30,40])){
            $where['three_status'] = $three_status;
        }
        return $where;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取操作的状态栏信息
     * @param array $session 操作人信息
     * @param int $type 是否展示数量信息1是
     * @retrun /multitype:array
     * @author dou 2021/9/14 13:37
     * |---------------------------------------------------------------------------------
    */
    public static function getStatusBar ( $session , $type = ''){
        $showcount = [
            ['show_name'=>"全部",'shownum'=>'--','status'=>0],
            ['show_name'=>"未审核",'shownum'=>'--','status'=>1],
            ['show_name'=>"未结算",'shownum'=>'--','status'=>10],
            ['show_name'=>"结算中",'shownum'=>'--','status'=>20],
            ['show_name'=>"已完成",'shownum'=>'--','status'=>30],
            ['show_name'=>"已回收价格",'shownum'=>'--','status'=>40],
        ];

        if( $type == '1'){
            foreach( $showcount as $k => $v ){
                $showcount[$k]['shownum'] = self::getStatusNum($v['status'],$session);
            }
        }
        return $showcount;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取指定状态数据数量
     * @param int $status 结算单状态
     * @param array $session 操作人信息
     * @retrun \/multitype:array
     * @author dou 2021/9/14 13:44
     * |---------------------------------------------------------------------------------
    */
    public static function getStatusNum ( $status , $session ){
        if(in_array($status, [1,10,20,40])) {
            $db = new SettlementThree();
            $where = [];
            $three_status = self::getStatusWhere($status, $session);//获取状态查询条件
            foreach ($three_status as $k => $v) {
                $where[$k] = $v;
            }
            $num = CommonService::getMysqlData($db,$where,[],[],'count');
            $num = $num??'0';
            return $num;
        }else{
            return '--';
        }
    }

    /**
     * 获取第三方结算单状态名
     * @return /multitype:array
     * @author dou 2021/9/14 13:44
     */
    public static function getSettlementThreeStatusName($type = 2)
    {
        $data = array(array('type'=>1,'value'=>'未审核'),array('type'=>10,'value'=>'未结算'),array('type'=>20,'value'=>'结算中'),array('type'=>30,'value'=>'已完成'),array('type'=>40,'value'=>'已回传价格 '));
        if($type == 1){
            $data = array_column($data, 'value','type');
        }
        return $data;
    }
    /**|---------------------------------------------------------------------------------
     * @name 添加平台金
     * @param string $price 结算金额
     * @param int $good_id 商品id
     * @param int $pt_id 平台id
     * @retrun /multitype:int
     * @author dou 2021/9/14 19:25
     * |---------------------------------------------------------------------------------
    */
    public static function insertPtPrice ( $price , $good_id , $pt_id ){
        $post['price'] = $price;
        $post['good_id'] = $good_id;
        $post['pt_id'] = $pt_id;
        $rea = PtPrice::insert($post);
        return $rea;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加三方数据
     * @param string $list_id 工单号
     * @param string $list_service_type 订单状态
     * @retrun /multitype:array
     * @author dou 2022/6/15 16:18
     * |---------------------------------------------------------------------------------
    */
    public static function addData ( $list_id , $list_service_type ){
        $setthreeid = self::getSettlementThreeBy('list_id' , $list_id , ['id','three_status']);
        $setlist = SettlementService::getSettlementListBy('list_id',$list_id,['sys_num','msg_id','p_id','order_num','list_id','ser_id','customer_id','id','create_time','setfeeds_time','company_id']);
        $pt = PlatformService::getFieldsById($setlist['p_id'],['pt_name','three_pd']);
        $post['p_name'] = $pt['pt_name'];
        $post['sys_num'] = $setlist['sys_num'];
        $post['msg_id'] = $setlist['msg_id'];
        $post['p_id'] = $setlist['p_id'];
        $post['order_num'] = $setlist['order_num'];
        $post['list_id'] = $setlist['list_id'];
        $post['ser_id'] = $setlist['ser_id'];
        $post['customer_id'] = $setlist['customer_id'];
        $post['pgid'] = $setlist['id'];
        $post['list_service_three'] = $list_service_type;
        $creact_time = OrderService::getOrderBy('sys_num', $setlist['sys_num'],['create_time']);
        $post['create_time'] = $creact_time??$setlist['create_time'];
        if( !$setthreeid || ( $setthreeid && $setthreeid['three_status'] == 1 )) {
            $goods_id = OrderService::getOrderMsgBy('id', $setlist['msg_id'], ["goods_id", "goods_name"]);
            if ($goods_id) {
                $post['goods_id'] = $goods_id['goods_id'];
                $post['goods_name'] = $goods_id['goods_name'];
                $p_price = DB::table('pt_price')->whereRaw("pt_id='" . $setlist['p_id'] . "' and good_id='" . $goods_id['goods_id'] . "'")->value("price");
                if (isset($p_price)) {
                    $post['p_price'] = $p_price;
                } else {
                    $post['p_price'] = 0;
                }

            }
        }
        $post['three_pd'] = $pt['three_pd'];
        $post['jd_time'] = $setlist['create_time'];
        $post['fk_time'] = $setlist['setfeeds_time'];
        $post['company_id'] = $setlist['company_id'];
        if($setthreeid){
            $post['updatetime'] = date("Y-m-d H:i:s");
            $rea = SettlementThree::where("id",$setthreeid['id'])->update($post);
        }else {
            $rea = SettlementThree::insert($post);
        }
        return $rea;
    }

    /**|---------------------------------------------------------------------------------
     * @name 删除三方数据
     * @param string $list_id 工单号
     * @retrun /multitype:array
     * @author dou 2022/6/15 19:06
     * |---------------------------------------------------------------------------------
    */
    public static function deletData ( $list_id ){
        $setthreeid = self::getSettlementThreeBy('list_id' , $list_id , ['id','three_status']);
        if( !$setthreeid || ( $setthreeid && $setthreeid['three_status'] == 1 )) {
            SettlementThree::where("list_id",$list_id)->delete();
        }
    }
}
