<?php
namespace App\Http\Controllers\DatasBase;
use App\Http\Controllers\BaseController;
use App\OtherModels\SmsRecord;
use App\Services\BmmcService;
use App\Services\CategoryService;
use App\Services\CommonService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use DB;
use App\Models\SmsTemplate;
use App\Models\OrderList;
use App\Models\OrderAfter;

class SmsTemplateController extends BaseController
{

    /**
     * @name  短信列表
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/2
     */
    public function index (Request $request)
    {
        $Db = new SmsTemplate();

        if ($request->filled('send_user_type')) { //接收类型：1:发给客户；2：发给门店
            $Db = $Db->where('send_user_type',$request->input('send_user_type'));
        }
        if ($request->filled('type')) { //短信类型
            $Db = $Db->where('type',$request->input('type'));
        }
        if ($request->filled('category')) { //品类类型
            $Db = $Db->where('category',$request->input('category'));
        }


        $page_size = (int)$request->input('page_size',20);
        $page = (int)$request->input('page',1);
        if ($page<1) {
            $page=1;
        }
        $offset = ($page-1)*$page_size;
        //统计数量
        $count = $Db->count();
        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        $export = BmmcService::getTopButton('insert','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $list = $Db->orderBy('created_at', 'DESC')->offset($offset)->limit($page_size)->get()->toArray();
        $data['page'] = [//页码信息
            'page' => $request->input('page',1),
            'page_size' => $page_size,
            'count' => $count,
            'allPage' => ceil($count/$page_size)
        ];
        if ($list && $list != []) {
            $type_names = CommonService::getSmsModelType();
            foreach ($list as $k => $v) {
                $list[$k]['type'] = $type_names[$v['type']];
                $list[$k]['cd_name'] = CategoryService::getNameByCdId($v['category']);
                $buttonData = [];
                if ($v['time_interval'] >= 60) {
                    $hour = floor($v['time_interval']/60);
                    $minutes = $v['time_interval'] - ($hour*60);
                    $list[$k]['time_interval'] = $hour . '时' . $minutes . '分';
                }
                $buttonData[] = 'edit,sms_test';
                $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']??[];
            }
            $data['list'] = $list;
            return $this->success('获取成功',$data);exit;
        }else{
            $data['list'] = [];
            return $this->success('获取成功',$data);exit;
        }
    }

    ////订单号为|OrderNum|，客户姓名为|Name|，电话：|Phone|。
    /**
     * @name  获取标签
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/2
     */
    public function template (Request $request)
    {
        $label = [
            ['tem_name' => '客户姓名', 'tem_ide' => '|Name|','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_01.jpg'],
            ['tem_name' => '客户电话', 'tem_ide' => '|Phone|','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_02.jpg'],
            ['tem_name' => '客户地址', 'tem_ide' => '|Dress|','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_03.jpg'],
           // ['tem_name' => '工单单号', 'tem_ide' => '|SerialNum|','img_url' => 'http://mo2o9s.sudianwang.com/image/lableimg/sms_temp_img_04.jpg'],
            //['tem_name' => '售后单号', 'tem_ide' => '|AfterNum|','img_url' => 'http://mo2o9s.sudianwang.com/image/lableimg/sms_temp_img_05.jpg'],
            ['tem_name' => '平台单号', 'tem_ide' => '|OrderNum|','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_06.jpg'],
            //['tem_name' => '商品名称', 'tem_ide' => '|GoodsName|','img_url' => 'http://mo2o9s.sudianwang.com/image/lableimg/sms_temp_img_07.jpg'],
            ['tem_name' => '检验码', 'tem_ide' => '|CheckCode|','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_08.jpg'],
            ['tem_name' => '下单时间', 'tem_ide' => '|OrderTime|','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_09.jpg'],
            ['tem_name' => '门店电话', 'tem_ide' => '|storePhone|','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_10.jpg'],
        ];
        if ($request->input('type') == '售后') {
            $count = count($label);
            unset($label[$count-1]);
        }
        if ($label != []) {
            return $this->success('获取成功',$label);exit;
        }
    }

    /**
     * @name  添加
     * @param type          短信类型：接单，催单，售后
     * @param content       短信内容
     * @param time_interval 时间间隔
     * @param img_text      标签图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     * @author du
     * @date 2021/9/2
     */
    public function insert (Request $request)
    {
        if ($request->filled('type','is_edit','content','category','send_user_type')) {
            $time_interval = $request->input('time_interval');
            $is_edit = $request->input('is_edit');
            $exits = SmsTemplate::where('type',$request->input('type'))->where('send_user_type',$request->input('send_user_type'))->first();
            if ($exits) {
                return $this->error('该短信类型已存在，无需重复添加', ErrorInc::MYSQL_FAILED);exit;
            }
            $content = $request->input('content','');
            if ($request->input('type') != '催单') {
                $time_interval = $time_interval;
            } else {
                $time_interval = 0;
            }
            $res = SmsTemplate::insertGetId([
                'type'          => $request->input('type'),//模块类型
                'category'      => $request->input('category'),//品类ID
                'send_user_type' => $request->input('send_user_type'),//1:发给客户；2：发给门店
                'content'       => $content,
                'time_interval' => $time_interval,
                'created_at'    => date('Y-m-d H:i:s'),
                'is_edit'       => $is_edit,
                'img_text'      => $request->input('img_text')
            ]);
            if ($res) {
                $this->insertingLog("添加","",'数据id：'.$res.'，内容：'.$content,"短信模板",$request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('操作成功');exit;
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }
    /**
     * @name  编辑
     * @param type          短信类型
     * @param content       短信内容
     * @param time_interval 时间间隔
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/2
     */
    public function edit (Request $request)
    {
        if ($request->filled(['id','type','content','category','send_user_type'])) {
            $content = $request->input('content','');
            if ($request->input('type') != '催单') {
                $time_interval = $request->input('time_interval');
            } else {
                $time_interval = 0;
            }
            $exits = SmsTemplate::where('type',$request->input('type'))->where('send_user_type',$request->input('send_user_type'))->where('id','!=',$request->input('id'))->first();
            if ($exits) {
                return $this->error('该短信类型已存在，无需重复添加', ErrorInc::MYSQL_FAILED);exit;
            }
            $res = SmsTemplate::where('id',$request->input('id'))->update([
                'type' => $request->input('type'),
                'category'      => $request->input('category'),//品类ID
                'send_user_type' => $request->input('send_user_type'),//1:发给客户；2：发给门店
                'content' => $content,
                'time_interval' => $time_interval,
                'updated_at'   => date('Y-m-d H:i:s'),
                'img_text'      => $request->input('img_text')
            ]);
            if ($res) {
                $this->insertingLog("编辑","",'数据id：'.$request->input('id').'，内容：'.$content,"短信模板",$request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('编辑成功');exit;
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        } else {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }
    /**
     * @name  发送短信
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/2
     */
    public function send_sms (Request $request)
    {
        $sms_tmp = SmsTemplate::whereIn('type', ['接单','售后'])->first();
        $interval = $sms_tmp['time_interval'];
        $content = $sms_tmp['content'];
        $time = strtotime("-".$interval." minutes");
        if ($sms_tmp['type'] == '接单') {
            $list = OrderList::leftJoin('user','user.id','=','order_list.customer_id')->leftJoin('orders','orders.sys_num','=','order_list.sys_num')->where('stauas','<',30)->where('create_time','>',$time)->select('serial_number','shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress','orders.check_code','order_list.order_goods_id')->get()->toArray();
        } elseif ($sms_tmp['type'] == '售后') {
            $list = OrderAfter::leftJoin('orders','orders.sys_num','=','order_after.sys_num')->where('status',1)->where('create_time','<',$time)->select('order_after.after_num','good_names as goods_name','shr_name','shr_phone','shr_sheng','shr_shi','shr_address as shr_adress','orders.check_code')->get()->toArray();
        }
        if (!$list && $list != []) {
            if ($sms_tmp['type'] == '接单') {
                $goodArr = [];
                foreach ($list as $ks => $vs) {
                    $goodArr[] = $vs['order_goods_id'];
                }
                $goods = DB::table('order_msg')->whereIn('id',$goodArr)->pluck('goods_name','id')->toArray();

                foreach ($list as $kv => $vv) {
                    if(isset($goods[$vv['goods_id']])) {
                        $list[$kv]['goods_name'] = $goods[$vv['goods_id']];
                    } else {
                        $list[$kv]['goods_name'] = '';
                    }
                }
            }
            foreach ($list as $k => $v) {
                $send_msg = $content;
                $address = $v['shr_sheng'].$v['shr_shi'].$v['shr_xian'].$v['adress'];
                $msg = str_replace("|Dress|",$address,$send_msg);
                $msg = str_replace("|Phone|",$v['shr_phone'],$msg);
                $msg = str_replace("|Name|",$v['shr_name'],$msg);
                $msg = str_replace("|GoodsName|",$v['goods_name'],$msg);
                $msg = str_replace("|CheckCode|",$v['check_code'],$msg);
                if ($sms_tmp['type'] == '接单') {
                    $msg = str_replace($v['serial_number'],"|SerialNum|",$msg);
                } elseif ($sms_tmp['type'] == '售后') {
                    $msg = str_replace($v['after_num'],"|AfterNum|",$msg);
                }
                if ($sms_tmp['type'] == '接单') {
                    OrderList::where('serial_number',$v['serial_number'])->update(['sord' => 1]);
                } elseif ($sms_tmp['type'] == '售后') {
                    OrderAfter::where('after_num',$v['after_num'])->update(['send_sms' => 1]);
                }

                //发送短信
                CommonService::senSms($v['shr_phone'], $msg, 'SuDianPaw','','',$request->get('session_token')['admin_acc']);
            }
            return $this->success('操作成功');exit;
        }else{
            return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**
     * @name  测试发送短信
     * @param phone  手机号
     * @param order_num 单号(平台单号或售后单号)
     * @param type 发送模块类型
     * @param send_user_type 接收类型：1:发给客户；2：发给门店
     * @param send_type 是否发短信，1：发送，2：不发
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/3
     */
    public function sms_test (Request $request)
    {
        $input = $request->all();
        $checkKey = CommonService::checkKey(['order_num', 'phone', 'type','send_user_type','send_type'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $msg = CommonService::sendSmsModle($input);

        if($msg['ErrorCode']!=1){
            return $msg;
        }
//print_r($msg);
       // echo $msg['Data']['msg'];
        if ($request->input('send_type') == 1) {
            //发送短信
            $res = SmsRecord::where('customer_phone',$input['phone'])->orderBy('created_at','Desc')->value('created_at');
            $oldTime = strtotime($res);
            $nowTime = time();
            if(($nowTime-$oldTime)<15){
                return $this->error('15秒内不可重复发送', ErrorInc::INVALID_PARAM);exit;
            }
            CommonService::senSms($input['phone'], $msg['Data']['msg'], 'SuDianPaw','','',$request->get('session_token')['admin_acc']);
            return $this->success('发送成功');exit;
        } else {
            return $this->error('不发送短信', ErrorInc::FAILED_PARAM);exit;
        }

        exit;

       /* if ($request->filled('id')) {
            if (!$request->filled('phone')) {
                return $this->error('请输入手机号', ErrorInc::FAILED_PARAM);exit;
            }
            if (!$request->filled('number')) {
                return $this->error('请输入单号', ErrorInc::FAILED_PARAM);exit;
            }
            $phone = $request->input('phone');
            $sms = SmsTemplate::where('id',$request->input('id'))->first(['type','content']);
            if (empty($sms['content'])) {
                return $this->error('短信内容为空，无法发送短信', ErrorInc::FAILED_PARAM);exit;
            }
            if ($sms['type'] == '售后') {
                $info = OrderAfter::leftJoin('orders','orders.sys_num','=','order_after.sys_num')->where('order_after.after_num',$request->input('number'))->select('order_list.order_num','good_names as goods_name','serial_number','sys_num','shr_name','shr_phone','shr_address','orders.check_code')->first();
            } else {
                $info = OrderList::leftJoin('user','order_list.customer_id','=','user.id')->leftJoin('orders','orders.sys_num','=','order_list.sys_num')->where('order_list.order_num',$request->input('number'))->select('order_list.order_num','order_list.sys_num','serial_number','shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress','orders.check_code','order_goods_id','orders.create_time')->first();
            }
            if ($info) {
                if ($sms['type'] != '售后') {
                    $goods = DB::table('order_msg')->where('id',$info['order_goods_id'])->value('goods_name');
                    $info['goods_name'] = $goods;
                }
                if (isset($info['shr_sheng'])) {
                    $info['shr_address'] = $info['shr_sheng'].$info['shr_shi'].$info['shr_xian'].$info['shr_adress'];
                }
                $msg = $sms['content'];
                $msg = str_replace("|Dress|",$info['shr_address'],$msg);
                $msg = str_replace("|Phone|",$info['shr_phone'],$msg);
                $msg = str_replace("|Name|",$info['shr_name'],$msg);
                $msg = str_replace("|SerialNum|",$info['serial_number'],$msg);
                $msg = str_replace("|OrderNum|",$info['order_num'],$msg);
                $msg = str_replace("|AfterNum|",$info['after_num'],$msg);
                $msg = str_replace("|GoodsName|",$info['goods_name'],$msg);
                $msg = str_replace("|CheckCode|",$info['check_code'],$msg);
                $msg = str_replace("|OrderTime|",$info['create_time'],$msg);
                if ($request->input('type') == 1) {
                    //发送短信
                    CommonService::senSms($phone, $msg, 'SuDianPaw', '', '', $request->get('session_token')['admin_acc']);
                    return $this->success('发送成功');exit;
                } else {
                    return $this->error('不发送短信', ErrorInc::FAILED_PARAM);exit;
                }
            } else {
                return $this->error('暂无订单信息', ErrorInc::DATA_EMPTY);exit;
            }
        } else {
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }*/
    }

    /**
     * @name 获取模块
     * @return mixed
     * @author du
     * @date 2022/2/10
     */
    public function getSmsModel(){
        $data = CommonService::getSmsModelType(false);
        return $this->success('获取成功',$data);
    }

}
