<?php

namespace app\controller;

use think\App;
use app\BaseController;
use Exception;
use think\facade\Cache;
use app\Constant;
use think\facade\Config;
use think\facade\Db;
use app\service\ToolService;

class Sys extends BaseController
{
  protected $service_tool = null;
  function __construct(
    App $app,
    ToolService $toolService
  ) {
    $this->service_tool = $toolService;
    $this->className = 'api.Sys';
    $this->ignore_log_params = true;
    parent::__construct($app);
  }

/*
# if ! pgrep -f zhihuitb_test > /dev/null; then
#     echo "zhihuitb_test stoped, to start";
#     nohup sh ./zhihuitb_test.sh > /dev/null 2>&1 &
# else
#     echo "zhihuitb_test.sh runing";
# fi

*/
// 通用分割
  public function auto_deal_type_SegmentHDCommonImage() {
    $list = D('orders')->where(['deal_type' => 'SegmentHDCommonImage', 'deleted' => 0, 'status' => 'payed'])->where('deal_status', 'IN', ['init', 'ing'])->order('id ASC')->limit(2)->select();
    print_r($list);
    foreach ($list as $one) {
      if ($one['deal_status'] == 'ing') continue;
      if ($one['deal_status'] == 'init') {
        D('orders')->where(['id' => $one['id']])->update(['deal_status' => 'ing']);
        $deal_params = c_safe_to_json($one['deal_params']);
        $root_dir = root_path();
        $filepath = $root_dir . 'public' . $deal_params['path'];
        $imageUrl = $this->service_tool->tongYongFenGe($filepath);
        if ($imageUrl) {
          D('orders')->where(['id' => $one['id']])->update(['deal_result' => $imageUrl, 'deal_status' => 'done']);
        } else {
          D('orders')->where(['id' => $one['id']])->update(['deal_status' => 'fail']);
        }
      }
    }
    if (count($list) == 0) {
      echo 'No Task';
    }
  }
  
  // VIP 购买
  public function auto_deal_type_vip() {
    $list = D('orders')->where(['deal_type' => 'vip', 'deleted' => 0, 'status' => 'payed'])->where('deal_status', 'IN', ['init'])->order('id ASC')->select();
    foreach ($list as $one) {
      if ($one['deal_status'] == 'init') {
        D('orders')->where(['id' => $one['id']])->update(['deal_status' => 'ing']);
        $deal_params = c_safe_to_json($one['deal_params']);
        $num = $deal_params['num'];
        $order_no = $one['order_no'];
        $user_id = $one['user_id'];
        $user = D('user')->where(['id' => $user_id])->find();
        if (empty($user)) {
          D('orders')->where(['id' => $one['id']])->update(['deal_status' => 'fail']);
          $this->log_error('用户不存在:' . $user_id . ';order_no:'.$order_no, 'auto_deal_vip', 'auto_deal_vip');
          continue;
        }
        $now_expire_time = $user['vip_expire_time'];
        if (!$now_expire_time) {
          $now_expire_time = time();
        } else {
          $now_expire_time = strtotime($now_expire_time);
        }
        $now_expire_time = $now_expire_time + $num * 30 * 24 * 3600;
        $now_expire_time = date('Y-m-d', $now_expire_time) . ' 23:59:59';  
        D('user')->where(['id' => $user_id])->update(['vip_expire_time' => $now_expire_time]);
        D('orders')->where(['id' => $one['id']])->update(['deal_result' => $now_expire_time, 'deal_status' => 'done']);
      }
    }
    if (count($list) == 0) {
      echo 'No Task';
    }
  }
  // 一寸照异步返回
  public function auto_deal_type_SegmentBody_01_cb($order_no) {
    $root_dir = root_path();
    $out_dir = $root_dir . 'public';
    $out_path = '/output/SegmentBody_01/' . $order_no . '.jpg';
    $filepath = $out_dir . $out_path;
    if (file_exists($filepath)) {
      D('orders')->where(['order_no' => $order_no])->update(['deal_result' => $out_path, 'deal_status' => 'done']);
    } else {
      D('orders')->where(['order_no' => $order_no])->update(['deal_status' => 'fail']);
    }
    return ajaxSuccess();
  }
  // 一寸照
  public function auto_deal_type_SegmentBody_01() {
    $list = D('orders')->where(['deal_type' => 'SegmentBody', 'deleted' => 0, 'status' => 'payed'])->where('deal_status', 'IN', ['init', 'ing'])->order('id ASC')->limit(2)->select();
    foreach ($list as $one) {
      if ($one['deal_status'] == 'ing') continue;
      if ($one['deal_status'] == 'init') {
        D('orders')->where(['id' => $one['id']])->update(['deal_status' => 'ing']);
        $deal_params = c_safe_to_json($one['deal_params']);
        $root_dir = root_path();
        $path = $root_dir . 'public' . $deal_params['path'];
        $color = $deal_params['color'];
        $order_no = $one['order_no'];
        $out_dir = $root_dir . 'public';
        $out_path = '/output/SegmentBody_01/' . $order_no . '.jpg';
        // 运行python
        echo 'python3 ./idcard/idcard.py -p ' . $path .' '. $color . ' ' . $out_dir . $out_path;
        // 执行回调结果
        echo "\n";
        echo "curl 'http://127.0.0.1/index.php/sys/auto_deal_type_SegmentBody_01_cb?order_no=" . $order_no . "' -H 'Host:zhihuitb.zhonganonline.top'";
        // echo 'python3'.c_json_encode($deal_params) . '_' . $order_id;
        // $imageUrl = $this->service_tool->tuPianShangSe($deal_params['path']);
        // if($imageUrl) {
        //   D('orders')->where(['id'=>$one['id']])->update(['deal_result'=>$imageUrl,'deal_status'=>'done']);
        // } else {
        //   D('orders')->where(['id'=>$one['id']])->update(['deal_status'=>'fail']);
        // }
      }
    }
    if (count($list) == 0) {
      echo 'No Task';
    }
  }

