<?php
/*
|--------------------------------------------------------------------------
| 平台管理 (原 “基础数据/平台管理” )
|--------------------------------------------------------------------------
|
| 平台增删改查
|  @author liXiaoLin
|  @Date: 2021/7/24
|  @Time: 15:07
|  @Email: lixiaolin@bluearp.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Platform;

use App\Http\Controllers\BaseController;
use App\Models\Admin;
use App\Models\AdminToken;
use App\Models\Pt;
use App\Services\AdminService;
use App\Services\CommonService;
use App\Services\PlatformService;
use App\Services\RedisService;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Traits\CurdControllerMethod;
use Illuminate\Http\Request;
use BlueCity\Core\Controllers\CoreController as Controller;
use Illuminate\Support\Facades\Input;
use DB;

class PlatformController extends BaseController
{
    public $dataService = null;  // CurdControllerMethod 必备参数
    public $dataFields = ['pt_name', 'sord', 'pt_other','pt_zt', 'model_id', 'p_oname', 'p_paytype', 'three_pd', 'bus_type','cd_ids','gs_bids'];  // 保存和修改时的 fields 参数
    protected $validateRules = [
        'rules'=>[
            'pt_name'=>'required|max:50',
            'sord'=>'required',
            'pt_zt'=>'required|in:1,2',
           // 'bus_type'=>'required|in:1,2',
            'cd_ids'=>'required',
            'gs_bids'=>'required',
        ],
        'messages'=>[
            'in'=>':attribute 选择错误',
            'unique'=>'该 :attribute 已存在'
        ],
        'attributes'=>[
            'pt_name'=>'平台名称',
            'sord'=>'首字母',
            'pt_zt'=>'状态',
          // 'bus_type'=>'业务类型',
            'cd_ids'=>'商品类型',
            'gs_bids'=>'包含品牌',
        ]
    ];

    public function __construct()
    {
        $service = new PlatformService();
        $this->bootWithService($service);
    }

    use CurdControllerMethod;

    /**
     * @api {post} /api/platform/platform 平台管理列表
     * @apiGroup 平台管理
     * @apiName 平台管理列表
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台管理列表
     *
     * @apiParam {String} pt_name  平台名称搜索
     * @apiParam {int} type  类型搜索
     * @apiParam {int} pt_zt  状态 1:启用;2:停用
     * @apiParam {int} three_pd  0:自家;1:第三方
     * @apiParam {int} p_paytype  开票公司
     * @apiParam {int} bus_type  业务类型
     * @apiParam {int} page_size  页大小
     * @apiParam {int} page  页码
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":["file_id":1]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function index(Request $request){
        $searchRequest = Input::all();
        $colums = ['*'];
        $page = Request()->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }
        $pageSize = (int)Request()->input('page_size', 20);
        $session = $request->get('session_token');
        $result = $this->dataService->search($searchRequest, $colums, $page, $pageSize,$session);
        $data = $this->dataService->formatPageContent($request->input('token'), $request->input('Pri_id'), $result);
        $list = CommonService::dataToArray($data['list']);

        $data['pt_type'] = PlatformService::getPtType();

        if ($list) {
            $data['p_paytype'] = PlatformService::getInvoiceType();//获取发票方
            return $this->success('获取成功', $data);
        } else {
            $page = [
                'count' => 0,
                'allPage' =>0,
                'page_size'=>$pageSize,
                'page' =>1
            ];
            $data['page'] = $page;
            $data['list'] = [];

            return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $data);
        }
    }


    /**
     * @name 短信内容图片
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/4/28
     */
    public function template (Request $request)
    {
        $label = [
            ['tem_name' => '验证码', 'tem_ide' => '$shr_code','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_08.jpg'],////
            ['tem_name' => '门店名称', 'tem_ide' => '$shr_code','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_13.jpg'],////
            ['tem_name' => '门店联系人', 'tem_ide' => '$shr_code','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_12.jpg'],////
            ['tem_name' => '门店电话', 'tem_ide' => '$phone','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_10.jpg'],
       //
            ['tem_name' => '门店地址', 'tem_ide' => '$phone','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_11.jpg'],
       //
            ['tem_name' => '客户姓名', 'tem_ide' => '$shr_name','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_01.jpg'],
            ['tem_name' => '客户电话', 'tem_ide' => '$shr_phone','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_02.jpg'],/////

            ['tem_name' => '平台单号', 'tem_ide' => '$order_number','img_url' => 'http://zptz.bluearp.com/image/lableimg/sms_temp_img_06.jpg'],
            ];

        if ($label != []) {
            return $this->success('获取成功',$label);exit;
        }
    }



    /**
     * @api {post} /api/platform/platform 平台添加
     * @apiGroup 平台管理
     * @apiName 平台添加
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台添加
     *
     * @apiParam {String} pt_name   平台名称
     * @apiParam {int} type         类型
     * @apiParam {int} pt_zt        状态 1:启用;2:停用
     * @apiParam {int} three_pd     平台类型0:自家;1:第三方
     * @apiParam {int} p_paytype    开票公司
     * @apiParam {int} bus_type     业务类型
     * @apiParam {int} sord         别名
     * @apiParam {int} pt_other     备注
     * @apiParam {int} model_id
     * @apiParam {int} p_oname      首字母
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息return $this->error('数据已存在', ErrorInc::REPEAT_SUBMIT);
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":["file_id":1]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */

    private function _beforeStore($request){
        $res = Pt::where("pt_name",$request->input('pt_name'))->value('id');
        if($res){
            return $this->error('平台名称已存在', ErrorInc::REPEAT_SUBMIT);
        }
        return false;
    }
    private function _setStore($data) {
        return $this->_setData($data);
    }
    private function _beforeUpdate($request,$id){
        $res = Pt::where("pt_name",$request->input('pt_name'))->where('id','!=',$id)->value('id');
        if($res){
            return $this->error('平台名称已存在', ErrorInc::REPEAT_SUBMIT);
        }
        return false;
    }
    private function _setUpdate($data) {
        return $this->_setData($data);
    }

    private function _setData($data) {
        unset($data['type']);
        unset($data['token']);
        unset($data['Login_id']);
        unset($data['Pri_id']);
        $data['model_id'] = 0;
        $session = Request()->get('session_token');
        $data['company_id'] = Request()->input('company_id')??$session['company_id'];

        if(is_array($data['cd_ids'])){
            $data['cd_ids'] = implode(',', $data['cd_ids']);
        }
        if(is_array($data['gs_bids'])){
            $data['gs_bids'] = implode(',', $data['gs_bids']);
        }
        $data['three_pd'] = intval(Request()->input('three_pd'));

        return $data;
    }

    private function _afterStore($data) {

        $request = new Request();
        $data = CommonService::dataToArray($data);
        /*--------------------------------------------添加指定用户平台权限开始--------------------------------------------*/
        $default_addptId = ['1','2'];
        $default_addptId[] = Request()->get('session_token')['id'];
        $admin_add = AdminService::getAdmins(['id_searchin'=>$default_addptId],['id','admin_pt_id']);
        foreach ($admin_add as $key => $val) {
            $admin_pt_id = trim($val['admin_pt_id'],',');
            $admin_pt_id .=",".$data['id'];
            Admin::where("id",$val['id'])->update(['admin_pt_id'=>$admin_pt_id]);
            $k = 'Login'.$val['id'];
            $token = AdminToken::where("at_adminid",$val['id'])->first();
            if($token){
                $token = CommonService::dataToArray($token);
                $token['at_permissions'] = json_decode($token['at_permissions'],true);
                $token['at_perm'] = json_decode($token['at_perm'],true);
                unset($token['at_perm']);
                $token['at_permissions']['admindata']['admin_pt_id'] = $admin_pt_id;
                AdminToken::where("at_adminid",$val['id'])->update(['at_permissions'=>json_encode($token['at_permissions'])]);
                RedisService::redisSet($k, json_encode($token));
            }
        }
        /*--------------------------------------------添加指定用户平台权限结束--------------------------------------------*/
       // PlatformService::getAll(false);


        $this->insertingLog("添加，","","添加平台：".Request()->input('pt_name'),"平台管理",Request()->ip(), Request()->get('session_token')['admin_acc']);
    }

    private function _afterUpdate($data, $beforeData) {
        PlatformService::getAll(false);
        $this->insertingLog("编辑平台","","编辑平台(id)：".$data['id'],"平台管理",Request()->ip(), Request()->get('session_token')['admin_acc']);
    }

    /**
     * @api {post}  /api/platform/platform/create 平台添加界面接口
     * @apiGroup 平台管理
     * @apiName 平台添加界面接口
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台添加界面接口
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":["file_id":1]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function create()
    {
        $invoiceType = PlatformService::getInvoiceType();//获取发票方
        $BusType = PlatformService::getBusType();//获取业务类型
        $states = PlatformService::getStates();//获取状态
        $pdNames = PlatformService::getPdName();//获取是否自营

        return $this->success('返回成功', ['invoiceType'=>$invoiceType, 'pdNames'=>$pdNames, 'BusType'=>$BusType, 'states'=>$states]);
    }

    /**
     * @api {post}  /api/platform/platform/edit 平台修改界面接口
     * @apiGroup 平台管理
     * @apiName 平台修改界面接口
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台修改界面接口
     *
     * @apiParam {int} id  平台ID
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":["file_id":1]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */

    public function edit(Request $request)
    {
        $id = $request->input('id');
        $entity = $this->dataService->find($id);
        $invoiceType = PlatformService::getInvoiceType();//获取发票方
        $BusType = PlatformService::getBusType();//获取业务类型
        $states = PlatformService::getStates();//获取状态
        $pdNames = PlatformService::getPdName();//获取是否自营

        return $this->success('返回成功', ['entity'=>$entity, 'pdNames'=>$pdNames, 'invoiceType'=>$invoiceType , 'BusType'=>$BusType, 'states'=>$states]);
    }

    /**
     * @api {post} /api/platform/platform/update 平台修改保存
     * @apiGroup 平台管理
     * @apiName 平台修改保存
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台修改保存
     *
     * @apiParam {int} id           要修改的平台ID
     * @apiParam {String} pt_name   平台名称
     * @apiParam {int} type         类型
     * @apiParam {int} pt_zt        状态 1:启用;2:停用
     * @apiParam {int} three_pd     平台类型0:自家;1:第三方
     * @apiParam {int} p_paytype    开票公司
     * @apiParam {int} bus_type     业务类型
     * @apiParam {int} sord         别名
     * @apiParam {int} pt_other     备注
     * @apiParam {int} model_id
     * @apiParam {int} p_oname      首字母
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":["file_id":1]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */

    /**
     * @api {post} /api/platform/platform/delete 平台删除
     * @apiGroup 平台管理
     * @apiName 平台删除
     * @apiVersion 1.0.0
     *
     * @apiDescription 平台删除
     *
     * @apiParam {int} id  平台ID
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":["file_id":1]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */

    /**
     * @name  预充值
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/4/28
     */
