<?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\adminapi\logic\user\UserLogic;
use app\common\model\property\PropertyHead;
use app\common\logic\BaseLogic;
use app\common\model\user\User;
use app\common\service\wechat\WeChatMnpService;
use Exception;
use think\facade\Db;
use think\facade\Log;


/**
 * PropertyHead逻辑
 * Class PropertyHeadLogic
 * @package app\adminapi\logic
 */
class PropertyHeadLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/09/19 10:48
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            PropertyHead::create([
                'property_name' => $params['property_name'],
                'village_name' => $params['village_name'],
                'address' => $params['address'],
                'head_name' => $params['head_name'],
                'head_mobile' => $params['head_mobile'],
                'ratio' => $params['ratio'],
                'head_bank_card' => $params['head_bank_card'],
                'lon' => $params['lon'],
                'lat' => $params['lat'],
                'remark' => $params['remark'],
                'bind_date'=>!empty($params['bind_date'])?$params['bind_date']:0,
                'sale_type'=>$params['sale_type']??0,
                'sale_id'=>$params['sale_id']??0,
            ]);

            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/09/19 10:48
     */
    public static function edit(array $params): bool
    {
        $headMobile = PropertyHead::where('id', $params['id'])->value('head_mobile');
        Db::startTrans();
        try {
            // 手机号不同时做判断
            if($headMobile != $params['head_mobile']){
                $user = User::where(['mobile' => $params['head_mobile']])->findOrEmpty();
                if (!$user->isEmpty()) {
                    throw new \Exception('该手机号已被注册');
                }
                // 更换用户手机号 account
                User::where(['mobile' => $headMobile])->save(['mobile' => $params['head_mobile']]);
            }
            PropertyHead::where('id', $params['id'])->update([
                'property_name' => $params['property_name'],
                'village_name' => $params['village_name'],
                'address' => $params['address'],
                'head_name' => $params['head_name'],
                'head_mobile' => $params['head_mobile'],
                'ratio' => $params['ratio'],
                'head_bank_card' => $params['head_bank_card'],
                'lon' => $params['lon'],
                'lat' => $params['lat'],
                'remark' => $params['remark'],
                'bind_date'=>!empty($params['bind_date'])?$params['bind_date']:0,
                'sale_type'=>$params['sale_type']??0,
                'sale_id'=>$params['sale_id']??0,
            ]);


            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/09/19 10:48
     */
    public static function delete(array $params): bool
    {
        return PropertyHead::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/09/19 10:48
     */
    public static function detail($params): array
    {
        return PropertyHead::findOrEmpty($params['id'])->toArray();
    }

    public static function updateUserId(string $head_mobile,int $userId): bool
    {
        Db::startTrans();
        try {
            PropertyHead::where('head_mobile', $head_mobile)->update(['user_id' => $userId]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
    public static function selectList(): array
    {
        return PropertyHead::where('id','>',0)->select()->toArray();
    }

    /**
     * @param $params
     * @param $url
     * @return string
     */
    public static function getWechatQrcode($params,$url)
    {
        try {
            $mnp_page = 'pages/tabView/main';
            $response = (new WeChatMnpService())->getUnlimitedQRCode(
                'property_head_id='.$params['id'],
                $mnp_page,
                env('miniprogram.mini_env_version', 'release'),
                false
            );
            $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);
            return  'data:png;base64,' . base64_encode(file_get_contents($file_name));
        } catch (\Throwable $e) {
            Log::info('getQRCode:'.$e->getMessage());
            return '';
        }
    }
}