<?php

namespace app\controller;

use think\App;
use app\BaseController;
use think\facade\Log;
use think\exception\ValidateException;
use app\AppCache;
use think\facade\Cache;
use app\Constant;
use Exception;
use think\facade\Config;
use app\service\ToolService;

class V1 extends BaseController
{
  protected $service_tool = null;
  function __construct(
    App $app,
    ToolService $toolService
  ) {
    $this->service_tool = $toolService;
    $this->check_actions = [
    ];
    $this->className = 'V1';
    $this->not_check_action_login = [
      'test',
      'pay_notify',
      'wx_login',
    ];
    parent::__construct($app);
  }
  public function goods_list() {
    $list = D('goods')->where(['deleted' => 0])->order('sort ASC')->select();
    return ajaxSuccess($list);
  }
  public function test() {
    // $root_dir = root_path();
    // $filepath = $root_dir . '/public/uploads/' . 'zpss.jpg';
    // $re = $this->service_tool->tuPianShangSe($filepath);
    $re = $this->mark_order_yiCunZhao(2, '/uploads/ycz.jpg', 'white');
    return ajaxSuccess($re);
  }
  public function mark_order_vip($goods_id = '', $num = 1) {
    $deal_params = ['num' => $num];
    $goods = D('goods')->where(['id' => $goods_id, 'deleted' => 0])->find();
    if (empty($goods)) {
      return ajaxFail('不存在的服务', -1);
    }
    $order_no = s_order_id_render('Z');
    $order = [
      'user_id' => $this->user_id,
      'goods_id' => $goods_id,
      // 'from_user_id' => $share['from_user_id'],
      'create_time' => c_now(),
      'status' => 'wait_pay',
      'order_no' => $order_no,
      'price' => $goods['price'] * $num,
      'deal_type' => $goods['deal_type'],
      'funct_name' => $goods['funct_name'],
      'deal_params' => c_json_encode($deal_params),
    ];
    D('orders')->insert($order);
    return ajaxSuccess(['order_no' => $order_no]);
  }
  public function mark_order_tongYongFenGe($goods_id='',$path='') {
    $deal_params = ['path' => $path];
    return $this->mark_order_base($goods_id, $deal_params);
  }
  // color: red blue white;
  public function mark_order_yiCunZhao($goods_id = '', $path = '', $color = '') {
    $deal_params = ['path' => $path,
      'color' => $color];
    return $this->mark_order_base($goods_id, $deal_params);
  }
  public function mark_order_zhaopianshangse($goods_id = '', $path = '') {
    $deal_params = ['path' => $path];
    return $this->mark_order_base($goods_id, $deal_params);
  }
  private function mark_order_base($goods_id, $deal_params) {
    // 是否是vip
    $is_vip = strtotime($this->user_info['vip_expire_time'] ?: c_now()) > time();
    if (!$is_vip) {
      $goods_free_use_limit = D('config')->where(['k' => 'goods_free_use_limit'])->value('v');
      $find_user_use =  D('user_use_cnt')->where(['goods_id' => $goods_id, 'user_id' => $this->user_id])->find();
      $use_cnt = 0;
      if($find_user_use) {
        $use_cnt = $find_user_use['use_cnt'];
      }else{
        D('user_use_cnt')->insert(['goods_id' => $goods_id, 'user_id' => $this->user_id, 'use_cnt'=>0]);
      }
      if ($use_cnt >= $goods_free_use_limit) {
        return ajaxFail('免费次数使用结束,请先充值', -1);
      }
    }
    $goods = D('goods')->where(['id' => $goods_id, 'deleted' => 0])->find();
    if (empty($goods)) {
      return ajaxFail('不存在的服务', -2);
    }
    $order_no = s_order_id_render('Z');
    $order = [
      'user_id' => $this->user_id,
      'goods_id' => $goods_id,
      // 'from_user_id' => $share['from_user_id'],
      'create_time' => c_now(),
      'status' => 'wait_pay',
      'order_no' => $order_no,
      'price' => $goods['price'],
      'deal_type' => $goods['deal_type'],
      'funct_name' => $goods['funct_name'],
      'deal_params' => c_json_encode($deal_params),
    ];
    D('orders')->insert($order);
    D('user_use_cnt')->where(['goods_id' => $goods_id, 'user_id' => $this->user_id])->inc('use_cnt');
    $this->pay_notify($order_no);
    return ajaxSuccess(['order_no' => $order_no]);
  }
  public function order_list($page = 1) {
    $list = D('orders')->where(['deleted' => 0, 'user_id' => $this->user_id])->where(['status' => 'payed'])->page($page, 10)->order('id DESC')->select();
    return ajaxSuccess($list);
  }

