<?php

namespace App\Http\Controllers\sms;
use App\Http\Controllers\BaseController;
use App\Models\SmsAccount;
use App\OtherModels\SmsRecord;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\OtherModels\SmsHistory;
use DB;
use App\Services\SmsService;
use App\OtherModels\AfterSms;
use App\Services\CommonService;
use App\Models\Orders;
use Validator;
class SmsHistoryController extends BaseController
{
	/**
	 * @param sh_phone
	 * @param sh_state
	 * @param Request $request
	 * @author du 2021年8月17日下午3:07:07
	 */
    public function index (Request $request)
    {
    	$input = $request->all();
    	$list = SmsService::getList($input);
    	if($list['list']){
    		return $this->success('获取成功', $list); exit;
    	}else{
    		return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$list);exit;
    	}
    }

    /**
     * 根据客户电话获取订单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\BlueCity\Core\Controllers\mixed
     * @author du 2021年8月17日下午4:38:50
     */
    public function orderList (Request $request)
    {
    	if(!$request->filled('sh_phone')){
    		return $this->error('参数错误无sh_phone', ErrorInc::FAILED_PARAM, []);exit;
    	}
        $phone = $request->input('sh_phone');
        $user_id = Db::table('user')->where('shr_phone',$phone)->select('id')->get()->toArray();
        if(!$user_id){
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
        }
        $id = array_column($user_id, 'id');
        $data = Orders::whereIn('new_customer_id',$id)->select('sys_num','create_time','order_num')->orderBy('create_time','DESC')->limit('20')->get()->toArray();
        if($data){
        	return $this->success('获取成功', $data); exit;
    	}else{
    		return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
    	}
    }
    /**
     *
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月17日下午4:34:50
     */
    public function orderDo (Request $request)
    {
    	if(!$request->filled('sh_id')){
    		return $this->error('参数错误无sh_id', ErrorInc::FAILED_PARAM, []);exit;
    	}
        $sys_num = $request->input('sys_num');
        $sh_id = $request->input('sh_id');
        $state['sh_state'] = 2;
        SmsHistory::where('sh_id',$sh_id)->update($state);
        $note_content = $request->input('note_content');
        $rest = CommonService::accMe($sys_num, "同步回复信息", $note_content, '', 1,$request->get('session_token')['admin_groupnew'], $request->get('session_token')['admin_acc'],$request->get('session_token')['admin_acc']);
        if($rest){
        	return $this->success('操作成功'); exit;
    	}else{
    		return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
    	}
    }



    /**
     * 发送列表
     * @param phone 电话
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月17日下午3:19:14
     */
    public function sendList (Request $request)
    {
    	$input = $request->all();
    	$list = SmsService::getSendList($input);
    	if($list['list']){
    		return $this->success('获取成功', $list); exit;
    	}else{
    		return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$list);exit;
    	}

    }

    /**
     * 获取回复信息
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月17日下午4:30:48
     */
    public function getReSmsByphone(Request $request){
    	if(!$request->filled('phones')){
    		return $this->error('参数错误无phones', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$phones = array_unique($request->input('phones'));

    	$data = SmsService::getReSmsByphone($phones);
    	if ($data) {
    		return $this->success('获取成功', $data); exit;
    	}else{
    		return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
    	}
    }

    /**
     * 模板列表
     * @param Request $request
     * @author du 2021年8月16日下午5:00:54
     */
    public function afterList (Request $request)
    {
    	$result = AfterSms::where('is_del',1)->get()->toArray();
    	if ($result) {
    		return $this->success('获取成功', $result); exit;
    	}else{
    		return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
    	}
    }

    /**
     * @name  添加短信内容
     * @param title       短信标题
     * @param sms_content 短信内容
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\BlueCity\Core\Controllers\mixed
     * @author du 2021年8月16日下午5:15:09
     */
    public function addSms (Request $request)
    {

    	$checked = $this->checkValue($request->all());
    	if ($checked != 1) {
    		return $this->error($checked, ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$input = $request->only('title','sms_content');

    	$result = SmsService::createAfterSms($input['title'], $input['sms_content'], $request->get('session_token')['id']);

    	if ($result) {
    		$this->insertingLog('添加，','',$input['title'],'短信模板',$request->ip(),$request->get('session_token')['admin_acc']);
    		return $this->success('操作成功'); exit;
    	}else{
    		return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
    	}

    }

    /**
     * @name  删除模板
     * @param id       数据id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\BlueCity\Core\Controllers\mixed
     * @author du 2021年8月16日下午5:17:31
     */
    public function remove (Request $request)
    {
    	if(!$request->filled('id')){
    		return $this->error('参数错误无id', ErrorInc::FAILED_PARAM, []);exit;
    	}

    	$id = intval($request->input('id'));
    	$result = AfterSms::where('id',$id)->first();
    	if($request->get('session_token')['id']!=$result['creact_id'] && $request->get('session_token')['id']!='225'){
    		return $this->error('非本人添加，无权限删除', ErrorInc::MYSQL_FAILED);exit;
    	}
    	$res = AfterSms::where('id', $id)->where('is_del',1)->update(['is_del' => 2]);
    	if ($res) {
    		$this->insertingLog('删除，','',$result['title'],'短信模板',$request->ip(),$request->get('session_token')['admin_acc']);
    		return $this->success('操作成功'); exit;
    	}else{
    		return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
    	}

    }


    /**
     * @name  编辑短信内容
     * @param title       短信标题
     * @param sms_content 短信内容
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed|\Illuminate\Http\JsonResponse
     * @author du 2021年8月16日下午5:43:47
     */
    public function editSms (Request $request)
    {
    	$checked = $this->checkValue($request->all());
    	if ($checked != 1) {
    		return $this->error($checked, ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$input = $request->only('id','title','sms_content');
    	$res = AfterSms::where('id',$input['id'])->value('creact_id');
    	if($request->get('session_token')['id'] !== $res){
    		return $this->error('非本人添加，无权限删除', ErrorInc::MYSQL_FAILED);exit;
    	}
    	$result = AfterSms::where('id', $input['id'])->update([
    			'title'       => $input['title'],
    			'sms_content' => $input['sms_content'],
    			'created_at'  => date("Y-m-d H:i:s")
    	]);
    	if ($result) {
    		$this->insertingLog('编辑，','',$input['title'],'短信模板',$request->ip(),$request->get('session_token')['admin_acc']);
    		return $this->success('操作成功'); exit;
    	}else{
    		return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
    	}
    }

    /**
     * @name  发送短信
     * @param phone 手机号
     * @param content 短信内容
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月16日下午5:40:29
     */
    public function sendSms (Request $request)
    {
    	$checked = $this->checkSendMsg($request->all());
    	if ($checked != 1) {
    		return $this->error($checked, ErrorInc::FAILED_PARAM, []);exit;
    	}
    	if(!$request->filled('phone')){
    		return $this->error('请填写手机号', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	if(!$request->filled('sms_content')){
    		return $this->error('请填写短信内容', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$input = $request->only('phone','sms_content');

    	if(count($input['phone'])<1){
    		return $this->error('请填写手机号', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$type = $request->input('type');
    	if($type == 'sdkb'){
    		$type = 'SuDianPaw';//1;
            $smsType = 1;
    	}elseif($type =='dpaz'){
    		$type = 'DianPingPaw';//2;
            $smsType = 2;
    	}else{
    		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$phone = array_unique($input['phone']);
    	$phone = implode(',',$phone);
    	$ret = CommonService::senSms($phone,$input['sms_content'],$type,'','',$request->get('session_token')['admin_acc']);
    	if($ret>=1){
//    		$phone = explode(',',$phone);
//    		foreach( $phone as $k => $v ){
//    			SmsService::createSmsRecord($input['sms_content'], $v, $request->get('session_token')['admin_acc'],$smsType);
//    		}
    		return $this->success('操作成功'); exit;
    	}else{
    		return $this->error('操作失败',ErrorInc::MYSQL_FAILED);
    	}
    }

    /**
     * 检查数据
     * @param $params
     * @return int|string
     */
    private function checkValue ($params)
    {
    	$message = [
    			'title.required'=> '标题不能为空',
    			'sms_content.required'=> '内容不能为空',
    			'title.max'=> '标题不能超过50个字符',
    			'sms_content.max'=> '短信内容不能超过200个字符',
    	];
    	$rules =[
    			'title' =>'required|max:50',
    			'sms_content'=>'required|max:200',
    	];
    	$Validator = Validator::make($params,$rules,$message);
    	if($Validator->fails()){
    		return $Validator->errors()->first();
    	} else {
    		return 1;
    	}
    }

    /**
     * 检查数据
     * @param $params
     * @return int|string
     */
    private function checkSendMsg ($params)
    {
    	$message = [
    			//'phone.required'=> '标题不能为空',
    			//'phone.regex'   => '手机号格式错误',
    			'sms_content.required'=> '内容不能为空',
    			'sms_content.max'=> '短信内容不能超过200个字符',

    	];

    	$rules =[
    			//'phone' =>'required|max:50|regex:/^1\d{10}$/',
    			'sms_content'=>'required|max:200',
    	];
    	$Validator = Validator::make($params,$rules,$message);
    	if($Validator->fails()){
    		return $Validator->errors()->first();
    	} else {
    		return 1;
    	}
    }

    /**
     * @name 重发短信
     * @param type 1:获取 2：发送
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/23
     */
    public function resetSendsms(Request $request){
        if(!$request->filled('id')||!$request->filled('type')){
    		return $this->error('参数错误无id', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$id = intval($request->input('id'));
        $type = intval($request->input('type'));
        $info = SmsService::getInfoBy('id', $id);
        if($type==1){
            if(!$info){
                return $this->error('无此数据',ErrorInc::MYSQL_FAILED); exit;
            }else{
                return $this->success('获取成功',$info); exit;
            }
          //  dump($info);
        }else{
            if($info['send_type'] == '2'){
                return $this->error('发送失败',ErrorInc::DATA_EXIST);exit;
            }
            $auth = '';
            $username = '';
            $pwd = '';
            $input = $request->all();
            if($info['type'] == '1'){
                $auth = 'SuDianPaw';//1;
            }elseif($info['type'] == '2'){
                $auth = 'DianPingPaw';//2;
            }elseif($info['type'] == '3' || $info['type'] == '0' || $info['type'] == ''){
                return $this->error('短信账号异常请从新添加',ErrorInc::DATA_EMPTY);exit;
            }else{
                $db = new SmsAccount();
                $sms_data = CommonService::getMysqlData($db, ['sms_name'=>$info['type']],['sms_name','sms_password'],[],'first');
                if($sms_data){
                    $username = $sms_data['sms_name'];
                    $pwd = $sms_data['sms_password'];
                }else{
                    return $this->error('短信账号异常请从新添加1',ErrorInc::DATA_EMPTY);exit;
                }
            }
            $ret = CommonService::senSms($input['phone'],$input['sms_content'],$auth,$username,$pwd,$request->get('session_token')['admin_acc']);
            if($ret>=1){
                SmsRecord::where('id',$id)->update(['send_type'=>2]);
//               SmsService::createSmsRecord($input['sms_content'], $input['phone'], $request->get('session_token')['admin_acc'],$smsType);
                return $this->success('发送成功'); exit;
            }else{
                return $this->error('发送失败',ErrorInc::MYSQL_FAILED);exit;
            }
        }


    }
}
