<?php

namespace app\api\controller;

use app\admin\logic\beforehand_order\BeforehandOrderLogic;
use app\admin\logic\store_branch_product\StoreBranchProductLogic;
use app\common\logic\StoreFinanceFlowLogic;
use app\admin\logic\store_product\StoreProductLogic;
use app\admin\validate\tools\GenerateTableValidate;
use app\admin\logic\tools\GeneratorLogic;
use app\api\lists\purchase_product_offer\PurchaseProductOfferListsTwo;
use app\api\logic\DemoLogic;
use app\api\logic\order\OrderLogic as OrderOrderLogic;
use app\common\cache\ExportCache;
use app\common\logic\ChangeLogLogic;
use app\common\logic\PayNotifyLogic;
use app\common\logic\store_order\StoreOrderLogic;
use app\common\model\beforehand_order_cart_info\BeforehandOrderCartInfo;
use app\common\model\beforehand_order_record\BeforehandOrderRecord;
use app\common\model\Config as ModelConfig;
use app\common\model\purchase_product_offer\PurchaseProductOffer;
use app\common\model\store_branch_product\StoreBranchProduct;
use app\common\model\store_finance_flow\StoreFinanceFlow;
use app\common\model\store_order\StoreOrder;
use app\common\model\store_order_cart_info\StoreOrderCartInfo;
use app\common\model\store_product\StoreProduct;
use app\common\model\system_store\SystemStore;
use app\common\model\system_store_storage\SystemStoreStorage;
use app\common\model\user\User;
use app\common\model\warehouse_product\WarehouseProduct;
use app\common\service\Curl;
use app\common\service\pay\PayService;
use app\common\service\PushService;
use app\common\service\wechat\WechatTemplate;
use app\common\service\xpyun\XpsdkPrintApi;
use app\statistics\logic\OrderLogic;
use Exception;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use support\Cache;
use think\facade\Db;
use Webman\Config;
use support\Log;
use Yansongda\Pay\Exception\InvalidSignException;
use  Monolog\Handler\RotatingFileHandler;
use Webman\RedisQueue\Redis;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Shared\Converter;
use PhpOffice\PhpWord\Style\Font;
use Chance\Log\facades\OperationLog;

class IndexController extends BaseApiController
{
    public $notNeedLogin = ['aa','index', 'app_update', 'express_list', 'province', 'city', 'area', 'street', 'village', 'brigade', 'config', 'push', 'purchase_product_offer'];

    public function index()
    {
           $arr= Db::name('ceshi_copy_copy')->select();
           foreach ($arr as $k => $v) {
                $find=Db::name('ceshi_copy')->where('product_id',$v['product_id'])->find();
                if($find){
                    Db::name('ceshi_copy_copy')->where('id',$v['id'])->update(['price_two'=>bcadd($v['price'],bcmul($v['price'], $find['purchase'], 2),2),'purchase'=>bcadd($v['price'],bcmul($v['price'], $find['price'], 2),2)]);

                }
           }
  d(1);
        $arr = Db::name('ceshi_copy')->select();
        foreach ($arr as $k => $v) {
            $data = [

                'cost' => $v['cost'],
                'purchase' => $v['purchase'],
                'price' => $v['price'],
                'vip_price' => $v['price'],

            ];
            $rose = 0;
            //零售-供货
            $rose_price = bcsub($v['price'], $v['purchase'], 2);
            if ($rose_price > 0) {
                //利润除于零售
                $price_div = bcdiv($rose_price, $v['price'], 2);
                $rose = bcmul($price_div, 100, 2);
            }
            $data['rose'] = $rose;
            StoreProduct::update($data, ['id' => $v['product_id']]);
            //修改
            StoreBranchProduct::where('product_id', $v['product_id'])->whereNotIn('store_id', [17, 18])->update([
                'price' => $v['price'],
                'vip_price' => $v['price'],
                'cost' => $v['cost'],
                'purchase' => $v['purchase'],
                'rose' => $rose

            ]);
        }
        d(11);
        $pay_price = StoreOrder::where('store_id', 3)->where('id', '>=', 1867)->where('id', '<=', 4826)->where('paid', 1)->sum('pay_price');
        $refund_price = StoreOrder::where('store_id', 3)->where('id', '>=', 1867)->where('id', '<=', 4826)->where('paid', 1)->sum('refund_price');
        d($pay_price, $refund_price);
        $arr = StoreOrder::where('store_id', 3)->where('id', '>', 551)->where('paid', 1)->field('id,pay_price,deduction_price,refund_price')->select()->toArray();
        $data = [];
        foreach ($arr as $k => $v) {
            $total_price = StoreOrderCartInfo::where('oid', $v['id'])->sum('total_price');
            if ($total_price != $v['pay_price']) {
                $s = $v;
                $s['total_price'] = $total_price;
                $data[] = $s;
            }
        }
        d($data);


        $url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b538e44b-940b-445f-afe0-97320942d959';

        $arr = ["msgtype" => "template_card", "template_card" => [
            'card_type' => 'text_notice',
            'main_title' => [
                'title' => '测试标题',
                'desc' => '分单'
            ],
            'card_action' => [
                'type' => 1,
                'url' => 'https://admin-multi-store.lihaink.cn/admin'
            ]
        ]];
        $a = (new Curl())->postJson($url, json_encode($arr, true));
        d($a);
        return json(1);

        $financeFlow = new StoreFinanceFlow();
        $financeFlowLogic = new StoreFinanceFlowLogic();
        $select_1 = $financeFlow->where('id', 16197)->select();

        foreach ($select_1 as $k => $v) {
            if ($v['other_uid'] > 0) {
                $financeFlowLogic->updateStatusUser($v['id'], $v['other_uid'], $v['number'], $v['order_id']);
            }
        }
    }


