<?php

namespace app\api\controller;

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\logic\order\OrderLogic as OrderOrderLogic;
use app\common\logic\PayNotifyLogic;
use app\common\logic\store_order\StoreOrderLogic;
use app\common\model\Config as ModelConfig;
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_product\StoreProduct;
use app\common\model\system_store\SystemStore;
use app\common\model\user\User;
use app\common\model\warehouse_product\WarehouseProduct;
use app\common\service\pay\PayService;
use app\common\service\PushService;
use app\common\service\wechat\WechatTemplate;
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;

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

    public function index()
    {
        // 创建一个新的PHPWord文档
        $phpWord = new \PhpOffice\PhpWord\PhpWord();

        // 添加一个节
        $section = $phpWord->addSection(array(
            'pageSizeW' => Converter::cmToTwip(4), // 宽度转换为twips
            'pageSizeH' => Converter::cmToTwip(2), // 高度转换为twips
            'marginLeft' => Converter::cmToTwip(0.2),
            'marginRight' => Converter::cmToTwip(0),
            'marginTop' => Converter::cmToTwip(0.2),
            'marginBottom' => Converter::cmToTwip(0),
        ));

        // 在节中添加一些内容
        // 添加文本
        $text = '这是一段测试文本,啊实打实的';
        $text1 = '这是一段测试文本,啊实打实的';
        $text2 = '这是一段测试文本,啊实打实的';
        // 检查文本宽度是否超过纸张宽度
        $fontStyle = ['name' => 'Arial', 'size' => 12, 'bold' => true];

        // 比较文本宽度和纸张宽度
        $section->addText(mb_substr($text, 0, 8, 'UTF-8'), $fontStyle);
        $section->addText(mb_substr($text1, 0, 8, 'UTF-8'), $fontStyle);
        $section->addText(mb_substr($text2, 0, 8, 'UTF-8'), $fontStyle);
        $section->addText(mb_substr($text, 0, 8, 'UTF-8'), $fontStyle);
        $section->addText(mb_substr($text1, 0, 8, 'UTF-8'), $fontStyle);
        $section->addText(mb_substr($text2, 0, 8, 'UTF-8'), $fontStyle);

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

        $url =  '/export/' . date('Y-m') . '/' . '标签单-' . date('Y-m-d') . '.docx';

        $a = $objWriter->save(public_path() . $url);
        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]);
    }
}