  // 照片上色
  public function auto_deal_type_ColorizeImage_01() {
    $list = D('orders')->where(['deal_type' => 'ColorizeImage', 'deleted' => 0, 'status' => 'payed'])->where('deal_status', 'IN', ['init', 'ing'])->order('id ASC')->limit(2)->select();
    print_r($list);
    foreach ($list as $one) {
      if ($one['deal_status'] == 'ing') continue;
      if ($one['deal_status'] == 'init') {
        D('orders')->where(['id' => $one['id']])->update(['deal_status' => 'ing']);
        $deal_params = c_safe_to_json($one['deal_params']);
        $root_dir = root_path();
        $filepath = $root_dir . 'public' . $deal_params['path'];
        $imageUrl = $this->service_tool->tuPianShangSe($filepath);
        if ($imageUrl) {
          D('orders')->where(['id' => $one['id']])->update(['deal_result' => $imageUrl, 'deal_status' => 'done']);
        } else {
          D('orders')->where(['id' => $one['id']])->update(['deal_status' => 'fail']);
        }
      }
    }
    if (count($list) == 0) {
      echo 'No Task';
    }
  }

  public function timer_cancel_order() {
    D('orderx')->where(['status' => 'wait_pay'])->where('create_time', '<=', c_now(time() - 30 * 60))->update(['status' => 'cancel']);
    return ajaxSuccess();
  }


  public function clear_access_token() {
    $cache_key = Constant::$CACHE_ACCESS_TOKEN;
    Cache::set($cache_key, '');
    return '';
  }
  /**
  * 定时获取access_token
  * test ok
  * http://testwx.yunyoumg.com/index.php/api/sys/access_token
  */
  public function access_token() {
    $cache_key = Constant::$CACHE_ACCESS_TOKEN;
    $env = env('app.envName', 'prod');
    if ($env == 'prod') {
      $cache_a_k = Cache::get($cache_key);
      // c_debug($cache_a_k);
      if ($cache_a_k) {
        if ($cache_a_k['time'] + 3600 >= time()) {
          return ajaxSuccess($cache_a_k);
        }
      }
      c_debug('重新获取小程序ac了');
      $appid = Config::get('app.APPID');
      $secret = Config::get('app.SECERT_KEY');
      $data = curl_get_https("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret);
      $data = json_decode($data, true);
      if (!array_key_exists('errorCode', $data)) {
        Cache::set($cache_key, [
          'access_token' => $data['access_token'],
          'time' => time(),
        ], $data['expires_in'] * 1);
        return ajaxSuccess($data);
      }
      return ajaxFail($data, -1);
    }
    // $data = curl_get_https('https://www.yunyoumg.com/api/Collection/getMini');
    // $data = curl_get_https('https://mini.yunyoumg.com/index.php/api/sys/get_access_token');
    // $data = json_decode($data, true);
    // if (!array_key_exists('errorCode', $data)) {
    //   Cache::set($cache_key, [
    //     'access_token' => $data['data']['accessToken'],
    //     'time' => time(),
    //   ]);
    //   return ajaxSuccess($data['data']['accessToken']);
    // }
    Cache::set($cache_key, $data['model']);
  }
  public function get_access_token() {
    $cache_key = Constant::$CACHE_ACCESS_TOKEN;
    $ac = Cache::get($cache_key);
    //   echo json_encode([
    //     'data'=>[
    //         'accessToken'=>$ac['access_token'],
    //         ]
    //  ]);
    //   exit();
    return ajaxSuccess($ac);
  }
  public function test($t) {
    $this->log_notice($t, 'feishu', 'feishu');
    return ajaxSuccess();
  }
}