    /**
     * @notes 下载文件
     */
    public function download()
    {
        $params = (new GenerateTableValidate())->goCheck('download');
        $result = GeneratorLogic::download($params['file']);
        if (false === $result) {
            return $this->fail(GeneratorLogic::getError() ?: '下载失败');
        }
        return response()->download($result, 'webman-curd.zip');
    }

    /**
     * @notes 获取app更新信息
     */
    public function app_update()
    {
        $find = Db::name('app_update')->where('type', 2)->order('id', 'desc')->findOrEmpty();
        return $this->success('ok', $find);
    }


    /**
     * @notes 获取省列表
     */
    public function province()
    {
        $list = Db::name('geo_province')->select()->toArray();
        return $this->success('ok', $list);
    }
    /**
     * @notes 获取市列表
     */
    public function city()
    {
        $province_code = $this->request->get('province_code');
        $list = Db::name('geo_city')->where('province_code', $province_code)->select()?->toArray();
        return $this->success('ok', $list);
    }
    /**
     * @notes 获取区列表
     */
    public function area()
    {
        $city_code = $this->request->get('city_code');
        $list = Db::name('geo_area')->where('city_code', $city_code)->select()?->toArray();
        return $this->success('ok', $list);
    }
    /**
     * @notes 获取街道列表
     */
    public function street()
    {
        $area_code = $this->request->get('area_code');
        $list = Db::name('geo_street')->where('area_code', $area_code)->select()?->toArray();
        return $this->success('ok', $list);
    }

    /**
     * @notes 获取村列表
     */
    public function village()
    {
        $area_code = $this->request->get('street_code');
        $list = Db::name('geo_village')->where('street_code', $area_code)->select()?->toArray();
        return $this->success('ok', $list);
    }
    /**
     * @notes 获取队列表
     */
    public function brigade()
    {
        $list = Db::name('geo_brigade')->select()?->toArray();
        return $this->success('ok', $list);
    }

    /**
     * @notes 获取队列表
     */
    public function config()
    {
        //处理返回最近的店铺
        $params = $this->request->get();
        if ((isset($params['lat']) && $params['lat'] != '') && (isset($params['long']) && $params['long'] != '')) {
            $latitude = $params['lat'];
            $longitude = $params['long'];
            // 计算距离的SQL表达式
            $distanceExpr = "6371 * 2 * ASIN(SQRT(POWER(SIN(({$latitude} - abs(latitude)) * pi()/180 / 2), 2) + COS({$latitude} * pi()/180) * COS(abs(latitude) * pi()/180) * POWER(SIN(({$longitude} - longitude) * pi()/180 / 2), 2)))";
            $find = SystemStore::field("id, name,abbreviation, {$distanceExpr} AS distance")
                ->where('is_show', '=', 1)
                ->where('latitude', '<>', '')
                ->where('longitude', '<>', '')
                ->order('distance', 'asc') // 根据距离排序
                ->find();
            if (!$find) {
                $store_id = getenv('STORE_ID') ?? 1;
                $find = SystemStore::where('id', $store_id)->find();
            }
        } else {
            $store_id = getenv('STORE_ID') ?? 1;
            $find = SystemStore::where('id', $store_id)->find();
        }
        $list = [
            'id' => $find['id'],
            'store_name' => $find['name'],
            'abbreviation' => $find['abbreviation'],
        ];
        return $this->success('ok', $list);
    }

    public function push()
    {
        $name = $this->request->get('name'); //用户名
        $uid = $this->request->get('uid'); //用户id
        $type = $this->request->get('type', 'INDUSTRYMEMBERS'); //类型
        $a =  PushService::push($name, $uid, ['type' => $type, 'msg' => '支付超时,订单已被取消,请重新提交订单', 'data' => ['id' => 5]]);
        return $this->success('ok', ['data' => $a]);
    }