  public function config_one($k) {
    $v = D('config')->where(['k' => $k])->value('v');
    $v = c_safe_to_json($v, $v);
    return ajaxSuccess($v);
  }

  public function configs($ks = '') {
    $model = D('config');
    if ($ks) {
      $model->where('k', 'in', $ks);
    }
    $all_enums = $model->select();
    $re = [];
    foreach ($all_enums as $one) {
      $re[$one['k']] = c_safe_to_json($one['v'], $one['v']);
    }
    //
    return ajaxSuccess($re);
  }
  public function my() {
    $info = $this->user_info;
    if ($info['is_share']) {
      $info['price_sum'] = D('orderx')->where(['status' => 'payed'])->where(['from_user_id' => $this->user_id])->sum('price');
      $info['share_cnt'] = D('share')->where(['from_user_id' => $this->user_id])->count();
      $info['share_view_cnt'] = D('share')->where(['from_user_id' => $this->user_id])->sum('view_cnt');
    }
    $show_vip_link = $info['is_share'] ? true : false;
    if (!$show_vip_link) {
      if (D('orderx')->where(['status' => 'payed'])->where(['user_id' => $this->user_id])->find()) {
        $show_vip_link = true;
      }
    }
    $info['show_vip_link'] = $show_vip_link;
    $info['payed_vip_link'] = D('config')->where(['k' => 'payed_vip_link'])->value('v');
    return ajaxSuccess($info);
  }
  public function set_name($name = '') {
    D('user')->where(['id' => $this->user_id])->update(['real_name' => $name]);
    return ajaxSuccess();
  }

