<?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\LeaveMessageModel;
use app\index\model\SysBannerModel;
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']);
            }])
            ->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->each(function($item) {
                if (Str::contains($item->title, '<br/>')) {
                    $title             = explode('<br/>', $item->title);
                    $item->title       = $title[0];
                    $item->title_short = $title[1];
                }
                return $item;
            })->chunk(4)->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('contact_message.send_fail'));
            }

            return success(lang('contact_message.send_success'));
        }

        $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']);
            }])
            ->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',
                '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'     => request()->header('host'),
               '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('contact_distributor.send_fail'));
            }
            return success(lang('contact_distributor.send_success'));
        }

        // 获取企业规模
        $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');
    }
}
