<?php
namespace App\Http\Models\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Order;

class CashierDesk extends Model
{
    /**
     * [submitAccount 虚拟加盟店添加订单派单]
     * @param  [type] $user_info  [用户信息]
     * @param  [type] $request    [提交数据]
     */
    public static function createVirtualOrder(
        $user_info,
        $request
    ) {
        // 生成订单数据
        $order_data = Order::createOrder($user_info, $request, 2);
        if ($order_data['code'] == 500) {
            DB::rollBack();
            return response()->json($order_data);
        }
    }

    // 客户单位应收正值
    public function positive($user_info, $chun_id, $shop_id)
    {
        // 正数
        $positive_arr = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            // ->where('recr_state', '!=',2)//未核销 2.已核销 3已收款
            ->whereRaw('`recr_settle_price` <> `recr_yet_receipt`')
            ->where('recr_belongs_id', '=', 0)
            ->where('recr_plus_minus', 1) //金额正值
            ->where('recr_client_id', $chun_id)
            ->where('recr_client_type', 2)
            ->select('recr_settle_price', 'recr_actual_price', 'recr_yet_receipt', 'recr_zero_price', 'recr_zero_plus_minus')
            ->get();
        $positive['recr_settle_price'] = 0;
        $positive['recr_yet_receipt'] = 0;
        $positive['recr_zero_price'] = 0;
        if (!empty($positive_arr)) {
            foreach ($positive_arr as $key => $value) {
                $positive['recr_settle_price'] += $value->recr_settle_price;
                // $positive['recr_actual_price'] += $value->recr_actual_price; 
                $positive['recr_yet_receipt'] += $value->recr_yet_receipt;
                if ($value->recr_zero_plus_minus == 1) {
                    $positive['recr_zero_price'] += $value->recr_zero_price;
                } else {
                    $positive['recr_zero_price'] -= $value->recr_zero_price;
                }
            }
        }
        return $positive;
    }