    /**
     * @notes 采购商品下载
     */
    public function purchase_product_offer()
    {
        $date = $this->request->get('date');
        if ($date) {
            $this->request->setGet(['date' => $date, 'export' => 2]);
            $lists = new PurchaseProductOfferListsTwo();
            $exportDownloadUrl = $lists->createExcel($lists->setExcelFields(), $lists->lists());
            $fileKey = explode('?file=', $exportDownloadUrl)[1];
            //通过文件缓存的key获取文件储存的路径
            $exportCache = new ExportCache();
            $fileInfo = $exportCache->getFile($fileKey);
            if (empty($fileInfo)) {
                return $this->fail('下载文件不存在');
            }
            //下载前删除缓存
            Cache::delete($fileKey);
            return response()->download($fileInfo['src'] . $fileInfo['name'], $fileInfo['name']);
        } else {
            return $this->fail('时间不能为空');
        }
    }

    /**
     * @notes 采购商品下载
     */
    public function wps_product()
    {
        $data = $this->request->post();
        if ($data) {
            if ($data['product_id'] > 0) {
                $find = Db::name('wps_product')->where('product_id', $data['product_id'])->find();
                $arr = [];
                if ($data['purchase'] > 0) {
                    $arr['purchase'] = $data['purchase'];
                }
                if ($data['cost'] > 0) {
                    $arr['cost'] = $data['cost'];
                }
                if ($data['price'] > 0) {
                    $arr['price'] = $data['price'];
                }
                if ($find) {
                    Db::name('wps_product')->where('id', $find['id'])->update($arr);
                } else {
                    $arr['product_id'] = $data['product_id'];
                    $arr['name'] = $data['name'];
                    Db::name('wps_product')->insert($arr);
                }
            }
        } else {
            return $this->fail('时间不能为空');
        }
    }

    public function aa(){
        $boyd = $this->request->post();

// 输出结果
        $time = $this->request->header('timestamp');
        
        // 需要签名的数据
        $data = [
            'appid' => 'e328e0d083784b8cbbd8a45e2a13b430',
            'timestamp' => $time,
            'version' => "1.0.0"
        ];
        $md5='{}';
        if($boyd){
            $md5 = md5(json_encode($boyd,true));
            $data['md5']=$md5;
        }else{
            $md5 = md5($md5);
            $data['md5']=$md5;
        }
        // 获取token
        $token=$this->request->header('token');
        if($token){
            $data['token']=$token;
        }
        // 按字母顺序排序
        ksort($data);
    
        // 转换为JSON字符串
        $jsonString = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        // RSA私钥
        $privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKYtaukWByNHG8VZsvfIwEeJUKa0t2RaNNMp/IlgWj/29aK+nCZZC+zROc8xjQAAHKbQgwXeFzizzDb98Q8Qavgo+8zuNi2V45sj12+7yC1tfX4zRkm4Yqri+YifJLNXxoh46dvx9CsNrKT/e5we6irxaWJoXxGxeZ4pA1JpcrwHAgMBAAECgYBnoELe/yGMWjdzJbB42/MrqPFmQ6NpLOdsFu6oLDGbWcFrrzlooHbTQtWt4tRuf6NeUwChlBEfBt/+GvVL040gF2T2ylsMi3biktZDSlT/+DI7H5S1x4aBplIBc4yAp/vrFTyWmxdULEksap2BUf5fEqG/CVcWMI2zszORQi4QAQJBAO4z9FsOyPZ0ycrCFmQD9AYPzmnBvgTg/uU0xGY7yus8zIt29TL1uE77/ksmGxJQXXcRUt2ytPVm9YqXnXS/EgcCQQCyl9l7Kdr/eifOcRd9wAAXwsHKkjfJR1Vd1igv5wCZqSkXK2qxxvQDPE98HugosNkFxuyedFbfrbSQpPUjnIYBAkAyDXK8K4go2XOJim0ACSCeoXWjHVXbWpfU+9iFDu1drsHgUFfHpIBdAHB3xAMOPxrUqSw7b5C8vCy+OYuZe4jDAkAdpsqMAWID4sMzKmGtFjCtwT8to+MxPu+0ebcIZQEbghN5blLzm0WuN9g2kmcXQm114RYuJMC7uHpvPYQZ2oYBAkBBzytKuG5EhbsI5flwxYGTDvQtY1TGvsYVrt0anirPa9xVq+RYC2Jr9zk0j8s13QhXoVwAO6seO7cYN9n8J65t";

        // 解码私钥
        $privateKeyPem = "-----BEGIN PRIVATE KEY-----\n" . wordwrap($privateKey, 64, "\n", true) . "\n-----END PRIVATE KEY-----";
        // 获取私钥资源
        $privateKeyResource = openssl_pkey_get_private($privateKeyPem);          
        openssl_sign($jsonString, $signature, $privateKeyResource, OPENSSL_ALGO_SHA1);
    
        // 将签名进行Base64编码
        $signatureString = base64_encode($signature);
    
        d($md5,$time,$signatureString);
    }
}