  public function bind_auth_phone($code = '') {
    $row_user = D('user')->where([
      'id' => $this->user_id,
    ])->find();

    $cache_a_k = Cache::get(Constant::$CACHE_ACCESS_TOKEN);
    $qdata = [
      'code' => $code,
    ];
    $re_data = curl_post_https('https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $cache_a_k['access_token'], json_encode($qdata));
    $this->log_notice([$re_data], '授权手机号返回', 'bind_auth_phone');
    // $session_key = $row_user['session_key'];
    // $data = decrypt_wx_data($encrypted_data, $iv, $session_key);
    // if (is_int($data) && $data < 0) {
    //     return ajaxFail('数据解析失败', -1);
    // }
    // /*
    // {
    //     "phoneNumber": "13580006666",
    //     "purePhoneNumber": "13580006666",
    //     "countryCode": "86",
    //     "watermark":
    //     {
    //         "appid":"APPID",
    //         "timestamp": TIMESTAMP
    //     }
    // }
    //  */
    // //更新数据
    // $pure_phone_number = $data['purePhoneNumber'];
    // $country_code = $data['countryCode'];
    $re_data_json = c_safe_to_json($re_data);
    if (isset($re_data_json['errcode']) && $re_data_json['errcode'] == 0) {
      $pure_phone_number = $re_data_json['phone_info']['purePhoneNumber'];
      $country_code = $re_data_json['phone_info']['countryCode'];
      D('user')->where([
        'id' => $this->user_id,
      ])->update([
        'phone' => $pure_phone_number,
        'phone_country_code' => $country_code,
      ]);
      return ajaxSuccess($pure_phone_number);
    }
    return ajaxFail('获取手机号失败', -1);
  }

  public function static_data_get($id) {
    $row = D('static_data')->where(['id' => $id])->find();
    return ajaxSuccess($row);
  }

  /**
  *小程序上传文件
  */
  public function wx_upload() {
    $file = request()->file('img_file');
    if ($file) {
      try {
        validate([
          'img_file' => [
            'fileSize' => (20 * 1024 * 1024),
            'fileExt' => ['png', 'jpg', 'jpeg'],
          ]
        ])->check(['img_file' => $file]);
        $savename = \think\facade\Filesystem::disk('public')->putFile(date('Y-m-d'), $file, 'md5');
        return ajaxSuccess([
          'path' => '/uploads/' . str_replace('\\', '/', $savename),
        ]);
      } catch (ValidateException $e) {
        // 上传失败获取错误信息
        $this->log_notice($e->getMessage(), '上传失败获取错误信息', 'wx_upload');
        return ajaxFail($e->getMessage(), -2);
      }
    }

    $file = request()->file('audio_file');
    if ($file) {
      try {
        validate([
          'audio_file' => [
            'fileSize' => (20 * 1024 * 1024),
            'fileExt' => ['mp3'],
          ]
        ])->check(['audio_file' => $file]);
        $savename = \think\facade\Filesystem::disk('public')->putFile(date('Y-m-d'), $file, 'md5');
        return ajaxSuccess([
          'path' => '/uploads/' . str_replace('\\', '/', $savename),
        ]);
      } catch (ValidateException $e) {
        // 上传失败获取错误信息
        return ajaxFail($e->getMessage(), -2);
      }
    }


    $file = request()->file('video_file');
    if ($file) {
      try {
        validate([
          'video_file' => [
            'fileSize' => (200 * 1024 * 1024),
            'fileExt' => ['mp4'],
          ]
        ])->check(['video_file' => $file]);
        $savename = \think\facade\Filesystem::disk('public')->putFile(date('Y-m-d'), $file, 'md5');
        return ajaxSuccess([
          'path' => '/uploads/' . str_replace('\\', '/', $savename),
        ]);
      } catch (ValidateException $e) {
        // 上传失败获取错误信息
        return ajaxFail($e->getMessage(), -3);
      }
    }
    return ajaxFail('未选择上传文件,请重试', -3);
  }
  public function wx_login($code) {
    if ($code != 'test') {
      $data = code_2_session($code);
      if ($data == null) {
        return ajaxFail('授权失败', -1);
      }
    } else {
      $data['openid'] = 'o3CkR7ecDQlsBfAW88Cmjin4YkmI';
      $data['unionid'] = 'oV_Fvs_X63XiA1UDc2Bvx1YbD3bk';
      $data['session_key'] = 'HBwb0sNhajpzzgM4nuMt6w==';
    }

    $openid = $data['openid'];
    $unionid = $data['unionid'] ?? '';
    $session_key = $data['session_key'];
    $row_user = D('user')->where('openid', $openid)->where(['deleted' => 0])->find();
    if (empty($row_user)) {
      D('user')->insert([
        'union_id' => $unionid,
        'openid' => $openid,
        'session_key' => $session_key,
        'create_time' => date('Y-m-d H:i:s', time()),
      ]);
      $user_id = D('user')->getLastInsID();
    }
    //update
    else {
      $user_id = $row_user['id'];
      $update = [
        'session_key' => $session_key,
        //      'union_id'=>$unionid,
      ];
      if ($unionid) {
        $update['union_id'] = $unionid;
      }
      D('user')->where('openid', $openid)->update($update);
    }
    // c_debug('有人登录了:' . $user_id);
    return ajaxSuccess([
      // 'union_id' => $unionid,
      'user_id' => a_encode($user_id . '|' . time()),
      'openid' => $openid,
      'phone' => empty($row_user) ? '' : $row_user['phone'],
    ]);
  }
  public function login_id($id=0) {
    $row_user = D('user')->where(['id'=>$id])->find();
    setcookie('user_id', a_encode($id . '|' . time()));
    return ajaxSuccess([
      // 'union_id' => $unionid,
      'user_id' => a_encode($id . '|' . time()),
      'openid' => $row_user['openid'],
      'phone' => empty($row_user) ? '' : $row_user['phone'],
    ]);
  }

  public function fetch_order($order_no) {
    $order = D('orders')->where([
      'order_no' => $order_no,
      'user_id' => $this->user_id,
    ])->find();
    return ajaxSuccess(c_filter_property($order, ['deleted', 'pay_wx_data', 'need_auto_refund', 'deal_type', 'deal_params', 'deal_result'], true));
  }

  public function pay_order($order_no = '') {
    $order = D('orders')->where([
      'order_no' => $order_no,
      // 'user_id' => $this->user_id,
    ])->find();
    if (empty($order)) {
      return ajaxFail('不存在的订单', -2);
    }
    $price = intval($order['price']);
    // $debug = false;
    // $debug = Config::get('app.APP_DEBUG');
    // if ($debug) {
    //     $price = 1;
    // }
    $appid = Config::get('app.APPID');
    $body = '商城订单' . $order_no;
    $mch_id = Config::get('app.MCH_ID');
    $pay_url = Config::get('app.PAY_NOTIFY_URL_SHOP');
    $key = Config::get('app.PAY_KEY');
    $nonce_str = '0123456789';
    $openid = $this->user_info['openid'];
    $create_ip = '127.0.0.1';
    $need_encode_str = "appid=" . $appid
    . "&body=" . $body
    . "&mch_id=" . $mch_id
    . "&nonce_str=" . $nonce_str
    . "&notify_url=" . $pay_url
    . "&openid=" . $openid
    . "&out_trade_no=" . $order_no
    . "&sign_type=MD5"
    . "&spbill_create_ip=" . $create_ip
    . "&total_fee=" . $price
    . "&trade_type=JSAPI"
    . "&key=" . $key;
    $this->log_notice($need_encode_str, '$need_encode_str', 'pay_order');
    $sign = strtoupper(md5($need_encode_str));
    $xml = '<xml>'
    . '<appid>' . $appid . '</appid>'
    . '<body><![CDATA[' . $body . ']]></body>'
    . '<mch_id>' . $mch_id . '</mch_id>'
    . '<nonce_str>' . $nonce_str . '</nonce_str>'
    . '<notify_url>' . $pay_url . '</notify_url>'
    . '<openid>' . $openid . '</openid>'
    . '<out_trade_no>' . $order_no . '</out_trade_no>'
    . '<sign_type>MD5</sign_type>'
    . '<spbill_create_ip>' . $create_ip . '</spbill_create_ip>'
    . '<total_fee>' . $price . '</total_fee>'
    . '<trade_type>JSAPI</trade_type>'
    . '<sign>' . $sign . '</sign>'
    . '</xml>';
    $res_map = \s_make_wx_order($xml);
    // Log::write(json_encode($res_map), 'notice');
    $this->log_notice($res_map, '请求支付参数', 'pay_order');
    if ($res_map['return_code'] == 'SUCCESS') {
      $timeStamp = time();
      $paySign = md5('appId=' . $appid
        . '&nonceStr=' . $nonce_str
        . '&package=prepay_id=' . $res_map['prepay_id']
        . '&signType=MD5'
        . '&timeStamp=' . $timeStamp
        . '&key=' . $key);
      return ajaxSuccess([
        'timeStamp' => '' . $timeStamp,
        'nonceStr' => $nonce_str,
        'package' => 'prepay_id=' . $res_map['prepay_id'],
        'signType' => 'MD5',
        'paySign' => $paySign,
      ]);
    }
    return ajaxFail('调用支付接口失败', -3);
  }

  // 微信支付回调
  public function pay_notify($_test_success_order_no = '') {
    $str = file_get_contents('php://input');
    if ($_test_success_order_no) {
      $str = '';
    }
    // 模拟支付成功
    if (!$str && $_test_success_order_no) {
      $map = ['out_trade_no' => $_test_success_order_no,
        '系统默认支付成功，0元或测试单'];
    } else {
      $this->log_notice($str, '支付通知', 'pay_notify');
      $map = c_read_xml_to_map($str);
      if (empty($map) || !isset($map['out_trade_no'])) {
        $this->log_warn($map['out_trade_no'], '错误的支付消息', 'pay_notify');
        echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[错误的消息]]></return_msg></xml>';
        exit();
      }
    }

    $order_no = $map['out_trade_no'];
    $notify_return = 0;
    $order_detail = D('orders')->where(['order_no' => $order_no])->find(); // 查询包含已删除
    if (empty($order_detail)) {
      $notify_return = -1;
    }
    if ($order_detail['status'] != 'wait_pay') {
      // 只记录,不失败
      $this->log_warn($map['out_trade_no'], '订单状态不正确', 'pay_notify');
      // $this->service_any->sendqywx_test($map['out_trade_no'] . '订单状态不正确','');
      if ($order_detail['status'] != 'payed') {
        D('orders')->where(['id' => $order_detail['id']])->update(['need_auto_refund' => 1]);
      }
    }
    //超时支付和正常支付都算能支付
    D('orders')->where(['id' => $order_detail['id'], 'deleted' => 0])->update(['status' => 'payed', 'pay_time' => c_now(), 'pay_wx_data' => $str]);
    if ($notify_return == -1) {
      if ($_test_success_order_no) {
        return ajaxFail([$order_no], '订单ID不存在', 'pay_notify');
      }
      echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[订单ID不存在]]></return_msg></xml>';
    } else if ($notify_return == 0) {
      if ($_test_success_order_no) {
        return ajaxSuccess();
      }
      echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
    }
    if ($_test_success_order_no) {
      return ajaxFail([$order_no], '支付通知', 'pay_notify');
    }
  }
  //
  public function ______unuse_function_start______() {}
  public function notice_list() {
    $list = D('notice')->where(['delete' => 0])
    ->where('start_time', '<=', date('Y-m-d H:i:s', time()))
    ->where('end_time', '>=', date('Y-m-d H:i:s', time()))->select();
    return ajaxSuccess(c_filter_property_list($list, ['id', 'title', 'content', 'create_time']));
  }
  public function notice_deital($id) {
    $detail = D('notice')->where(['id' => $id, 'delete' => 0])->find();
    return ajaxSuccess(\c_filter_property($detail, ['delete', 'start_time', 'end_time'], true));
  }
  public function mark_order_info($order_no, $name = '', $phone = '', $position = '') {
    D('orderx')->where(['order_no' => $order_no])->update([
      'name' => $name,
      'phone' => $phone,
      'position' => $position,
    ]);
    return ajaxSuccess();
  }

  public function make_order($share_id) {
    $share = D('share')->where(['id' => $share_id, 'deleted' => 0])->find();
    if (empty($share)) {
      return ajaxFail('链接已失效，请联系客服');
    }
    if ($share['expire_time']) {
      if ($share['expire_time'] <= c_now()) {
        return ajaxFail('购买链接已过期，请重新联系客服');
      }
    }
    $order_no = s_order_id_render('P');
    $order = [
      'user_id' => $this->user_id,
      'share_id' => $share_id,
      'from_user_id' => $share['from_user_id'],
      'create_time' => c_now(),
      'status' => 'wait_pay',
      'order_no' => $order_no,
      'price' => $share['price'],
      'buy_type' => $share['buy_type'],
    ];
    D('orderx')->insert($order);
    return ajaxSuccess(['order_no' => $order_no]);
  }
  public function get_share($id) {
    $data = D('share')->where(['id' => $id, 'deleted' => 0])->find();
    // if(strtotime($data['expire_time']) >= time()) {
    //   return ajaxFail('支付链接已超时，请联系客服');
    // }
    // $v = D('config')->where(['k' => 'buy_types'])->value('v');
    // $data['buy_types'] = c_safe_to_json($v, $v);
    // $v = D('config')->where(['k' => 'tip_before_pay'])->value('v');
    // $data['tip_before_pay'] = c_safe_to_json($v, $v);
    // $v = D('config')->where(['k' => 'tip_after_pay'])->value('v');
    // $data['tip_after_pay'] = c_safe_to_json($v, $v);

    return ajaxSuccess($data);
  }
  public function view_share($id) {
    D('share')->where(['id' => $id, 'deleted' => 0])->inc('view_cnt')->update();
    return ajaxSuccess();
  }
  public function del_share($id) {
    D('share')->where(['id' => $id])->update(['deleted' => 1]);
    return ajaxSuccess();
  }
  public function share_link_list($page = 1, $pageSize = 10) {
    $list = D('share')->where(['from_user_id' => $this->user_id, 'deleted' => 0])->where('expire_time', '>=', c_now())->page($page, $pageSize)->select();
    return ajaxSuccess($list);
  }
  public function create_share($price, $expireDate, $buy_type = '') {
    if (!$this->user_info['is_share']) {
      return ajaxFail('您暂无分销权限', -1);
    }
    $data = [
      'from_user_id' => $this->user_id,
      'price' => $price * 100,
      'expire_time' => $expireDate . ' 23:59:59',
      'create_time' => c_now(),
      'title' => '推荐您购买' . $buy_type,
      'img' => 'http://cdn.zhonganonline.top/liiistem/static/liii_icon.png',
      'buy_type' => $buy_type,
    ];
    D('share')->insert($data);
    $id = D('share')->getLastInsID();
    $data['id'] = $id;
    // $data['path'] =
    return ajaxSuccess($data);
  }
  public function mark($id, $remark = '') {
    $one = D('orderx')->where(['id' => $id, 'from_user_id' => $this->user_id])->find();
    if (empty($one)) {
      return ajaxFail('不存在的内容', -1);
    }
    D('orderx')->where(['id' => $id])->update(['remark' => $remark]);
    return ajaxSuccess();
  }
  public function share_list($page = 1, $status = '') {
    $model = D('orderx')->where(['from_user_id' => $this->user_id]);
    if ($status) {
      $model->where(['status' => $status]);
    } else {
      $model->where('status', 'IN', ['payed', 'wait_pay']);
    }
    $list = $model->page($page, 10)->order('id DESC')->select();
    return ajaxSuccess($list);
  }

  public function banner_list() {
    $where = ['deleted' => 0];
    $list = D('banner')->where($where)->order('id DESC')->select();
    return ajaxSuccess($list);
  }

  public function news_list($page = 1, $pageSize = 10) {
    $where = ['deleted' => 0,
      'status' => 1];
    $model = D('news')->order('id DESC')->where($where);
    $list = $model->page($page, $pageSize)->select();
    return ajaxSuccess($list);
  }

  public function news_detail($id = '') {
    $detail = D('news')->where(['id' => $id, 'deleted' => 0])->find();
    if (!$detail) {
      return ajaxFail('数据不存在', -1);
    }
    $detail['view_cnt'] = $detail['view_cnt'] + 1;
    D('news')->where(['id' => $id, 'deleted' => 0])->update(['view_cnt' => $detail['view_cnt']]);
    return ajaxSuccess([
      'detail' => $detail,
    ]);
  }

}