    // 客户单位应收负值
    public function minus($user_info, $chun_id, $shop_id)
    {
        // 负数
        $minus_arr = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            // ->where('recr_state', '!=',2)//未核销 2.已核销 3已收款
            ->whereRaw('`recr_settle_price` <> `recr_yet_receipt`')
            ->where('recr_belongs_id', '=', 0)
            ->where('recr_plus_minus', 2) //金额正值
            ->where('recr_client_id', $chun_id)
            ->where('recr_client_type', 2)
            ->select('recr_settle_price', 'recr_actual_price', 'recr_yet_receipt', 'recr_zero_price', 'recr_zero_plus_minus')
            ->get();

        $minus['recr_settle_price'] = 0;
        $minus['recr_yet_receipt'] = 0;
        $minus['recr_zero_price'] = 0;
        if (!empty($minus_arr)) {
            foreach ($minus_arr as $key => $value) {
                $minus['recr_settle_price'] += $value->recr_settle_price;
                // $minus['recr_actual_price'] += $value->recr_actual_price; 
                $minus['recr_yet_receipt'] += $value->recr_yet_receipt;
                if ($value->recr_zero_plus_minus == 1) {
                    $minus['recr_zero_price'] += $value->recr_zero_price;
                } else {
                    $minus['recr_zero_price'] -= $value->recr_zero_price;
                }
            }
        }
        return $minus;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加推送信息
     * @param Request pushtype 推送类型
     * @param Request wor_number 工单号
     * @param Request ord_number 订单单号
     * @param Request order_type 工单类型
     * @param Request adm_id 账号id
     * @param Request user_name 用户姓名
     * @param Request user_phone 用户电话
     * @param Request user_dress 用户地址
     * |---------------------------------------------------------------------------------
     */
    public function inforPush($input)
    {
        $pushtype = [1,2,3,4,5,6,7,8]; //推送类型：1新工单派单通知2待发货通知3工单进度通知-技师返工4智配推送新订单5短信余额预警6撤回订单提醒8用户注册提醒
        $master = DB::table('admin_master')
            ->where("adma_adm_id", $input['adm_id'])
            ->where("adma_follow", '2')
            ->where("adma_binding_state", '1')
            ->select("adma_openid")
            ->get()->toArray();
        if (!$master) {
            $data['wep_wor_number'] = isset($input['wor_number']) ? $input['wor_number'] : '';
            $data['wep_ord_number'] = $input['ord_number'];
            $data['wep_adm_id'] = $input['adm_id'];
            $data['wep_weixindata'] = '无绑定微信';
            $data['wep_type'] = $input['pushtype'];
            DB::table('weixin_push')->insert($data);
        } else {
            $appid_bjmd = config('wechat.bjmd.appid');//半径门店公众号appid
            $appsecret_bjmd = config('wechat.bjmd.appsecret');//半径门店appsecret
            // 半径门店appid=wx7c45128ab7710f54 AppSecret： a92d64dd5fcf2d72cd12df9aeb9c7a5a
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid_bjmd.'&secret='.$appsecret_bjmd; //生产环境
            $output = file_get_contents($url); //运行curl
            $obj = json_decode($output, true);
            if (empty($obj['access_token'])) {
                $data['wep_wor_number'] = $input['wor_number'];
                $data['wep_ord_number'] = $input['ord_number'];
                $data['wep_adm_id'] = $input['adm_id'];
                $data['wep_weixindata'] = 'token错误';
                $data['wep_type'] = $input['pushtype'];
                DB::table('weixin_push')->insert($data);
            } else {
                $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $obj['access_token'];
                if ($input['pushtype'] == 1) {//1新工单派单通知
                    $poss['template_id'] = config('wechat.template.paidan');
                    $miniprogram['appid'] = 'wx5a9e016f8ebb40c7';
                    $miniprogram['pagepath'] = 'pages/workOrder/workOrderList?action=myWorkIndex';
                    $poss['miniprogram'] = $miniprogram;
//                    $first['value'] = $input['tittle'];
//                    // $keyword1['value'] = $input['orcl_appoint_time'];
//                    $keyword1['value'] = $input['ord_create_time'];
//                    $keyword2['value'] = $input['sepr_name'];
//                    $remark['value'] = $input['tittle'];
//                    $data['first'] = $first;
//                    $data['keyword1'] = $keyword1;
//                    $data['keyword2'] = $keyword2;
//                    $data['remark'] = $remark;
                    $first['value'] = $input['tittle'];
                    $remark['value'] = $input['tittle'];
                    $keyword1['value'] = $input['wor_number'];//工单编号
                    $keyword2['value'] = $input['sepr_name'];//服务内容
                    $keyword3['value'] = $input['orcl_appoint_time'];//服务时间
                    $keyword4['value'] = $input['shop_name'];//服务地址
                    $keyword5['value'] = $input['sevice_list'];//所属团队
                    $remark['value'] = $input['tittle'];
                    $data['first'] = $first;
                    $data['keyword1'] = $keyword1;
                    $data['keyword2'] = $keyword2;
                    $data['keyword3'] = $keyword3;
                    $data['keyword4'] = $keyword4;
                    $data['keyword5'] = $keyword5;
                    $data['remark'] = $remark;
                    $poss['data'] = $data;
                } elseif ($input['pushtype'] == 2) {//2待发货通知
                    $poss['template_id'] = config('wechat.template.daifahuo');
                    $miniprogram['appid'] = 'wx5a9e016f8ebb40c7';
                    if(isset($input['dego_id'])){
                        $miniprogram['pagepath'] = '/pages/warehouse/deliverGoods?dego_id='.$input['dego_id'];
                    }else{
                        $miniprogram['pagepath'] = 'pages/warehouse/warehouse?type=1';
                    }
                    $poss['miniprogram'] = $miniprogram;
                    $first['value'] = $input['tittle'];
                    $keyword1['value'] = $input['user_data'];
                    $keyword2['value'] = $input['user_dress'];
                    $remark['value'] = $input['remark'];
                    $data['first'] = $first;
                    $data['keyword1'] = $keyword1;
                    $data['keyword2'] = $keyword2;
                    $data['remark'] = $remark;
                    $poss['data'] = $data;
                } elseif ($input['pushtype'] == 3) {//工单进度通知-技师返工
                    $poss['template_id'] = config('wechat.template.gongdanjindu');
                    if(isset($input['wor_number'])){
                        $miniprogram['appid'] = 'wx5a9e016f8ebb40c7';
                        $miniprogram['pagepath'] = 'pages/workOrder/workOrderList?action=myWorkIndex&keywords='.$input['wor_number'];
                        // $miniprogram['pagepath'] = '/pages/workOrder/workDetail?wor_id='.$input['wor_id'];
                        $poss['miniprogram'] = $miniprogram;
                    }
                    $first['value'] = $input['tittle'];
                    $keyword1['value'] = $input['wor_number'];//工单号
                    $keyword2['value'] = $input['wor_state'];//工单进度
                    $keyword3['value'] = $input['user_name'];//被通知人
                    $remark['value'] = '';
                    $data['first'] = $first;
                    $data['keyword1'] = $keyword1;
                    $data['keyword2'] = $keyword2;
                    $data['keyword3'] = $keyword3;
                    $data['remark'] = $remark;
                    $poss['data'] = $data;
                } elseif ($input['pushtype'] == 4) {//智配推送新订单
                    $poss['template_id'] = config('wechat.template.neworder');
                    if(isset($input['ord_id'])){
                        $miniprogram['appid'] = 'wx5a9e016f8ebb40c7';
                        $miniprogram['pagepath'] = '/pages/order/orderDetail?ord_id='.$input['ord_id'];
                        $poss['miniprogram'] = $miniprogram;
                    }
                    $first['value'] = $input['tittle'];
                    $keyword5['value'] = $input['goods'];//工单号
                    $keyword6['value'] = $input['orcl_name'];//客户名称
                    $remark['value'] = '';
                    $data['first'] = $first;
                    $data['thing5'] = $keyword5;
                    $data['thing6'] = $keyword6;
                    $data['remark'] = $remark;
                    $poss['data'] = $data;
                } elseif ($input['pushtype'] == 5) {//短信余额预警
                    $poss['template_id'] = config('wechat.template.msgremind');
                    
                    $first['value'] = $input['tittle'];
                    $keyword5['value'] = $input['shop_message_num'];//短信条数
                    $keyword6['value'] = $input['name'];//名称
                    $remark['value'] = '';
                    $data['first'] = $first;
                    $data['thing5'] = $keyword5;
                    $data['thing6'] = $keyword6;
                    $data['remark'] = $remark;
                    $poss['data'] = $data;
                } elseif ($input['pushtype'] == 6) {//撤回订单提醒
                    $poss['template_id'] = config('wechat.template.cancelorder');
                    if(isset($input['ord_id'])){
                        $miniprogram['appid'] = 'wx5a9e016f8ebb40c7';
                        $miniprogram['pagepath'] = '/pages/order/orderDetail?ord_id='.$input['ord_id'];
                        $poss['miniprogram'] = $miniprogram;
                    }
                    $character_string1['value'] = $input['character_string1'];//订单号
                    $keyword5['value'] = $input['thing4'];//取消客户
                    $keyword6['value'] = $input['time3'];//取消时间
                    // $const2['value'] = $input['const2'];//取消原因
                    $data['character_string1'] = $character_string1;
                    $data['thing4'] = $keyword5;
                    $data['time3'] = $keyword6;
                    // $data['const2'] = $const2;
                    $poss['data'] = $data;
                } elseif ($input['pushtype'] == 7) {//客户小程序下单提醒
                    $poss['template_id'] = config('wechat.template.orderNotice');
                    if(isset($input['ord_id'])){
                        $miniprogram['appid'] = 'wx5a9e016f8ebb40c7';
                        $miniprogram['pagepath'] = '/pages/order/orderDetail?ord_id='.$input['ord_id'];
                        $poss['miniprogram'] = $miniprogram;
                    }
                    $character_string10['value'] = $input['ord_number'];//订单号
                    $phone_number5['value'] = $input['orcl_phone'];//订单号
                    $thing9['value'] = $input['sepr_name'];//服务项目
                    $thing8['value'] = $input['orcl_name'];//客户姓名
                    $time6['value'] = $input['ord_create_time'];//下单时间
                    $data['character_string10'] = $character_string10;
                    $data['phone_number5'] = $phone_number5;
                    $data['thing9'] = $thing9;
                    $data['thing8'] = $thing8;
                    $data['time6'] = $time6;
                    $poss['data'] = $data;
                } elseif ($input['pushtype'] == 8) {//用户注册提醒
                    $poss['template_id'] = config('wechat.template.zhuce');
                    
                    $first['value'] = $input['shop_name'];
                    $keyword5['value'] = $input['state'];//状态
                    $keyword6['value'] = $input['time'];//名称
                    $data['thing1'] = $first;
                    $data['const3'] = $keyword5;
                    $data['time4'] = $keyword6;
                    $poss['data'] = $data;
                }
                $master = $this->objectToArray($master);
                foreach ($master as $k => $v) {
                    $poss['touser'] = $v['adma_openid'];
                    $res = $this->https_post($url, json_encode($poss));
                    $datas['wep_wor_number'] = isset($input['wor_number']) ? $input['wor_number'] : '';
                    $datas['wep_ord_number'] = $input['ord_number'];
                    $datas['wep_adm_id'] = $input['adm_id'];
                    $datas['wep_openid'] = $v['adma_openid'];
                    $datas['wep_weixindata'] = $res."---".json_encode($poss);
                    $datas['wep_type'] = $input['pushtype'];
                    $rea = DB::table('weixin_push')->insert($datas);
                }
            }
        }
    }

    // 后端发送消息，给会员发送推送消息
    public function weixinMessageSend($input)
    {
        $appid_bjmd = config('wechat.bjmd.appid');//半径门店公众号appid
        $appsecret_bjmd = config('wechat.bjmd.appsecret');//半径门店appsecret
        // 半径门店appid=wx7c45128ab7710f54 AppSecret： a92d64dd5fcf2d72cd12df9aeb9c7a5a
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid_bjmd.'&secret='.$appsecret_bjmd; //生产环境
        $output = file_get_contents($url); //运行curl
        $obj = json_decode($output, true);
        if (!empty($obj['access_token'])) {
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $obj['access_token'];
            $poss['template_id'] = config('wechat.template.kehugenjin');
            $first['value'] = $input['title'];
            $keyword1['value'] = $input['name'];//客户昵称
            $keyword2['value'] = $input['phone'];//客户手机
            $keyword3['value'] = date('Y-m-d H:i:s');//操作时间
            $remark['value'] = $input['message'];
            $data['first'] = $first;
            $data['keyword1'] = $keyword1;
            $data['keyword2'] = $keyword2;
            $data['keyword3'] = $keyword3;
            $data['remark'] = $remark;
            $poss['data'] = $data;
            $poss['touser'] = $input['openid'];//OPENID
            // $poss['url'] = 'https://xm.bluearp.com/';//查看详情链接
            $poss = json_encode($poss);
            $res = $this->https_post($url, $poss);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name  对象转数组
     * @param $object 对象数据
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/9/30 16:35>
     * |---------------------------------------------------------------------------------
     */
    function objectToArray($object)
    {
        // 先编码成json字符串，再解码成数组
        return json_decode(json_encode($object), true);
    }

    /**|---------------------------------------------------------------------------------
     * @name  https协议post传参
     * @param $url 请求链接
     * @param $data 请求数据
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/11/9 17:10>
     * |---------------------------------------------------------------------------------
     */
    //
    function https_post($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    // 计算可欠金额  可欠天数
    public function isExceed($request, $user_info, $ord_actual_price)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 是否超出可欠 金额 天数
        $is_exceed = true;
        // 验证天数
        // if ($request['ord_type'] == 2) {
        $chun_info = DB::table('channel_info')
            ->where('chin_chun_id', $request['ord_client_id'])
            ->first(['chin_type', 'chin_owe_day', 'chin_owe_money']);
        // 查询出该客户最早未结算的订单距离今天的天数
        if (!empty($chun_info) && $chun_info->chin_owe_day > 0) {
            // 查询出该客户最早未结算的订单距离今天的天数
            $ord_time = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_id', $user_info->adm_shop_id)
                ->where('recr_state', '!=', 2) //未核销 2.已核销 3已收款
                // ->whereRaw('`recr_settle_price` <> `recr_yet_receipt`')
                ->where('recr_belongs_id', '=', 0)
                ->where('recr_plus_minus', 1) //金额正值
                ->where('recr_client_id', $request['ord_client_id'])
                ->where('recr_client_type', 2)
                ->orderBy('recr_order_time', 'asc')
                ->value('recr_order_time');
            if ($ord_time) {
                $diff_day = (strtotime(date('Y-m-d')) - strtotime(substr($ord_time, 0, 10))) / 86400;
            } else {
                $diff_day = 0;
            }

            // 大于可欠天数：不允许客户生成账期的订单
            // if ($diff_day > $chun_info->chin_owe_day && $request['ord_payment_way'] == 1) {
            if ($diff_day > $chun_info->chin_owe_day) {
                $is_exceed = false;
            }
        }
        // 金额
        if (!empty($chun_info) && $chun_info->chin_owe_money > 0) {
            // 客户单位应收正值
            $positive = $this->positive($user_info, $request['ord_client_id'], $shop_id);
            $positive['recr_settle_price'] += $ord_actual_price;
            // 客户单位应收负值
            $minus = $this->minus($user_info, $request['ord_client_id'], $shop_id);
            // // 虚拟加盟店
            // $vish_id = DB::table('virtual_shop')
            //     ->where('vish_chun_id',$request['ord_client_id'])
            //     ->value('vish_id');
            // if(!empty($vish_id)){
            //     // 负数
            //     $minus_virtual = DB::table('receivable_credit')
            //         ->where('recr_cid', $user_info->adm_cid)
            //         ->where('recr_shop_superior_id', $shop_id)
            //         ->where('recr_state', 1)//未核销
            //         ->where('recr_statistics_type', 1)//1统计状态
            //         ->where('recr_plus_minus', 2)//金额正值
            //         ->where('recr_client_id',$vish_id)
            //         ->where('recr_client_type',7)
            //         ->select(DB::raw('sum(recr_settle_price) as recr_settle_price,sum(recr_actual_price) as recr_actual_price,sum(recr_yet_receipt) as recr_yet_receipt,sum(recr_zero_price) as recr_zero_price'))
            //         ->first();
            //     $minus->recr_settle_price += $minus_virtual->recr_settle_price;
            //     $minus->recr_yet_receipt += $minus_virtual->recr_yet_receipt;
            //     $minus->recr_zero_price += $minus_virtual->recr_zero_price;
            // }
            $recr_settle_price = $positive['recr_settle_price'] - $minus['recr_settle_price']; //实际金额
            $recr_yet_receipt = $positive['recr_yet_receipt'] - $minus['recr_yet_receipt']; //已收金额
            $recr_zero_price = $positive['recr_zero_price'] - $minus['recr_zero_price']; //抹零金额
            // 欠收 = 结算金额 - 已收 - 抹零
            $total_client_price = ($recr_settle_price - $recr_yet_receipt - $recr_zero_price) / 100; //客户欠收总金额总计
            // if ($total_client_price > $chun_info->chin_owe_money && $request['ord_payment_way'] == 1) {
            if ($total_client_price > $chun_info->chin_owe_money) {
                $is_exceed = false;
            }
        }
        // }   
        return $is_exceed;
    }
}