public function prerecharge(Request $request){
    $input = $request->all();
    $id = intval($request->input('id'));
    if(!$id){
        return $this->error('参数错误，ID必传', ErrorInc::FAILED_PARAM);
    }
    $exist = PlatformService::getFieldsById($id,['pt_prepamount','pt_warnuserid']);
    $type = $input['type'];//1:获取数据 2：更新数据；
    //print_r($exist);
    if($type==1){
        if($exist['pt_prepamount']){
            $data = DB::table('pt_relation')->where('ptj_id',$id)->first();
            $data['pt_prepamount'] = $exist['pt_prepamount'];
            $data['pt_warnuserid'] = $exist['pt_warnuserid'];
            return $this->success('获取成功',$data);
        }else{
            return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);exit;
        }
    }else{
        $checkKey = CommonService::checkKey(['id','type','pt_prepamount','pt_warnuserid','ptqc_dispamount','ptqc_receamount','ptqd_dispamount','ptqd_receamount','ptcd_dispamount','ptcd_receamount','pthd_dispamount','pthd_receamount','pttc_dispamount','pttc_receamount','ptdtc_dispamount','ptdtc_receamount','ptcj_dispamount','ptcj_receamount'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $nowdate = date('Y-m-d H:i:s');
        DB::beginTransaction();
        $pt_warnamount = $input['pt_prepamount']*0.3;
        $ret = Pt::where('id',$id)->update(['pt_prepamount'=>$input['pt_prepamount'],'pt_warnuserid'=>$input['pt_warnuserid'],'update_time'=>$nowdate,'pt_warnamount'=>$pt_warnamount]);
        $arr = ['ptqc_dispamount'=>$input['ptqc_dispamount'],'ptqc_receamount'=>$input['ptqc_receamount'],'ptqd_dispamount'=>$input['ptqd_dispamount'],'ptqd_receamount'=>$input['ptqd_receamount'],'ptcd_dispamount'=>$input['ptcd_dispamount'],'ptcd_receamount'=>$input['ptcd_receamount'],'pthd_dispamount'=>$input['pthd_dispamount'],'pthd_receamount'=>$input['pthd_receamount'],'pttc_dispamount'=>$input['pttc_dispamount'],'pttc_receamount'=>$input['pttc_receamount'],'ptdtc_dispamount'=>$input['ptdtc_dispamount'],'ptdtc_receamount'=>$input['ptdtc_receamount'],'ptcj_dispamount'=>$input['ptcj_dispamount'],'ptcj_receamount'=>$input['ptcj_receamount'],'updata_time'=>$nowdate];
        if($exist['pt_prepamount']){
            $res = DB::table('pt_relation')->where('ptj_id',$id)->update($arr);
        }else{
            $arr['ptj_id'] = $id;
            $res = DB::table('pt_relation')->insert($arr);
        }
        if($ret && $res){
            DB::commit();
            $this->insertingLog("预充值","","编辑平台(id)：".$id.'预充值金额'.$exist['pt_prepamount'].'->'.$input['pt_prepamount'],"平台管理",$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功');exit;
        }else{
            DB::rollback();
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }

    }

}


}
