<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\model\AgentBusinessTypeModel;
use app\index\model\AgentEnterpriseSizeTypeModel;
use app\index\model\AgentModel;
use app\index\model\BulkPurchaseInquiryModel;
use app\index\model\LeaveMessageModel;
use app\index\model\SysBannerModel;
use app\index\model\SysConfigModel;
use app\index\validate\ContactUsBulkBuyValidate;
use app\index\validate\ContactUsDistributorValidate;
use app\index\validate\ContactUsMessageValidate;
use think\facade\View;
use \think\helper\Str;

/**
 * 联系我们控制器
 */
class ContactUs extends Common
{
    /**
     * 联系我们
     */
    public function index()
    {
        $focus_image = [];
        $info_datas  = [];
        // 获取banner
        $banner = SysBannerModel::with(['items' => function($query) {
                $query->withoutField(['status', 'created_at', 'updated_at', 'deleted_at'])
                    ->where('status', '=', 1)
                    ->order(['sort' => 'asc', 'id' => 'desc']);
            }])
            ->atPlatform(request()->from)
            ->uniqueLabel(['BANNER_6805e3d32dcc2', 'BANNER_6806090c1838f'])
            ->language($this->lang_id)
            ->enabled(true)
            ->select();
        if (!$banner->isEmpty()) {
            $banner_map = [];
            foreach ($banner as $v) {
                $banner_map[$v->unique_label] = $v;
            }
            $focus_image = data_get($banner_map, 'BANNER_6805e3d32dcc2')?->items->first()?->toArray();
            $info_datas  = data_get($banner_map, 'BANNER_6806090c1838f')?->items->toArray();
        }
        View::assign('focus_image', $focus_image);
        View::assign('info_datas', $info_datas);

        return View::fetch('index');
    }

    /**
     * 留言联系我们
     */
    public function message()
    {
        if (request()->isPost()) {
            // 提交留言处理
            $form_data = request()->post([
                'name',
                'email',
                'content'
            ]);

            // 数据校验
            $validate = new ContactUsMessageValidate;
            if (!$validate->check($form_data)) {
                return error($validate->getError());
            }
            
            // 保存留言
            $msg = LeaveMessageModel::create([
                'language_id' => $this->lang_id,
                'name'        => $form_data['name'],
                'email'       => $form_data['email'],
                'content'     => $form_data['content'],
                'ip'          => request()->ip(),
                'user_agent'  => request()->header('user-agent'),
            ]);
            if ($msg->isEmpty()) {
                return error(lang('信息提交失败！'));
            }

            return success(lang('信息已成功提交！'));
        }

        $focus_image     = [];
        $our_information = [];
        // 获取我的信息banner
        $banner = SysBannerModel::with(['items' => function($query) {
                $query->withoutField(['status', 'created_at', 'updated_at', 'deleted_at'])
                    ->where('status', '=', 1)
                    ->order(['sort' => 'asc', 'id' => 'desc']);
            }])
            ->atPlatform(request()->from)
            ->uniqueLabel([
                'BANNER_6801be1e7d686',
                'BANNER_6801c053ce12e',
            ])
            ->language($this->lang_id)
            ->enabled(true)
            ->select();
        if (!$banner->isEmpty()) {
            $banner_map = [];
            foreach ($banner as $v) {
                $banner_map[$v->unique_label] = $v;
            }
            $focus_image     = data_get($banner_map, 'BANNER_6801be1e7d686')?->items->first()?->toArray();
            $our_information = data_get($banner_map, 'BANNER_6801c053ce12e')?->items->toArray();
        }
        View::assign('focus_image', $focus_image);
        View::assign('our_information', $our_information);

        return View::fetch('message');
    }

    /**
     * 留言成为分销商
     */
    public function distributor()
    {
        if (request()->isPost()) {
            // 提交留言处理
            $form_data = request()->post([
                'corp_name',
                'email',
                'phone',
                'website_url',
                'business_type',
                'enterprise_size',
                'address',
                'message'
            ]);

            // 验证字段
            $validate = new ContactUsDistributorValidate;
            if (!$validate->check($form_data)) {
                return error($validate->getError());
            }

            // 保存留言
            $ret = AgentModel::create([
               'language_id'     => $this->lang_id,
               'corp_name'       => $form_data['corp_name'],
               'email'           => $form_data['email'],
               'phone'           => $form_data['phone'],
               'referer_url'     => request()->header('referer'),
               'website_url'     => $form_data['website_url'],
               'business_type'   => $form_data['business_type'],
               'enterprise_size' => $form_data['enterprise_size'],
               'address'         => $form_data['address'],
               'message'         => $form_data['message'],
               'ip'              => request()->ip(),
            ]);
            if ($ret->isEmpty()) {
                return error(lang('信息提交失败！'));
            }
            return success(lang('信息已成功提交！'));
        }

        // 获取企业规模
        $sizes = AgentEnterpriseSizeTypeModel::language($this->lang_id)->select();
        View::assign('sizes', $sizes);

        // 获取企业业务类型
        $types = AgentBusinessTypeModel::language($this->lang_id)->select();
        View::assign('types', $types);
        
        return View::fetch('distributor');
    }

    /**
     * 留言批量购买
     */
    public function bulkbuy()
    {
        if (request()->isPost()) {
            // 提交留言处理
            $form_data = request()->post([
                'corp_name',
                'url',
                'first_name',
                'last_name',
                'email',
                'phone',
                'interested',
                'message'
            ]);

            // 验证字段
            $validate = new ContactUsBulkBuyValidate;
            if (!$validate->check($form_data)) {
                return error($validate->getError());
            }

            // 保存留言
            $ret = BulkPurchaseInquiryModel::create([
                'language_id' => $this->lang_id,
                'corp_name'   => $form_data['corp_name'],
                'url'         => $form_data['url'],
                'first_name'  => $form_data['first_name'],
                'last_name'   => $form_data['last_name'],
                'email'       => $form_data['email'],
                'phone'       => $form_data['phone'],
                'interested'  => is_array($form_data['interested']) ? implode(',', $form_data['interested']) : $form_data['interested'],
                'referer_url' => request()->header('referer'),
                'website_url' => request()->header('host'),
                'message'     => $form_data['message'],
                'ip'          => request()->ip(),
            ]);
            if ($ret->isEmpty()) {
                return error(lang('信息提交失败！'));
            }
            return success(lang('信息已成功提交！'));
        }

        // 获取可选产品品类配置
        $config = SysConfigModel::hasWhere('group', function($query) {
                $query->where('language_id', '=', $this->lang_id);
            })
            ->byName('bulk_purchase_inquiry_interested')
            ->find();
        if (empty($config)) {
            return error(lang('当前选定语言的采购可选品类配置出错'));
        }
        View::assign('interested', explode(',', preg_replace('/\r?\n/', ',', $config->value)));

        return View::fetch('bulkbuy');
    }
}
