<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\property;


use app\common\model\coupon\CouponRules;
use app\common\model\property\PropertyActivity;
use app\common\logic\BaseLogic;
use app\common\service\wechat\WeChatMnpService;
use think\db\Query;
use think\Exception;
use think\facade\Db;
use think\facade\Log;


/**
 * PropertyActivity逻辑
 * Class PropertyActivityLogic
 * @package app\adminapi\logic
 */
class PropertyActivityLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/11/21 15:04
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            PropertyActivity::create([
                'property_head_id' => $params['property_head_id'],
                'activity_name' => $params['activity_name'],
                'activity_start_time' => $params['activity_start_time']?strtotime($params['activity_start_time']):0,
                'activity_end_time' => $params['activity_end_time']?strtotime($params['activity_end_time']):0,
                'block_data' => self::configureReservedField($params['block_data']??[], 'block_data'),
                'coupon_data' => self::configureReservedField($params['coupon_data']??[], 'coupon_data'),
                'url_page' => $params['url_page']??'',
                'page_type' => $params['page_type']??0,
                'images' => $params['images']??[],
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/11/21 15:04
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            PropertyActivity::where('id', $params['id'])->update([
                'property_head_id' => $params['property_head_id'],
                'activity_name' => $params['activity_name'],
                'activity_start_time' => $params['activity_start_time']?strtotime($params['activity_start_time']):0,
                'activity_end_time' => $params['activity_end_time']?strtotime($params['activity_end_time']):0,
                'block_data' => json_encode(self::configureReservedField($params['block_data']??[], 'block_data')),
                'coupon_data' => json_encode(self::configureReservedField($params['coupon_data']??[], 'coupon_data')),
                'url_page' => $params['url_page']??'',
                'page_type' => $params['page_type']??0,
                'images' => json_encode($params['images']??[]),
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
    public static function configureReservedField($data, $reserved_type,$reserved_field = []): array
    {
        if($reserved_type === 'block_data'){
            $reserved_field = ['id','recommend_weight','goods_name','base_service_fee','service_total','service_fee','activity_service_fee'];
            foreach ($data as $key => &$item) {
                $data[$key]['block_key'] = $key+1;
                foreach ($item['goods'] as &$good) {
                    foreach ($good as $k=>$v) {
                        if(!in_array($k,$reserved_field)){
                            unset($good[$k]);
                        }
                    }
                }
            }
        }
        if($reserved_type === 'coupon_data'){
            $reserved_field = ['id','voucher_count','voucher_status','server_category_name','event_name','couponWithCategory','expire_time',
                    'amount_require','amount','max_deductible_price','discount_ratio','mold_type','coupon_type','code','remaining_count'
                ];
            foreach ($data as &$item) {
                foreach ($item as $k=>$v) {
                    if(!in_array($k,$reserved_field)){
                        unset($item[$k]);
                    }
                }
            }
        }
        return $data??[];
    }

    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/11/21 15:04
     */
    public static function delete(array $params): bool
    {
        return PropertyActivity::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/11/21 15:04
     */
    public static function detail($params): array
    {
        return PropertyActivity::findOrEmpty($params['id'])->toArray();
    }

    public static function getQRCode($params,$url='weixiu.kyjlkj.com')
    {
        try {
//            $mnp_page = (isset($params['mnp_page']) && $params['mnp_page'])?urldecode($params['mnp_page']):env('miniprogram.property_activity_qrcode', '');
            $mnp_page = 'pages/web_view/index';
            if(empty($params['mnp_page'])){
                throw new Exception('路径错误');
            }
            $scene_page = (isset($params['mnp_page']) && $params['mnp_page'])? $params['mnp_page']:'';
            Log::info('getQRCode:'.rawurlencode($scene_page));
            $response = (new WeChatMnpService())->getUnlimitedQRCode(
                'page='.$scene_page.'&id='.$params['id'],
                $mnp_page,
                env('miniprogram.mini_env_version', 'release'),
                false
            );
            Log::info('getQRCode:'.json_encode([$response]));
            $qrcode = $response->getContent();
            if(!is_dir('./uploads/wx_qrcode/'.date('Ymd'))){
                mkdir('./uploads/wx_qrcode/'.date('Ymd'));
            }
            $file_name = 'uploads/wx_qrcode/'.date('Ymd').'/'.time().rand(1000,9999).'.png';
            file_put_contents($file_name, $qrcode);

            //$file_name = 'https://fushencdn.kyjlkj.com/uploads/miniqrcode/27f140aae615bbe16c1e888c14c9ab10.png';
            return $url.'/'.$file_name;
        } catch (\Throwable $e) {
            Log::info('getQRCode:'.$e->getMessage());
            return '';
        }
    }


    public static function newDataExecute()
    {
        try {
            $activity_list = PropertyActivity::select()->toArray();
            foreach ($activity_list as &$item) {
                if(!empty($item['block_data'])){
                    for ($i = 0; $i < count($item['block_data']); $i++) {
                        $item['block_data'][$i]['block_key'] = $i+1;
                    }
                    PropertyActivity::where('id',$item['id'])->update(['block_data'=>json_encode($item['block_data'])]);
                }
            }
            return true;
        } catch (\Throwable $e) {
            return $e->getMessage();
        }
    }

}