<?php
/**
 * Created by PhpStorm.
 * User: wuzhenke
 * Date: 2018/11/16
 * Time: 11:17
 */

namespace App\Http\Controllers\Web\Company;

use Aix\Pay\Data\PayOrder;
use App\Exceptions\ResponseException;
use App\Http\Controllers\Web\WebBaseController;
use App\Models\Jobs;
use App\Models\Promotion;
use App\Repositories\JobsRepository;
use App\Repositories\MemberHandselRepository;
use App\Repositories\MemberLogRepository;
use App\Repositories\MembersChargeLogRepository;
use App\Repositories\PromotionRepository;
use App\Repositories\QueueAutoRefreshRepository;
use App\Services\Common\MembersSetmealService;
use App\Services\Common\OrderService;
use App\Services\Common\PaymentService;
use App\Services\Common\PayService;
use App\Services\Common\SetmealIncrementsService;
use App\Services\Common\SetmealService;
use App\Services\Company\CompanyService;
use App\Services\Company\CompanyTplService;
use App\Services\Company\ComplaintConsultantService;
use App\Services\Company\ServiceService;
use App\Services\Person\MemberPointService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class ServiceController extends WebBaseController
{

    protected $serviceService;
    protected $membersSetmealService;
    protected $payService;
    protected $setmealService;
    protected $memberPointService;
    protected $orderService;
    protected $memberLogRepository;
    protected $memberHandselRepository;
    protected $membersChargeLogRepository;
    protected $paymentService;
    protected $setmealIncrementsService;
    protected $companyService;
    protected $queueAutoRefreshRepository;
    protected $jobsRepository;
    protected $promotionRepository;
    protected $companyTplService;
    protected $complaintConsultantService;

    /**
     * ServiceController constructor.
     * @param $serviceService
     * @param $membersSetmealService
     * @param $payService
     * @param $setmealService
     * @param $memberPointService
     * @param $orderService
     * @param $memberLogRepository
     * @param $memberHandselRepository
     * @param $membersChargeLogRepository
     * @param $paymentService
     * @param $setmealIncrementsService
     * @param $companyService
     * @param $queueAutoRefreshRepository
     * @param $jobsRepository
     * @param $promotionRepository
     */
    public function __construct(ServiceService $serviceService, PromotionRepository $promotionRepository, JobsRepository $jobsRepository, QueueAutoRefreshRepository $queueAutoRefreshRepository, CompanyService $companyService, SetmealIncrementsService $setmealIncrementsService, PaymentService $paymentService, MembersChargeLogRepository $membersChargeLogRepository, MemberHandselRepository $memberHandselRepository, MemberLogRepository $memberLogRepository, OrderService $orderService, MemberPointService $memberPointService, MembersSetmealService $membersSetmealService, PayService $payService, SetmealService $setmealService, CompanyTplService $companyTplService, ComplaintConsultantService $complaintConsultantService)
    {
        $this->serviceService = $serviceService;
        $this->membersSetmealService = $membersSetmealService;
        $this->payService = $payService;
        $this->setmealService = $setmealService;
        $this->memberPointService = $memberPointService;
        $this->orderService = $orderService;
        $this->memberLogRepository = $memberLogRepository;
        $this->memberHandselRepository = $memberHandselRepository;
        $this->membersChargeLogRepository = $membersChargeLogRepository;
        $this->paymentService = $paymentService;
        $this->setmealIncrementsService = $setmealIncrementsService;
        $this->companyService = $companyService;
        $this->queueAutoRefreshRepository = $queueAutoRefreshRepository;
        $this->jobsRepository = $jobsRepository;
        $this->promotionRepository = $promotionRepository;
        $this->companyTplService = $companyTplService;
        $this->complaintConsultantService = $complaintConsultantService;
    }

    /**我的套餐
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $user = auth('web-company')->user();//企业信息
        $res = $this->serviceService->index($user);
        return view('app.company.service.index', $res);
    }


    public function setmealDetail(Request $request)
    {
        $user = auth('web-company')->user();//企业信息
        $res = $this->serviceService->setmealDetail($request->all(), $user);
        return view('app.company.service.setmeal_detail', $res);
    }

    /**积分任务
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function points()
    {
        $user = auth('web-company')->user();
        $res = $this->serviceService->points($user);
        return view('app.company.service.points', $res);
    }

    /**积分明细
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function pointsDetail(Request $request)
    {
        $user = auth('web-company')->user();
        $type = $request->type?$request->type:1;
        $res = $this->serviceService->pointsDetail(3, $user);
        return view('app.company.service.points_detail', $res);
    }

    /**套餐升级
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \App\Exceptions\ResponseException
     */
    public function setmealAdd($id)
    {
        $user = auth('web-company')->user();
        if (!$id) {
            throw new ResponseException('请选择正确的套餐!', '', 404);
        }
        $setmeal = $this->serviceService->setmealAdd($id, $user);
        return view('app.company.service.setmeal_add', $setmeal);
    }

    /**套餐弹窗
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function paySetmeal()
    {
        $user = auth('web-company')->user();
        $mysetmeal = $this->membersSetmealService->getSetmealByUid($user->id, $user->utype);
        if (config('aix.companyset.setmeal_com.setmeal_com_set.is_superposition') == 0 && config('aix.companyset.setmeal_com.setmeal_com_set.is_superposition_time') == 0) {   //项目和时间都不叠加
            $tip = '您当前是【' . $mysetmeal->setmeal_name . '】重新开通套餐<br /><span class="font_yellow">1. 原有套餐资源以新开套餐资源为准;</span><br /><span class="font_yellow">2. 原有会员服务时长以新开套餐时长为准;</span><br />确定要重新开通套餐吗?';
        } elseif (config('aix.companyset.setmeal_com.setmeal_com_set.is_superposition') == 0 && config('aix.companyset.setmeal_com.setmeal_com_set.is_superposition_time') == 1) { //项目不叠加时间叠加
            $tip = '您当前是【' . $mysetmeal->setmeal_name . '】重新开通套餐<br /><span class="font_yellow">您的原套餐资源会被新开通的套餐资源覆盖</span><br />确定要重新开通套餐吗?';
        } elseif (config('aix.companyset.setmeal_com.setmeal_com_set.is_superposition') == 1 && config('aix.companyset.setmeal_com.setmeal_com_set.is_superposition_time') == 0) { //项目叠加时间不叠加
            $tip = '您当前是【' . $mysetmeal->setmeal_name . '】重新开通套餐<br /><span class="font_yellow">您的会员服务时长将以新开套餐服务时长为准</span><br />确定要重新开通套餐吗?';
        } else {
            $tip = '您当前是【' . $mysetmeal->setmeal_name . '】重新开通套餐<br /><span class="font_yellow">您的套餐资源和会员时长将叠加</span><br />确定要重新开通套餐吗?';
        }
        return response()->json(['status' => 1, 'data' => ['html' => view('app.company.ajax.ajax_warning', ['tip' => $tip])->render()]]);
    }

    /**会员套餐
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ResponseException
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function setmealAddSave(Request $request)
    {
        $user = auth('web-company')->user();
        //检查未处理订单数
        $order_pay_type = 1;
        $payment_name = $request->input('payment_name', '');
        $pay_type = $request->input('points', '');
        $setmeal_id = $request->input('project_id', 0);
        $is_deductible = $request->input('is_deductible', 0);

        if ($payment_name == 'wechat') {
            $type = 'scan';
        } elseif ($payment_name == 'alipay') {
            $type = 'web';
        } elseif ($payment_name == 'offline') {
            $is_deductible=0;
            $type = 'pay';
        }

        if ($is_deductible == 0) {
            $deductible = 0;
        } else {
            $deductible = $request->input('deductible', '');
        }
        $amount = $request->input('amount', '');//应当付款价格
        if ($amount == 0) {
            $pay_type = 'points';
        }
        if ($deductible>0) {
            $m_amount = floatval($deductible/config('aix.companyset.points.points_set.payment_rate')); //积分充值比例
        } else {
            $m_amount =0;//应该减去的钱
        }

        if ($setmeal_id == 0 || $setmeal_id==1) {
            throw new ResponseException(AjaxError("请选择套餐",0));
        }
        $setmealInfo = $this->setmealService->getSetmealOne($setmeal_id);//套餐详情

        if ($setmealInfo->apply==0){
            throw new ResponseException(AjaxError("改套餐不可购买",0));
        }
        $mypoints = $this->memberPointService->getPoints($user->id, $user->utype);

        $amount = $setmealInfo->expense;//套餐的价格
        $price=$amount-$m_amount; //套餐-积分兑换的钱

        $price=round($price, 2); //去小数点


        $service_need_points = round($amount * config('aix.companyset.points.points_set.payment_rate'));
        if (!config('aix.companyset.setmeal_com.setmeal_com_set.setmeal_by_points')) {
            $is_deductible = 0;
            $deductible = 0;
            $pay_type = 'cash';
        }
        if ($pay_type == 'points') {
            DB::beginTransaction();
            try {
                if ($mypoints->points < $service_need_points) {
                    throw new \Exception('积分不足,请使用其他方式支付!');
                }
                $set_setmeal = $this->serviceService->setMembersSetmeal($user, $setmeal_id);
                if (!$set_setmeal['status']) {
                    throw new \Exception($set_setmeal['msg']);
                }
                $description = '购买服务:' . $setmealInfo->setmeal_name . ';积分支付:' . $service_need_points . "积分";
                $order = $this->orderService->addOrder($user, 1, $setmealInfo->expense, 0, $service_need_points, $setmealInfo->setmeal_name, 'points', '积分支付', $description, 2, 0, $setmeal_id, time(), '');
                if (!$order) {
                    throw new \Exception('生成订单失败!');
                }
                $oid = $this->payService->getTradeNo($order->id);//订单号
                if (!$this->serviceService->updateOid($order->id, $oid)) {
                    throw new \Exception('生成订单号失败!');
                }
                //生成会员日志
                $this->memberLogRepository->createLog($user, 9001, [$oid, '积分支付','']);
                if (false === $p_rst = $this->memberPointService->reportDeal($user->id, $user->utype, 2, $service_need_points)) {
                    throw new \Exception('修改会员积分失败!');
                } else {
                    $handsel['uid'] = $user->id;
                    $handsel['utype'] = $user->utype;
                    $handsel['htype'] = 'points_buy_setmeal';
                    $handsel['htype_cn'] = '购买增值包:' . $setmealInfo->setmeal_name;
                    $handsel['operate'] = 2;
                    $handsel['points'] = $service_need_points;
                    if (!$this->memberHandselRepository->addNew($handsel)) { //添加积分操作记录
                        throw new \Exception('添加积分操作记录失败!');
                    }
                    $notes = date('Y-m-d H:i:s', time()) . "通过积分兑换成功开通{ $setmealInfo->setmeal_name}";

                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                return response()->json(['status' => 0, 'msg' => $e->getMessage()]);
            }
            return response()->json(['status' => 1, 'data' => $oid]);
        } else {
            if ($is_deductible == 1 && $mypoints->points < $deductible) {
                throw new ResponseException('积分不足,请使用其他方式支付!');
            }
            if ($is_deductible == 1 && $deductible > 0) {
                $description = $setmealInfo->setmeal_name . ';积分抵扣:' . $deductible . '积分';
            }
            if ($deductible > 0 && $is_deductible) {
                $amount = $amount - floatval($deductible / config('aix.companyset.points.points_set.payment_rate'));
            }
            $paysetarr['ordtotal_fee'] = $price;
            $payment = $this->paymentService->returnPayment($payment_name);
            $description = '购买服务:' . $setmealInfo->setmeal_name . ';' . $payment->name . $paysetarr['ordtotal_fee'];

            if ($deductible > 0 && $is_deductible == 1) {
                $description .= ';积分支付:' . $deductible . '积分';
            }
            $params = [
                'setmeal_id'=>$setmealInfo->id,
                'setmeal_name'=>$setmealInfo->setmeal_name,
                'company_id'=>$user->id,
                'utype'=>$user->utype,
                'companyname'=>$user->companyname,
                'amount'=>$paysetarr['ordtotal_fee'],
                'points'=>$deductible,
                'payment'=>$payment_name,
                'username'=>$user->username,
                'subsite_id'=>$user->subsite_id,
            ];
            $insert_id = $this->orderService->addOrder($user, 1, $price, $paysetarr['ordtotal_fee'], $deductible, $setmealInfo->setmeal_name, $payment_name, $payment->name, $description, 1, $deductible, $setmeal_id, 0, serialize($params));
            $tradeNo = $this->payService->getTradeNo($insert_id->id);
            if (!$this->serviceService->updateOid($insert_id->id, $tradeNo)) {
                throw new ResponseException('生成订单号失败');
            }

            $payOrder = new PayOrder();
            $payOrder->trade_no = $tradeNo;
            $payOrder->subject = '购买' . $setmealInfo->setmeal_name;
            $payOrder->detail = $description;
            $payOrder->price = $price;
            $payOrder->callback = "App\Services\Common\OrderService.updateCompany";
            $payOrder->return_url = route('service.order.index');
            $result = $this->payService->pay($payment_name, $type, $payOrder);
            if ($payment_name == 'wechat') {
                return response()->json([
                    'status' => 1,
                    'tradeCode' => get_qrcode_html($result->code_url),
                    'tradeNo' => $tradeNo,
                ]);
            } elseif ($payment_name =='alipay') {
                return $result;
            } else {
                return response()->json([
                    'status'=>1,
                    'tradeNo'=>$tradeNo,
                    'url'=>route("service.order.detail",['id'=>$insert_id->id]),
                ]);
            }
        }
    }

    /**订单状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkOrderStatus(Request $request)
    {
        $tradeNo = $request->tradeNo;
        if (!$tradeNo) {
            return response()->json(['status' => 0, 'msg' => "订单号错误!"]);
        }
        return $this->orderService->getOrderbyTradeNo($tradeNo);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function paySetmealStatus()
    {
        $tip = '请在新打开的支付页面完成付款';
        $description = '付款完成前请不要关闭此窗口,付款后请根据您的情况点击下面的按钮,如果在支付中遇到问题请到<a target="_blank" href="">帮助中心</a>。';
        return response()->json(['status' => 1, 'html' => view('app.company.ajax.ajax_warning', ['tip' => $tip, 'description' => $description])->render()]);
    }

    /**增值服务
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function increment()
    {
        $res = $this->serviceService->increment(auth('web-company')->user());
        return view('app.company.increment.index', $res);
    }

    /**各增值包
     * @param Request $request
     * @param $cat
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws ResponseException
     */
    public function incrementAdd(Request $request, $cat)
    {
        switch ($cat) {
            case 'download_resume':
            case 'sms':
            case 'jobs':
            case 'jobfair_num':
                $display_tpl = "resume_sms";
                break;
            case 'stick':
            case 'emergency':
                $display_tpl = 'stick_emergency';
                break;
            case 'tpl':
                $display_tpl = 'tpl';
                break;
            case 'auto_refresh_jobs':
                $display_tpl = 'auto_refresh_jobs';
                break;
            default:
                throw new ResponseException('参数错误');
                break;
        }
        $res = $this->serviceService->incrementAdd($cat, $request->all());
        return view("app.company.increment.increment_add_{$display_tpl}", $res);
    }

    /**增值服务 === 提示框内容
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function confirmPayIncrement()
    {
        $user = auth('web-company')->user();
        $res = $this->serviceService->confirmPayIncrement($user);
        return response()->json(['status'=>1, 'msg'=>'success','data'=>['html'=>view('app.company.ajax.ajax_warning', $res)->render()]]);
    }

    /**增值服务保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function incrementPaySave(Request $request)
    {
        $service_type = $request->input('service_type', '');
        if (!$service_type) {
            return response()->json(['status'=>0,'msg'=>"参数错误"]);
        }
        switch ($service_type) {
            case 'download_resume':
                $fun = 'DownloadResume';
                break;
            case 'sms':
                $fun = 'Sms';
                break;
            case 'jobs':
                $fun = 'Jobs';
                break;
            case 'jobfair_num':
                $fun = 'JobfairNum';
                break;
            case 'stick':
                $fun = 'Stick';
                break;
            case 'emergency':
                $fun = 'Emergency';
                break;
            case 'tpl':
                $fun = 'Tpl';
                break;
            case 'auto_refresh_jobs':
                $fun = 'AutoRefreshJobs';
                break;
        }
        $func_name = "increment".$fun;
        $incrment_arr = ['download_resume','jobs','jobfair_num','sms','stick','emergency','tpl','auto_refresh_jobs'];
        if (!in_array($service_type, $incrment_arr)) {
            return response()->json(['status'=>0,'msg'=>"参数错误"]);
        } else {
            return $this->$func_name($request);
        }
    }

    /**简历包
     * @param $request
     * @return array|\Illuminate\Http\JsonResponse
     * @throws ResponseException
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    protected function incrementDownloadResume($request)
    {
        $cat = $request->input('service_type', 'download_resume');
        $order_pay_type = 6;
        $payment_name = $request->input('payment_name', '');
        $pay_type = $request->input('pay_type', 'points');
        $project_id = $request->input('project_id', 0);
        $is_deductible = $request->input('is_deductible', 0);
        if ($is_deductible==0) {
            $deductible = 0;
        } else {
            $deductible = $request->input('deductible', 0);
        }
        $amount = floatval($request->input('amount', 0));
        if ($amount==0) {
            $pay_type = 'points';
        }
        if ($project_id==0) {
            return response()->json(['status'=>0, 'msg' => '请选择增值包套餐!']);
        }
        $user = auth('web-company')->user();
        $my_setmeal =  $this->membersSetmealService->getUserSetmeal($user, '1');    //会员套餐信息
        $my_point = $this->memberPointService->getPoints($user->id, 1);  //获取会员积分信息
        $increment_info = $this->setmealIncrementsService->getIncrement($project_id);       //获取所选简历增值包信息
        $my_discount = $this->setmealIncrementsService->getIncrementDiscountByArray($cat, $my_setmeal);     //套餐折扣
        $service_need_cash = $my_discount > 0 ?round($increment_info->price*$my_discount/10, 2):$increment_info->price; //增值包套餐金额
        if ($pay_type=='points') {      //积分支付
            $service_need_points = round($service_need_cash*config('aix.companyset.points.points_set.payment_rate'));   //增值包套餐所需积分
            if ($my_point->points < $service_need_points) {
                return response()->json(['status'=>0, 'msg' =>'积分不足,请使用其他方式支付!']);
            }
            //操作事务开始
            DB::beginTransaction();
            try {
                //会员套餐添加增值包数量
                $setmeal_rst = $this->membersSetmealService->actionUserSetmeal(array('uid'=>$user->id, 'utype'=>1), $cat, 1, $increment_info->value);
                if (!$setmeal_rst) {
                    throw new \Exception('修改会员套餐失败!');
                }
                $description1 = '购买服务:'.$increment_info->name.';积分支付:'.$service_need_points.'积分';
                $stime = time();
                //添加订单信息
                $order = $this->orderService->addOrder($user, $order_pay_type, $service_need_cash, 0, $service_need_points, $increment_info->name, $payment_name, '积分支付', $description1, 2, 0, $project_id, $stime, '', '专享'.$my_discount.'折优惠');
                if (!$order) {
                    throw new \Exception('生成订单失败!');
                }
                $oid = $this->payService->getTradeNo($order->id);//订单号
                if (!$this->serviceService->updateOid($order->id, $oid)) {
                    throw new \Exception('生成订单号失败!');
                }
                //会员日志:添加创建增值服务订单日志
                $log_rst1 = $this->serviceService->writeMembersLog($user, '9001', [$oid,'积分兑换','']);

                //修改会员积分
                if (false === $p_rst = $this->memberPointService->reportDeal($user->id, $user->utype, 2, $service_need_points)) {
                    throw new \Exception('修改会员积分失败!');
                } else {
                    $handsel['uid'] = $user->id;
                    $handsel['utype'] = $user->utype;
                    $handsel['htype'] = 'increment_download_resume';
                    $handsel['htype_cn'] = '购买增值包:' . $increment_info->name;
                    $handsel['operate'] = 2;
                    $handsel['points'] = $service_need_points;
                    if (!$this->memberHandselRepository->addNew($handsel)) { //添加积分操作记录
                        throw new \Exception('添加积分操作记录失败!');
                    }
                    $notes = date('Y-m-d H:i:s', time()) . "通过积分兑换成功开通{ $increment_info->name}";

                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                return response()->json(['status'=>0, 'msg' => $e->getMessage()]);
            }
            return response()->json(['status'=>1, 'msg' => '积分兑换成功!','data'=>$oid]);
        } else {
            if ($is_deductible==1 && $my_point->points<$deductible) {
                return response()->json(['status'=>1, 'msg' => '积分不足,请使用其他方式支付!']);
            }
            return $this->callCashPay($my_setmeal, $my_point, $increment_info, $order_pay_type, $payment_name, $service_need_cash, $is_deductible, $deductible, '', '', 0, $project_id, '专享'.$my_discount.'折优惠');
        }
    }

    /**短信包
     * @param $request
     * @return array|\Illuminate\Http\JsonResponse
     * @throws ResponseException
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    protected function incrementSms($request)
    {
        $cat = $request->input('service_type', 'sms');
        $order_pay_type = 7;
        $payment_name = $request->input('payment_name', '');
        $pay_type = $request->input('pay_type', 'points');
        $project_id = $request->input('project_id', 0);
        $is_deductible = $request->input('is_deductible', 0);
//        dd($request);
        if ($is_deductible==0) {
            $deductible = 0;
        } else {
            $deductible = $request->input('deductible', '');
        }
        $amount = floatval($request->input('amount', ''));
        if ($amount==0) {
            $pay_type = 'points';
        }
        if ($project_id==0) {
            return response()->json(['status'=>0, 'msg' => '请选择增值包套餐!']);
        }
        $user = auth('web-company')->user();
        $my_setmeal =  $this->membersSetmealService->getUserSetmeal($user, '1');    //会员套餐信息
        $my_point = $this->memberPointService->getPoints($user->id, 1);  //获取会员积分信息
        $increment_info = $this->setmealIncrementsService->getIncrement($project_id);       //获取所选简历增值包信息
        $my_discount = $this->setmealIncrementsService->getIncrementDiscountByArray($cat, $my_setmeal);     //套餐折扣
        $service_need_cash = $my_discount > 0 ?round($increment_info->price*$my_discount/10, 2):$increment_info->price; //增值包套餐金额
        if ($pay_type=='points') {      //积分支付
            $service_need_points = round($service_need_cash*config('aix.companyset.points.points_set.payment_rate'));   //增值包套餐所需积分
            if ($my_point->points < $service_need_points) {
                return response()->json(['status'=>0, 'msg' => '积分不足,请使用其他方式支付!']);
            }
            //操作事务开始
            DB::beginTransaction();
            try {
                $companySms = $this->companyService->incSms($user->id, 1, $increment_info->value);
                if (!$companySms) {
                    throw new \Exception('会员短信数量增加失败!');
                }
                $description1 = '购买服务:'.$increment_info->name.';积分支付:'.$service_need_points.'积分';
                $stime = time();
                //添加订单信息
                $order = $this->orderService->addOrder($user, $order_pay_type, $service_need_cash, 0, $service_need_points, $increment_info->name, $payment_name, '积分支付', $description1, 2, 0, $project_id, $stime, '', '专享'.$my_discount.'折优惠');
                if (!$order) {
                    throw new \Exception('生成订单失败!');
                }
                $oid = $this->payService->getTradeNo($order->id);//订单号
                if (!$this->serviceService->updateOid($order->id, $oid)) {
                    throw new \Exception('生成订单号失败!');
                }
                //会员日志:添加创建增值服务订单日志
                $log_rst1 = $this->serviceService->writeMembersLog($user, '9001', [$oid,'积分兑换','']);
                //修改会员积分
                if (false === $p_rst = $this->memberPointService->reportDeal($user->id, $user->utype, 2, $service_need_points)) {
                    throw new \Exception('修改会员积分失败!');
                } else {
                    $handsel['uid'] = $user->id;
                    $handsel['utype'] = $user->utype;
                    $handsel['htype'] = 'increment_download_resume';
                    $handsel['htype_cn'] = '购买增值包:' . $increment_info->name;
                    $handsel['operate'] = 2;
                    $handsel['points'] = $service_need_points;
                    if (!$this->memberHandselRepository->addNew($handsel)) { //添加积分操作记录
                        throw new \Exception('添加积分操作记录失败!');
                    }

                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                return array( 'status'=>0, 'msg' => $e->getMessage());
            }
            return array( 'status'=>1, 'msg' => '积分兑换成功!','data'=>$oid);
        } else {
            if ($is_deductible==1 && $my_point->points<$deductible) {
                return array( 'status'=>0, 'msg' => '积分不足,请使用其他方式支付!');
            }
            return $this->callCashPay($my_setmeal, $my_point, $increment_info, $order_pay_type, $payment_name, $service_need_cash, $is_deductible, $deductible, '', '', 0, $project_id, '专享'.$my_discount.'折优惠');
        }
    }

    protected function incrementJobfairNum($request)
    {
        $cat = $request->input('service_type', 'jobfair_num');
        $order_pay_type = 15;
        $payment_name = $request->input('payment_name', '');
        $pay_type = $request->input('pay_type', 'points');
        $project_id = $request->input('project_id', 0);
        $is_deductible = $request->input('is_deductible', 0);

        if ($is_deductible==0) {
            $deductible = 0;
        } else {
            $deductible = $request->input('deductible', '');
        }
        $amount = floatval($request->input('amount', ''));
        if ($amount==0) {
            $pay_type = 'points';
        }
        if ($project_id==0) {
            return response()->json(['status'=>0, 'msg' => '请选择增值包套餐!']);
        }
        $user = auth('web-company')->user();
        $my_setmeal =  $this->membersSetmealService->getUserSetmeal($user, '1');    //会员套餐信息
        $my_point = $this->memberPointService->getPoints($user->id, 1);  //获取会员积分信息
        $increment_info = $this->setmealIncrementsService->getIncrement($project_id);       //获取所选简历增值包信息
        $my_discount = $this->setmealIncrementsService->getIncrementDiscountByArray($cat, $my_setmeal);     //套餐折扣
        $service_need_cash = $my_discount > 0 ?round($increment_info->price*$my_discount/10, 2):$increment_info->price; //增值包套餐金额
        if ($pay_type=='points') {      //积分支付
            $service_need_points = round($service_need_cash*config('aix.companyset.points.points_set.payment_rate'));   //增值包套餐所需积分
            if ($my_point->points < $service_need_points) {
                return response()->json(['status'=>0, 'msg' => '积分不足,请使用其他方式支付!']);
            }
            //操作事务开始
            DB::beginTransaction();
            try {
                $companySms = $this->membersSetmealService->actionUserSetmeal($user->id, 'jobfair_num', 1, $increment_info->value);
                if (!$companySms) {
                    throw new \Exception('会员招聘会场次数量增加失败!');
                }
                $description1 = '购买服务:'.$increment_info->name.';积分支付:'.$service_need_points.'积分';
                $stime = time();
                //添加订单信息
                $order = $this->orderService->addOrder($user, $order_pay_type, $service_need_cash, 0, $service_need_points, $increment_info->name, $payment_name, '积分支付', $description1, 2, 0, $project_id, $stime, '', '专享'.$my_discount.'折优惠');
                if (!$order) {
                    throw new \Exception('生成订单失败!');
                }
                $oid = $this->payService->getTradeNo($order->id);//订单号
                if (!$this->serviceService->updateOid($order->id, $oid)) {
                    throw new \Exception('生成订单号失败!');
                }
                //会员日志:添加创建增值服务订单日志
                $log_rst1 = $this->serviceService->writeMembersLog($user, '9001', [$oid,'积分兑换','']);
                //修改会员积分
                if (false === $p_rst = $this->memberPointService->reportDeal($user->id, $user->utype, 2, $service_need_points)) {
                    throw new \Exception('修改会员积分失败!');
                } else {
                    $handsel['uid'] = $user->id;
                    $handsel['utype'] = $user->utype;
                    $handsel['htype'] = 'increment_jobfair_num';
                    $handsel['htype_cn'] = '购买增值包:' . $increment_info->name;
                    $handsel['operate'] = 2;
                    $handsel['points'] = $service_need_points;
                    if (!$this->memberHandselRepository->addNew($handsel)) { //添加积分操作记录
                        throw new \Exception('添加积分操作记录失败!');
                    }

                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                return array( 'status'=>0, 'msg' => $e->getMessage());
            }
            return array( 'status'=>1, 'msg' => '积分兑换成功!','data'=>$oid);
        } else {
            if ($is_deductible==1 && $my_point->points<$deductible) {
                return array( 'status'=>0, 'msg' => '积分不足,请使用其他方式支付!');
            }
            return $this->callCashPay($my_setmeal, $my_point, $increment_info, $order_pay_type, $payment_name, $service_need_cash, $is_deductible, $deductible, '', '', 0, $project_id, '专享'.$my_discount.'折优惠');
        }
    }

    /**购买职位增值包
     * @param $request
     * @return array|\Illuminate\Http\JsonResponse
     * @throws ResponseException
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    protected function incrementJobs($request)
    {
        $cat = $request->input('service_type', 'jobs');
        $order_pay_type = 15;
        $payment_name = $request->input('payment_name', '');
        $pay_type = $request->input('pay_type', 'points');
        $project_id = $request->input('project_id', 0);
        $is_deductible = $request->input('is_deductible', 0);

        if ($is_deductible==0) {
            $deductible = 0;
        } else {
            $deductible = $request->input('deductible', '');
        }
        $amount = floatval($request->input('amount', ''));
        if ($amount==0) {
            $pay_type = 'points';
        }
        if ($project_id==0) {
            return response()->json(['status'=>0, 'msg' => '请选择增值包套餐!']);
        }
        $user = auth('web-company')->user();
        $my_setmeal =  $this->membersSetmealService->getUserSetmeal($user, '1');    //会员套餐信息
        $my_point = $this->memberPointService->getPoints($user->id, 1);  //获取会员积分信息
        $increment_info = $this->setmealIncrementsService->getIncrement($project_id);       //获取所选简历增值包信息
        $my_discount = $this->setmealIncrementsService->getIncrementDiscountByArray($cat, $my_setmeal);     //套餐折扣
        $service_need_cash = $my_discount > 0 ?round($increment_info->price*$my_discount/10, 2):$increment_info->price; //增值包套餐金额
        if ($pay_type=='points') {      //积分支付
            $service_need_points = round($service_need_cash*config('aix.companyset.points.points_set.payment_rate'));   //增值包套餐所需积分
            if ($my_point->points < $service_need_points) {
                return response()->json(['status'=>0, 'msg' => '积分不足,请使用其他方式支付!']);
            }
            //操作事务开始
            DB::beginTransaction();
            try {
                $companySms = $this->membersSetmealService->actionUserSetmeal($user->id, 'jobs_meanwhile', 1, $increment_info->value);
                if (!$companySms) {
                    throw new \Exception('会员可发布职位数量增加失败!');
                }
                $description1 = '购买服务:'.$increment_info->name.';积分支付:'.$service_need_points.'积分';
                $stime = time();
                //添加订单信息
                $order = $this->orderService->addOrder($user, $order_pay_type, $service_need_cash, 0, $service_need_points, $increment_info->name, $payment_name, '积分支付', $description1, 2, 0, $project_id, $stime, '', '专享'.$my_discount.'折优惠');
                if (!$order) {
                    throw new \Exception('生成订单失败!');
                }
                $oid = $this->payService->getTradeNo($order->id);//订单号
                if (!$this->serviceService->updateOid($order->id, $oid)) {
                    throw new \Exception('生成订单号失败!');
                }
                //会员日志:添加创建增值服务订单日志
                $log_rst1 = $this->serviceService->writeMembersLog($user, '9001', [$oid,'积分兑换','']);
                //修改会员积分
                if (false === $p_rst = $this->memberPointService->reportDeal($user->id, $user->utype, 2, $service_need_points)) {
                    throw new \Exception('修改会员积分失败!');
                } else {
                    $handsel['uid'] = $user->id;
                    $handsel['utype'] = $user->utype;
                    $handsel['htype'] = 'increment_jobs';
                    $handsel['htype_cn'] = '购买增值包:' . $increment_info->name;
                    $handsel['operate'] = 2;
                    $handsel['points'] = $service_need_points;
                    if (!$this->memberHandselRepository->addNew($handsel)) { //添加积分操作记录
                        throw new \Exception('添加积分操作记录失败!');
                    }

                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                return array( 'status'=>0, 'msg' => $e->getMessage());
            }
            return array( 'status'=>1, 'msg' => '积分兑换成功!','data'=>$oid);
        } else {
            if ($is_deductible==1 && $my_point->points<$deductible) {
                return array( 'status'=>0, 'msg' => '积分不足,请使用其他方式支付!');
            }

            return $this->callCashPay($my_setmeal, $my_point, $increment_info, $order_pay_type, $payment_name, $service_need_cash, $is_deductible, $deductible, '', '', 0, $project_id, '专享'.$my_discount.'折优惠');
        }
    }

    /**职位置顶
     * @param $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ResponseException
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    protected function incrementStick($request)
    {
        $user = auth('web-company')->user();
        $cat = $request->input('service_type', 'stick');
        $order_pay_type = 8;
        $payment_name = $request->input('payment_name', '');
        $pay_type = $request->input('pay_type', 'points');
        $project_id = $request->input('project_id', 0);
        $is_deductible = $request->input('is_deductible', 0);
        $jobs_id = $request->input('jobs_id', 0);
        $form_validate = $request->input('form_validate', false); //支付宝支付是Form 表单提交的,错误信息返回json,不是form的就不进行callback
        if ($is_deductible==0) {
            $deductible = 0;
        } else {
            $deductible = $request->input('deductible', '');
        }
        $amount = floatval($request->input('amount', ''));
        if ($amount==0) {
            $pay_type = 'points';
        }
        if ($project_id==0) {
            return response()->json(['status'=>0, 'msg' => '请选择增值包套餐!']);
        }
        if (!$jobs_id) {
            return response()->json(['status'=>0, 'msg'=>"请选择职位!"]);
        }
        if (!$jobsRes = $this->jobsRepository->findWhere(['id'=>$jobs_id,'company_id'=>$user->id])->first()) {
            return response()->json(['status'=>0,'msg'=>'该职位不存在!']);
        }
        if ($this->jobsRepository->getInfo(['stick'=>1,'id'=>$jobs_id,])) {
            return response()->json(['status'=>0,'msg'=>'该职位已置顶!']);
        }

        $my_setmeal =  $this->membersSetmealService->getUserSetmeal($user, '1');    //会员套餐信息
        $my_point = $this->memberPointService->getPoints($user->id, 1);  //获取会员积分信息
        $increment_info = $this->setmealIncrementsService->getIncrement($project_id);       //获取所选简历增值包信息
        $my_discount = $this->setmealIncrementsService->getIncrementDiscountByArray($cat, $my_setmeal);     //套餐折扣
        $service_need_cash = $my_discount > 0 ?round($increment_info->price*$my_discount/10, 2):$increment_info->price; //智能刷新所需积分
        if ($pay_type=='points') {      //积分支付
            $service_need_points = round($service_need_cash*config('aix.companyset.points.points_set.payment_rate'));   //智能刷新所需积分
            if ($my_point->points < $service_need_points) {
                return response()->json(['status'=>0, 'msg' => '积分不足,请使用其他方式支付!']);
            }
            //操作事务开始
            DB::beginTransaction();
            try {
                $promotionsqlarr['companyid']=$user->id;
                $promotionsqlarr['jobid']=$jobs_id;
                $promotionsqlarr['ptype'] = 1;
                $promotionsqlarr['days']=$increment_info->value;
                $promotionsqlarr['starttime']=time();
                $promotionsqlarr['endtime']=strtotime("{$increment_info->value} day");
                $promotion_insert_id = Promotion::create($promotionsqlarr);
                if (!$promotion_insert_id) {
                    throw new \Exception('职位置顶添加失败!');
                }

//                $refresh_time = $this->jobsRepository->getFires($jobs_id);
                $stick_time = time();
                $this->jobsRepository->update(['stime'=>$stick_time, 'stick'=>1], $jobs_id);
                $params_array = array('days'=>$increment_info['value']);
                $description1 = '购买服务:'.$increment_info->name.';积分支付:'.$service_need_points.'积分';
                $stime = time();
                $params_array['jobs_id'] = $jobs_id;
                //添加订单信息
                $order = $this->orderService->addOrder($user, $order_pay_type, $service_need_cash, 0, $service_need_points, $increment_info->name, $payment_name, '积分支付', $description1, 2, 0, $project_id, $stime, serialize($params_array), '专享'.$my_discount.'折优惠');
                if (!$order) {
                    throw new \Exception('生成订单失败!');
                }
                $oid = $this->payService->getTradeNo($order->id);//订单号
                if (!$this->serviceService->updateOid($order->id, $oid)) {
                    throw new \Exception('生成订单号失败!');
                }
                //会员日志:添加创建增值服务订单日志
                $log_rst1 = $this->serviceService->writeMembersLog($user, '9001', [$oid,'积分兑换','']);
                //修改会员积分
                if (false === $p_rst = $this->memberPointService->reportDeal($user->id, $user->utype, 2, $service_need_points)) {
                    throw new \Exception('修改会员积分失败!');
                } else {
                    $handsel['uid'] = $user->id;
                    $handsel['utype'] = $user->utype;
                    $handsel['htype'] = 'increment_download_resume';
                    $handsel['htype_cn'] = '购买增值包:' . $increment_info->name;
                    $handsel['operate'] = 2;
                    $handsel['points'] = $service_need_points;
                    if (!$this->memberHandselRepository->addNew($handsel)) { //添加积分操作记录
                        throw new \Exception('添加积分操作记录失败!');
                    }

                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                return response()->json(['status'=>0, 'msg' => $e->getMessage()]);
            }
            event_search_update(Jobs::class, (string)$jobs_id, 'update');
            return response()->json(['status'=>1, 'msg' => '积分兑换成功!','data'=>$oid]);
        } else {
            if ($is_deductible==1 && $my_point->points<$deductible) {
                return response()->json(['status'=>0, 'msg' => '积分不足,请使用其他方式支付!!']);
            }
            if ($form_validate){//是否是表单验证的
                //返回之后支付宝再用form 表单再请求一遍
                return response()->json(['status'=>1, 'msg' => '验证成功!']);
            }
            $params['jobs_id'] = $jobs_id;
            $params['days'] = $increment_info['value'];
            $nowtime = time();
            $params['starttime'] = $nowtime;
            for ($i=0; $i < $params['days']*4; $i++) {
                $timespace = 3600*6*$i;
                if ($i+1==$params['days']*4) {
                    $params['endtime'] = $nowtime+$timespace;
                }
            }
            return $this->callCashPay($my_setmeal, $my_point, $increment_info, $order_pay_type, $payment_name, $service_need_cash, $is_deductible, $deductible, '', $params, 0, $project_id, '专享'.$my_discount.'折优惠');
        }
    }

    /**职位紧急
     * @param $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ResponseException
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    protected function incrementEmergency($request)
    {
        $user = auth('web-company')->user();

        $cat = $request->input('service_type', 'emergency');
        $order_pay_type = 9;
        $payment_name = $request->input('payment_name', '');
        $pay_type = $request->input('pay_type', 'points');
        $project_id = $request->input('project_id', 0);
        $is_deductible = $request->input('is_deductible', 0);
        $jobs_id = $request->input('jobs_id', 0);
        $form_validate = $request->input('form_validate', false); //支付宝支付是Form 表单提交的,错误信息返回json,不是form的就不进行callback
        if ($is_deductible==0) {
            $deductible = 0;
        } else {
            $deductible = $request->input('deductible', '');
        }
        $amount = floatval($request->input('amount', ''));
        if ($amount==0) {
            $pay_type = 'points';
        }
        if ($project_id==0) {
            return response()->json(['status'=>0, 'msg' => '请选择增值包套餐!']);
        }
        if (!$jobs_id) {
            return response()->json(['status'=>0, 'msg'=>"请选择职位!"]);
        }
        if (!$jobsRes = $this->jobsRepository->findWhere(['id'=>$jobs_id,'company_id'=>$user->id])->first()) {
            return response()->json(['status'=>0,'msg'=>'该职位不存在!']);
        }
        if ($this->jobsRepository->getInfo(['emergency'=>1,'id'=>$jobs_id,])) {
            return response()->json(['status'=>0,'msg'=>'该职位已紧急!']);
        }
        $my_setmeal =  $this->membersSetmealService->getUserSetmeal($user, '1');    //会员套餐信息
        $my_point = $this->memberPointService->getPoints($user->id, 1);  //获取会员积分信息
        $increment_info = $this->setmealIncrementsService->getIncrement($project_id);       //获取所选简历增值包信息
        $my_discount = $this->setmealIncrementsService->getIncrementDiscountByArray($cat, $my_setmeal);     //套餐折扣
        $service_need_cash = $my_discount > 0 ?round($increment_info->price*$my_discount/10, 2):$increment_info->price; //智能刷新所需积分
        if ($pay_type=='points') {      //积分支付
            $service_need_points = round($service_need_cash*config('aix.companyset.points.points_set.payment_rate'));   //智能刷新所需积分
            if ($my_point->points < $service_need_points) {
                return response()->json(['status'=>0, 'msg' => '积分不足,请使用其他方式支付!']);
            }
            //操作事务开始
            DB::beginTransaction();
            try {
                $promotionsqlarr['companyid']=$user->id;
                $promotionsqlarr['jobid']=$jobs_id;
                $promotionsqlarr['ptype'] = 2;
                $promotionsqlarr['days']=$increment_info->value;
                $promotionsqlarr['starttime']=time();
                $promotionsqlarr['endtime']=strtotime("{$increment_info->value} day");
                $promotion_insert_id = $this->promotionRepository->create($promotionsqlarr);
                if (!$promotion_insert_id) {
                    throw new \Exception('职位紧急添加失败!');
                }

                $this->jobsRepository->update(['emergency'=>1], $jobs_id);
                $params_array = array('days'=>$increment_info['value']);
                $description1 = '购买服务:'.$increment_info->name.';积分支付:'.$service_need_points.'积分';
                $stime = time();
                $params_array['jobs_id'] = $jobs_id;
                //添加订单信息
                $order = $this->orderService->addOrder($user, $order_pay_type, $service_need_cash, 0, $service_need_points, $increment_info->name, $payment_name, '积分支付', $description1, 2, 0, $project_id, $stime, serialize($params_array), '专享'.$my_discount.'折优惠');
                if (!$order) {
                    throw new \Exception('生成订单失败!');
                }
                $oid = $this->payService->getTradeNo($order->id);//订单号
                if (!$this->serviceService->updateOid($order->id, $oid)) {
                    throw new \Exception('生成订单号失败!');
                }
                //会员日志:添加创建增值服务订单日志
                $log_rst1 = $this->serviceService->writeMembersLog($user, '9001', [$oid,'积分兑换','']);
                //修改会员积分
                if (false === $p_rst = $this->memberPointService->reportDeal($user->id, $user->utype, 2, $service_need_points)) {
                    throw new \Exception('修改会员积分失败!');
                } else {
                    $handsel['uid'] = $user->id;
                    $handsel['utype'] = $user->utype;
                    $handsel['htype'] = 'increment_download_resume';
                    $handsel['htype_cn'] = '购买增值包:' . $increment_info->name;
                    $handsel['operate'] = 2;
                    $handsel['points'] = $service_need_points;
                    if (!$this->memberHandselRepository->addNew($handsel)) { //添加积分操作记录
                        throw new \Exception('添加积分操作记录失败!');
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                return response()->json(['status'=>0, 'msg' => $e->getMessage()]);
            }
            event_search_update(Jobs::class, (string)$jobs_id, 'update');
            return response()->json(['status'=>1, 'msg' => '积分兑换成功!','data'=>$oid]);
        } else {
            if ($is_deductible==1 && $my_point->points<$deductible) {
                return response()->json(['status'=>0, 'msg' => '积分不足,请使用其他方式支付!!']);
            }
            if ($form_validate){//是否是表单验证的
                //返回之后支付宝再用form 表单再请求一遍
                return response()->json(['status'=>1, 'msg' => '验证成功!']);
            }
            $params['jobs_id'] = $jobs_id;
            $params['days'] = $increment_info['value'];
            $nowtime = time();
            $params['starttime'] = $nowtime;
            for ($i=0; $i < $params['days']*4; $i++) {
                $timespace = 3600*6*$i;
                if ($i+1==$params['days']*4) {
                    $params['endtime'] = $nowtime+$timespace;
                }
            }
            return $this->callCashPay($my_setmeal, $my_point, $increment_info, $order_pay_type, $payment_name, $service_need_cash, $is_deductible, $deductible, '', $params, 0, $project_id, '专享'.$my_discount.'折优惠');
        }
    }

    /**企业模版
     * @param $request
     * @return ServiceController
     */
    protected function incrementTpl(Request $request)
    {
        $result = $this->companyTplService->incrementTpl(auth('web-company')->user(), $request->all(), $request->route());
        if ($result['code']=='wechat') {
            if ($result['type']=='wap') {
                return $result['tradeCode'];
            } else {
                return json_encode(['tradeCode'=>$result['tradeCode'],'tradeNo'=>$result['tradeNo']]);
            }
        } elseif ($result['code']=='alipay') {
            return $result['tradeCode'];
        } elseif ($result['code']=='offline') {
            return json_encode(['tradeNo'=>$result['tradeNo']]);
        } else {
            if ($result['status']==1) {
                return $this->sendSuccessResponse($result['info']);
            } else {
                return $this->sendErrorResponse($result['info'], '', 400);
            }
        }
    }

    /**智能刷新
     * @param $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ResponseException
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    protected function incrementAutoRefreshJobs($request)
    {
        $cat = $request->input('service_type', 'auto_refresh_jobs');
        $order_pay_type = 12;
        $payment_name = $request->input('payment_name', '');
        $pay_type = $request->input('pay_type', 'points');
        $project_id = $request->input('project_id', 0);
        $is_deductible = $request->input('is_deductible', 0);
        $jobs_id = $request->input('id', 0);
        $form_validate = $request->input('form_validate', false); //支付宝支付是Form 表单提交的,错误信息返回json,不是form的就不进行callback
        if ($is_deductible==0) {
            $deductible = 0;
        } else {
            $deductible = $request->input('deductible', '');
        }
        $amount = floatval($request->input('amount', ''));
        if ($amount==0) {
            $pay_type = 'points';
        }
        if ($project_id==0) {
            return response()->json(['status'=>0, 'msg' => '请选择增值包套餐!']);
        }
        if (!$jobs_id) {
            return response()->json(['status'=>0, 'msg'=>"请选择职位!"]);
        }
        if ($this->queueAutoRefreshRepository->findData(['type'=>1, 'pid'=>$jobs_id])) {
            return response()->json(['status'=>0,'msg'=>'该职位已预约刷新!']);
        }
        $user = auth('web-company')->user();
        $my_setmeal =  $this->membersSetmealService->getUserSetmeal($user, '1');    //会员套餐信息
        if (isExpire($my_setmeal)){
            return response()->json( ['status' => 0, 'msg' => "提醒:您的套餐已到期,请及时到我的套餐处升级套餐!"]);
        }
        $my_point = $this->memberPointService->getPoints($user->id, 1);  //获取会员积分信息
        $increment_info = $this->setmealIncrementsService->getIncrement($project_id);       //获取所选简历增值包信息
        $my_discount = $this->setmealIncrementsService->getIncrementDiscountByArray($cat, $my_setmeal);     //套餐折扣
        $service_need_cash = $my_discount > 0 ?round($increment_info->price*$my_discount/10, 2):$increment_info->price; //智能刷新所需积分
        if ($pay_type=='points') {      //积分支付
            $service_need_points = round($service_need_cash*config('aix.companyset.points.points_set.payment_rate'));   //智能刷新所需积分
            if ($my_point->points < $service_need_points) {
                return response()->json(['status'=>0, 'msg' => '积分不足,请使用其他方式支付!']);
            }
            //操作事务开始
            DB::beginTransaction();
            try {
                //添加自动刷新记录
                $days = $increment_info->value;
                $params_array['days'] = $days;
                $nowtime = time();
                $params_array['days'] = $nowtime;
                $params_array['starttime'] = $nowtime;
                for ($i=0; $i < $days*4; $i++) {
                    $timespace = 3600*6*$i;
                    $this->queueAutoRefreshRepository->create(['uid'=>$user->id,'pid'=>$jobs_id,'type'=>1,'refreshtime'=>$nowtime+$timespace]);
                    if ($i+1==$days*4) {
                        $params_array['endtime'] = $nowtime+$timespace;
                    }
                }
                $params_array['jobs_id'] = $jobs_id;
                $description1 = '购买服务:'.$increment_info->name.';积分支付:'.$service_need_points.'积分';
                $stime = time();
                //添加订单信息
                $order = $this->orderService->addOrder($user, $order_pay_type, $service_need_cash, 0, $service_need_points, $increment_info->name, $payment_name, '积分支付', $description1, 2, 0, $project_id, $stime, serialize($params_array), '专享'.$my_discount.'折优惠');
                if (!$order) {
                    throw new \Exception('生成订单失败!');
                }
                $oid = $this->payService->getTradeNo($order->id);//订单号
                if (!$this->serviceService->updateOid($order->id, $oid)) {
                    throw new \Exception('生成订单号失败!');
                }
                //会员日志:添加创建增值服务订单日志
                $log_rst1 = $this->serviceService->writeMembersLog($user, '9001', [$oid,'积分兑换','']);
                //修改会员积分
                if (false === $p_rst = $this->memberPointService->reportDeal($user->id, $user->utype, 2, $service_need_points)) {
                    throw new \Exception('修改会员积分失败!');
                } else {
                    $handsel['uid'] = $user->id;
                    $handsel['utype'] = $user->utype;
                    $handsel['htype'] = 'increment_download_resume';
                    $handsel['htype_cn'] = '购买增值包:' . $increment_info->name;
                    $handsel['operate'] = 2;
                    $handsel['points'] = $service_need_points;
                    if (!$this->memberHandselRepository->addNew($handsel)) { //添加积分操作记录
                        throw new \Exception('添加积分操作记录失败!');
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                return response()->json(['status'=>0, 'msg' => $e->getMessage()]);
            }
            return response()->json(['status'=>1, 'msg' => '积分兑换成功!','data'=>$oid]);
        } else {
            if ($is_deductible==1 && $my_point->points<$deductible) {
                return response()->json(['status'=>0, 'msg' => '积分不足,请使用其他方式支付!!']);
            }
            if ($form_validate){//是否是表单验证的
                //返回之后支付宝再用form 表单再请求一遍
                return response()->json(['status'=>1, 'msg' => '验证成功!']);
            }

            $params['jobs_id'] = $jobs_id;
            $params['days'] = $increment_info['value'];
            $nowtime = time();
            $params['starttime'] = $nowtime;
            for ($i=0; $i < $params['days']*4; $i++) {
                $timespace = 3600*6*$i;
                if ($i+1==$params['days']*4) {
                    $params['endtime'] = $nowtime+$timespace;
                }
            }
            return $this->callCashPay($my_setmeal, $my_point, $increment_info, $order_pay_type, $payment_name, $service_need_cash, $is_deductible, $deductible, '', $params, 0, $project_id, '专享'.$my_discount.'折优惠');
        }
    }

    /**购买积分
     * @return ServiceController|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function pointsAdd()
    {
        if (!config('aix.companyset.points.points_set.enable_com_buy_points')) {
            return $this->sendErrorResponse('参数错误!', 404);
        }
        $res = $this->serviceService->pointsAdd();
        return view('app.company.increment.points_add', $res);
    }

    public function pointsSave(Request $request)
    {
        if (!config('aix.companyset.points.points_set.enable_com_buy_points')) {
            return $this->sendErrorResponse('企业充值未开启,请联系网站管理员!', 404);
        }
        $payment_name = $request->input('payment_name', '');
        $points = $request->input('points', 0);
        if (!$points) {
            return response()->json(['status'=>0, 'msg'=>"请输入要购买的积分数量!"]);
        } elseif ($points < config('aix.companyset.points.points_set.com_buy_points_min')) {
            $points = config('aix.companyset.points.points_set.com_buy_points_min');
        }
        $service_need_cash = round($points/config('aix.companyset.points.points_set.payment_rate'), 2);
        $paymenttpye = $this->paymentService->returnPayment($payment_name);
        if (!$paymenttpye) {
            return array( 'status'=>0, 'msg' => '支付方式错误!');
        }

        $user = auth('web-company')->user();
        $description = '购买积分';
        $params['points'] = $points;
        $params['cash'] = $service_need_cash;
        $params['rate'] = config('aix.companyset.points.points_set.payment_rate');

        $order = $this->orderService->addOrder($user, 2, $service_need_cash, $service_need_cash, 0, '购买积分', $payment_name, $paymenttpye->name, $description, 1, 0, 0, 0, serialize($params));
        $tradeNo = $this->payService->getTradeNo($order->id);
        if (!$this->serviceService->updateOid($order->id, $tradeNo)) {
            throw new ResponseException('生成订单号失败!');
        }
        if ($payment_name == 'wechat') {
            $type = 'scan';
        } elseif ($payment_name == 'offline') {
            $type = 'pay';
        } else {
            $type = 'web';
        }

        $payOrder = new PayOrder();
        $payOrder->trade_no = $tradeNo;
        $payOrder->subject = '购买积分';
        $payOrder->detail = $description;
        $payOrder->price = $service_need_cash;
        $payOrder->callback = "App\Services\Common\OrderService.pointsSave";
        $result = $this->payService->pay($payment_name, $type, $payOrder);
        if ($payment_name == 'wechat') {
            return response()->json([
                'status' => 1,
                'tradeCode' => get_qrcode_html($result->code_url),
                'tradeNo' => $tradeNo,
            ]);
        } elseif ($payment_name == 'offline') {
            return response()->json([
                'status'=>1,
                'tradeNo'=>$tradeNo,
                'url'=>route("service.order.detail",['id'=>$order->id]),
            ]);
        } else {
            return $result;
        }
    }


    /**现金支付
     * @param $resume_id
     * @param $my_setmeal
     * @param $my_point
     * @param $increment_info
     * @param $order_pay_type
     * @param string $payment_name
     * @param string $amount
     * @param $is_deductible
     * @param int $deductible
     * @param string $description
     * @param string $params
     * @param int $points
     * @param int $stemeal
     * @param string $discount
     * @return \Illuminate\Http\JsonResponse
     * @throws ResponseException
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    protected function callCashPay($my_setmeal, $my_point, $increment_info, $order_pay_type, $payment_name = '', $amount = '0.0', $is_deductible, $deductible = 0, $description = '', $params = '', $points = 0, $stemeal = 0, $discount = '')
    {
        //获取支付方式
        $paymenttpye = $this->paymentService->returnPayment($payment_name);
        if (!$paymenttpye) {
            return array( 'status'=>0, 'msg' => '支付方式错误!');
        }
        if (!config("aix.system.pay.{$payment_name}.is_on")) {
            if ($payment_name == 'alipay') {
                return "支付方式未开启!请联系客服电话:【".config('aix.system.pay.offline.service_tel')."】";
            } else {
                return array( 'status'=>0, 'msg' => "支付方式未开启!请联系客服电话:【".config('aix.system.pay.offline.service_tel')."】");
            }

        }

        if ($payment_name == 'wechat') {
            $type = 'scan';
        } elseif ($payment_name == 'alipay') {
            $type = 'web';
        } elseif ($payment_name == 'offline') { //如果是线下转账
            /**
             * 把积分设为0,产生原因:线下线上用的同一个请求参数,
             * 切换时候没有擦除,会带上积分
             * bug-#1255
             */
            $is_deductible=0;
            $type='pay';
        }

        if ($my_point->points < $deductible) {
            return array( 'status'=>0, 'msg' => '积分不足,请使用其他方式支付!');
        }
        if ($is_deductible==0) {
            $deductible = 0;
        }
        if ($deductible>0) {
            $m_amount = round($amount- floatval($deductible/config('aix.companyset.points.points_set.payment_rate')),2);
        } else {
            $m_amount = $amount;
        }



        $paysetarr['ordtotal_fee']=$m_amount;
        if ($description=='') {
            $description = '购买服务:'.$increment_info->name;
        }
        $description .= ';'.$paymenttpye->name.$paysetarr['ordtotal_fee'].'元';
        if ($deductible>0) {
            $description .= ';积分支付:'.$deductible.'积分';
        }
        $stime = time();
        $user = auth('web-company')->user();



        //生成订单
        $order = $this->orderService->addOrder($user, $order_pay_type, $amount, $paysetarr['ordtotal_fee'], $deductible, $increment_info->name, $payment_name, $paymenttpye->name, $description, 1, $deductible, $stemeal, 0, serialize($params), $discount);
        $tradeNo = $this->payService->getTradeNo($order->id);
        if (!$this->serviceService->updateOid($order->id, $tradeNo)) {
            throw new ResponseException('生成订单号失败!');
        }

        $payOrder = new PayOrder();
        $payOrder->trade_no = $tradeNo;
        $payOrder->subject = '购买' . $increment_info->name;
        $payOrder->detail = $description;
        $payOrder->price = round($m_amount, 2);
        $payOrder->callback = "App\Services\Common\OrderService.incrementSave";
        $payOrder->return_url = route('service.order.index');
        $result = $this->payService->pay($payment_name, $type, $payOrder);
        if ($payment_name == 'wechat') {
            return response()->json([
                'status' => 1,
                'tradeCode' => get_qrcode_html($result->code_url),
                'tradeNo' => $tradeNo,
            ]);
        } elseif ($payment_name =='alipay') {
            return $result;
        } else {
            return response()->json([
                'status'=>1,
                'tradeNo'=>$tradeNo,
                'url'=>route("service.order.detail",['id'=>$order->id]),
            ]);
        }
    }

    /**订单列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function orderList(Request $request)
    {
        $user = auth('web-company')->user();
        $res = $this->orderService->orderList($request->all(), $user);
        return view('app.company.order.index', $res);
    }


    public function templateList()
    {
        $res = $this->companyTplService->templateList(auth('web-company')->user());
        return view('app.company.increment.template', $res);
    }

    public function companyUpdate(Request $request)
    {
        $result = $this->companyTplService->companyUpdate(auth('web-company')->user(), $request->tpl);
        if ($result) {
            return $this->sendSuccessResponse('更新成功!');
        } else {
            return $this->sendErrorResponse('更新失败!');
        }
    }

    public function complaintConsultant(Request $request)
    {
        if($request->method()=='POST'){
            $result = $this->complaintConsultantService->getCompanyConsultant(auth('web-company')->user(), $request->all());
            if ($result) {
                return $this->sendSuccessResponse('投诉成功!');
            } else {
                return $this->sendErrorResponse('投诉失败!');
            }
        }else{
            $arr['name'] = $request->name;
            $arr['id'] = $request->id;
            $html = view('app.company.ajax.complaint_consultant', $arr)->render();
            return response()->json(['html'=>$html]);
        }
    }


    /**删除订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function orderDel(Request $request)
    {
        $id = $request->id?$request->id:0;
        if (!$id) {
            return response()->json(['status'=>0,'msg'=>'参数错误']);
        }
        if ($request->method()=='POST') {
            $user = auth('web-company')->user();
            return $this->orderService->orderDel($id,$user);
        }
        $tip='订单被删除后无法恢复,您确定要删除该订单吗?';
        return response()->json(['status'=>1, 'msg'=>'', 'data'=>['html'=>view('app.company.ajax.ajax_warning', ['tip'=>$tip])->render()]]);
    }

    /**订单取消
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function orderCancel(Request $request)
    {
        $user = auth('web-company')->user();
        $id = $request->id?$request->id:0;
        if (!$id) {
            return response()->json(['status'=>0,'msg'=>'参数错误']);
        }
        if ($request->method() == 'POST') {
            return $this->orderService->orderCancel($id, $user);
        }
        $tip='您确定要取消该订单吗?';
        $description='如果您在支付过程中遇到问题,可以联系网站客服,联系电话:'.config('aix.system.site.site.bootom_tel').'。';
        return response()->json(['status'=>1, 'msg'=>'', 'data'=>['html'=>view('app.company.ajax.ajax_warning', ['tip'=>$tip, 'description'=>$description])->render()]]);
    }

    /**订单详情
     * @param $id
     * @return ServiceController|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws ResponseException
     */
    public function orderDetail($id)
    {
        if (!$id) {
            return $this->sendErrorResponse('参数错误!', 404);
        }
        $user = auth('web-company')->user();
        $res = $this->orderService->orderDetail($id, $user);
        if ($res['order']->is_pay==2 || $res['order']->is_pay==3) {
            $tpl = 'order_detail';
        } else {
            $tpl = 'order_detail_nopay';
        }

        return view("app.company.order.{$tpl}", $res);
    }

    /**索要发票
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function invoiceSave(Request $request)
    {
        $data = $request->except('_token');
        $user = auth('web-company')->user();
        return $this->orderService->invoiceSave($data, $user);
    }

    /**重新支付
     * @param int $id
     * @return ServiceController|\Illuminate\Http\JsonResponse
     * @throws ResponseException
     */
    public function orderPayRepeat($id = 0)
    {
        if (!$id) {
            return $this->sendErrorResponse('参数错误!', 404);
        }
        return $this->orderService->orderPayRepeat($id);
    }
    /**
     * 电子票据
     */
//    public function enote($id = 0)
//    {
//        if (!$id) {
//            return response()->json(['status'=>0, 'msg'=>"参数错误!"]);
//        }
//        $res = $this->orderService->enote($id);
//        return response()->json(['status'=>1,'msg'=>'获取数据成功!','data'=>['html'=>view('app.company.ajax.ajax_enote', $res)->render()]]);
//    }
    /**订单支付成功
     * @param $oid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws ResponseException
     */
    public function setmealFinish($oid)
    {
        $res = $this->serviceService->setmealFinish($oid);
        return view('app.company.service.order_finish', $res);
    }

}