<?php

namespace App\Console\Commands;

use App\Models\PortalStatusArticle;
use Illuminate\Console\Command;
use App\Models\Article;
use App\Models\UserInfo;
use App\Models\RelationInterior;
use App\Models\MstStationPortal;
use App\Models\MstAddressPortal;
use Illuminate\Support\Facades\Auth;
use App\Models\MstStore;
use Illuminate\Support\Facades\Storage;
use voku\helper\HtmlDomParser;
use voku\helper\SimpleHtmlDom;

class SetArticleToHomes extends Command
{
    private $option;
    private $countError;
    private $canRecursive;
    private $type;
    private $textNumber;

    const DIRECTORY = 'data/homes';

    const KANRININ_JOUCHU = 1;
    const KANRININ_NIKKIN = 2;
    const KANRININ_JUNKAI = 3;
    const KANRININ_NONE = 4;
    const KANRININ_HIJOUKIN = 5;
    const KANRIKEITAI_JISHU = 1;
    const KANRIKEITAI_ICHIBU_ITAKU = 2;
    const KANRIKEITAI_ZENBU_ITAKU = 3;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'batch:test2 {id?} {type?} {user?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    protected $indexUrl = 'https://manager.homes.co.jp/index.php';

    protected $numberConverter = ["1" => "１", "2" => "２", '3' => "３" , '4' => "４", '5' => '５', '6' => '６', '7' => '７', '8' => '８', '9' => '９', '10' => '１０' ];
    protected $textJpToNumber = ["一" => "１", "二" => "２", '三' => "３" , '四' => "４", '五' => '５', '六' => '６', '七' => '７', '八' => '８', '九' => '９', '十' => '１０' ];
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->textNumber = ["", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
        $this->textNumberjp = ["", "１", "２", "３", "４", "５", "６", "７", "８", "９", "１０"];

        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        logHomes('Start ==========');
        // 登録対象の物件を取得
        $building_id = $this->argument('id');
        $this->type = $this->argument('type');
        $this->user = $this->argument('user');

        Auth::login($this->user);

        $company_id = $this->user->company_id;

        logHomes("-- Data article: builing_id = $building_id, user_id = " . $this->user->id . ", company_id = $company_id, type = " . $this->type);
        $this->countError = 0;
        $this->canRecursive = true;

        $this->loginHome();
        //$this->getDataAddress('YXYTtClbxmDXi-RBdHFC_A', '沖縄県');
        //$this->SaleInquiryList();
        //dd('done');

        $article = Article::getDataById($building_id);
        $articlePortal = PortalStatusArticle::getDataById($building_id, 2);
        $article->homes_no = null;
        if(!empty($articlePortal)){
            $article->homes_no = $articlePortal->portal_id;
            $article->panorama_homes = $articlePortal->panorama_homes;
        }

        //Recomment when code done
        // if (!empty($article->homes_no)) {
        //     $this->checkId($article);
        // }
        if ($article->property == 1 || $article->property == 2 || $article->property == 3) {
            // 土地
            $article = $this->moldingDataLand($article);
            logHomes('-- Data land: ' . jsonEncodeJp($article));
            $this->saveData($article);
        } elseif ($article->property == 4 || $article->property == 5) {
            // 戸建
            $article = $this->moldingDataHouse($article);
            logHomes('-- Data house: ' . jsonEncodeJp($article));
            $this->saveData($article);
        } else {
            // マンション
            $mansion = Article::getParentMansion($article->mansion_id);
            if (isset($mansion)) {
                $article = $this->moldingDataMansion($article, $mansion);
                logHomes('-- Data mansion: ' . jsonEncodeJp($article));
                $this->saveData($article);
            }
        }

        logHomes('End ==========');
    }

    function getDataAddress($pre_id, $pre_name)
    {
        // 物件登録画面へアクセス 土地1区画
        $url = "https://manager.homes.co.jp/ajax/index.php";

        // 土地1区画
        $POST_DATA = array(
            'id'        =>  $pre_id,
            'type'      =>  'addr1',
            'addr1'     =>  $pre_id,
            'action'    =>  'ajaxdata_addrselect',
            'func'      =>  'reins'
        );

        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($POST_DATA)); // POST変数をセット
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt_array($curl, $this->option);
        $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行

        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $response = substr($res, $header_size);
        $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");

        preg_match_all('/<select name="" id="">(.*?)<\/select>/s', $response, $matches);
        $select = $matches[1][1];
        preg_match_all('/<option value="(.*?)"\s*>(.*?)<\/option>/', $select, $matches, PREG_SET_ORDER);

        $data = [];
        foreach ($matches as $a => $val) {
            if ($a > 50 and $a <= 55) {
                $area_id = $val[1];
                $area_name = $val[2];
                //dd($area_name);
                if ($area_id != "") {
                    $POST_DATA1 = array(
                        'id' => $area_id,
                        'type' => 'addr2',
                        'addr1' => $pre_id,
                        'addr2' => $area_id,
                        'action' => 'ajaxdata_addrselect',
                        'func' => 'reins'
                    );

                    $curl = curl_init(); // cURLセッションの初期化
                    curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
                    curl_setopt($curl, CURLOPT_POST, TRUE);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($POST_DATA1)); // POST変数をセット
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
                    curl_setopt_array($curl, $this->option);
                    $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行

                    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
                    $response = substr($res, $header_size);
                    $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");

                    preg_match_all('/<select name="" id="">(.*?)<\/select>/s', $response, $matches1);
                    $select1 = $matches1[1][2];

                    preg_match_all('/<option value="(.*?)"\s*>(.*?)<\/option>/', $select1, $matches1, PREG_SET_ORDER);
                    foreach ($matches1 as $val1) {
                        $town_id = $val1[1];
                        $town_name = $val1[2];
                        if ($town_id != '') {
                            $POST_DATA2 = array(
                                'id' => $town_id,
                                'type' => 'addr3',
                                'addr1' => $pre_id,
                                'addr2' => $area_id,
                                'addr3' => $town_id,
                                'action' => 'ajaxdata_addrselect',
                                'func' => 'reins'
                            );

                            $curl = curl_init(); // cURLセッションの初期化
                            curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
                            curl_setopt($curl, CURLOPT_POST, TRUE);
                            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($POST_DATA2)); // POST変数をセット
                            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
                            curl_setopt_array($curl, $this->option);
                            $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行

                            $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
                            $response = substr($res, $header_size);
                            $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");

                            preg_match_all('/<select name="" id="">(.*?)<\/select>/s', $response, $matches2);
                            $select2 = $matches2[1][3];

                            preg_match_all('/<option value="(.*?)"\s*>(.*?)<\/option>/', $select2, $matches2, PREG_SET_ORDER);
                            foreach ($matches2 as $val2) {
                                $town_more_id = $val2[1];
                                $town_more_name = $val2[2];
                                if ($town_more_id != '') {
                                    $check = MstAddressPortal::where('pref_id', $pre_id)->where('area_id', $area_id)->where('town_id', $town_id)->where('town_more_id', $town_more_id)->count();
                                    if ($check == 0) {
                                        $data = [
                                            "pref_id" => $pre_id,
                                            "pref_name" => $pre_name,
                                            "area_id" => $area_id,
                                            "area_name" => $area_name,
                                            "town_id" => $town_id,
                                            "town_name" => $town_name,
                                            "town_more_id" => $town_more_id,
                                            "town_more_name" => $town_more_name,
                                            "type" => 1
                                        ];
                                        MstAddressPortal::create($data);
                                    }
                                } else {
                                    if (count($matches2) == 1) {
                                        $check = MstAddressPortal::where('pref_id', $pre_id)->where('area_id', $area_id)->where('town_id', $town_id)->count();
                                        if ($check == 0) {
                                            $data = [
                                                "pref_id" => $pre_id,
                                                "pref_name" => $pre_name,
                                                "area_id" => $area_id,
                                                "area_name" => $area_name,
                                                "town_id" => $town_id,
                                                "town_name" => $town_name,
                                                "town_more_id" => '',
                                                "town_more_name" => '',
                                                "type" => 1
                                            ];
                                            MstAddressPortal::create($data);
                                        }
                                    }
                                }
                            }
                        } else {
                            if (count($matches1) == 1) {
                                $check = MstAddressPortal::where('pref_id', $pre_id)->where('area_id', $area_id)->count();
                                if ($check == 0) {
                                    $data = [
                                        "pref_id" => $pre_id,
                                        "pref_name" => $pre_name,
                                        "area_id" => $area_id,
                                        "area_name" => $area_name,
                                        "town_id" => '',
                                        "town_name" => '',
                                        "town_more_id" => '',
                                        "town_more_name" => '',
                                        "type" => 1
                                    ];
                                    MstAddressPortal::create($data);
                                }
                            }
                        }
                    }
                }
            }
        }

        return true;
    }

    function log($res)
    {
        $res = str_replace("物件メンテ - 入力｜売買｜LIFULL HOME'S Manager", "HOME's LOCAL", $res);
        $res = mb_convert_encoding($res, 'EUC-JP', 'UTF-8');
        $res = str_replace('src="/', 'src="https://manager.homes.co.jp/', $res);
        $res = str_replace('href="/', 'href="https://manager.homes.co.jp/', $res);
        Storage::disk('public')->put('home_response.html', $res);
    }

    function loginHome()
    {
        logHomes("-- Login HOMES: Start.");
        if ($this->countError >= 5) {
            $this->canRecursive = false;
            logHomes("-- -- Can not recursive.");
            logHomes("-- Login HOMES: End.");
            return;
        }
        // Homesにアクセス
        $this->info("Start login Home");

        $cookie_path = './homes_cookie.txt';
        touch($cookie_path);
        //$id = "takara@wills.co.jp";
        //$pass = "OaOJ0FGg4E";
        $user = $this->user;
        $shop = MstStore::getDataByCode($user->company_id, $user->store_id);
        $id = $shop->homes_id;
        $pass = $shop->homes_pw;
        $orgChecked = $shop->homes_org_checked;
        logHomes("-- -- Account: id = $id, pass = $pass.");

        // cURLセッションの共通オプション
        $this->option = [
            // CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0',
            CURLOPT_SSL_VERIFYPEER => FALSE,
            CURLOPT_SSL_VERIFYHOST => FALSE,
            CURLOPT_COOKIEJAR => $cookie_path,
            CURLOPT_COOKIEFILE => $cookie_path,
            // CURLOPT_FOLLOWLOCATION => TRUE,
            CURLOPT_HEADER => TRUE,
        ];

        // ログイン画面へアクセス
        $url = "https://lifull.my.site.com/pro/userlogin?startURL=%2Fpro%2Ftop";
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        $res = curl_exec($curl); // cURLセッションの実行
        if ($res === false) {
            $err = curl_error($curl);
            curl_close($curl);
            logHomes("-- -- Login HOMES failed (Step 1 - $url): $err.");
            logHomes("-- Login HOMES: End.");
            die("error $err");
        }

        curl_close($curl);

        // cURLセッション実行結果の解析
        $pattern = '/<form id="(.*?)" name="(.*?)" method="post" action="(.*?)" enctype="application\/x-www-form-urlencoded">/';
        preg_match($pattern, $res, $match1);

        $pattern = '/<input type="hidden"  id="com.salesforce.visualforce.ViewState" name="com.salesforce.visualforce.ViewState" value="(.*?)" \/>/';
        preg_match($pattern, $res, $match2);

        $pattern = '/<input type="hidden"  id="com.salesforce.visualforce.ViewStateVersion" name="com.salesforce.visualforce.ViewStateVersion" value="(.*?)" \/>/';
        preg_match($pattern, $res, $match3);

        $pattern = '/<input type="hidden"  id="com.salesforce.visualforce.ViewStateMAC" name="com.salesforce.visualforce.ViewStateMAC" value="(.*?)" \/>/';
        preg_match($pattern, $res, $match4);


        // ログイン処理
        $url = $match1[3];
        $POST_DATA = [
            $match1[1] => $match1[1],
            'j_id0:j_id13:j_id23' => $id,
            'j_id0:j_id13:j_id25' => $pass,
            'j_id0:j_id13:j_id32' => 'ログイン',
            'com.salesforce.visualforce.ViewState' => $match2[1],
            'com.salesforce.visualforce.ViewStateVersion' => $match3[1],
            'com.salesforce.visualforce.ViewStateMAC' => $match4[1],
        ];

        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($POST_DATA)); // POST変数をセット
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
        $res = curl_exec($curl); // cURLセッションの実行
        if ($res === false) {
            $err = curl_error($curl);
            curl_close($curl);
            logHomes("-- -- Login HOMES failed (Step 2 - $url): $err.");
            logHomes("-- Login HOMES: End.");
            die("error $err");
        }
        curl_close($curl);

        // https://homes.force.com/pro/secur/frontdoor.jspのパラメータ付きURLを取得したいが、Cookieに応じて実行結果が変わる
        // Cookieが無い状態からバッチを起動すると正常処理になるので、Cookieの削除処理を最後に加える？

        // cURLセッション実行結果の解析
        $pattern = '/window\.location\.href =\'(.*?)\';/';
        preg_match($pattern, $res, $match5);

        if ($match5) {
            $url = $match5[1];
        }
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
        curl_setopt_array($curl, $this->option); // 共通オプションの設定
        $res = curl_exec($curl); // cURLセッションの実行
        if ($res === false) {
            $err = curl_error($curl);
            curl_close($curl);
            logHomes("-- -- Login HOMES failed (Step 3 - $url): $err.");
            logHomes("-- Login HOMES: End.");
            die("error $err");
        }
        curl_close($curl);

        // Homesトップ画面にアクセス
        $url = 'https://lifull.my.site.com/pro/top';
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
        curl_setopt_array($curl, $this->option); // 共通オプションの設定
        $res = curl_exec($curl); // cURLセッションの実行
        if ($res === false) {
            $err = curl_error($curl);
            curl_close($curl);
            logHomes("-- -- Login HOMES failed (Step 4 - $url): $err.");
            logHomes("-- Login HOMES: End.");
            die("error $err");
        }
        curl_close($curl);

        // cURLセッション実行結果の解析
        $pattern = '/<h3 class="lhProService__contentHeading"><a href="(.*?)" target="_blank" class="lhProService__link/';
        preg_match($pattern, $res, $match6);
        if ($orgChecked === 1){
            $url = $this->getOrgUrl($res, $shop);
            if (!isset($url)){
                $this->countError++;
                logHomes("-- -- Login HOMES failed: Re-login.");
                return $this->loginHome();
            }
        }else {
            // LIFULL HOME'S Managerにログイン情報を連携
            if (count($match6) < 2) {
                $res = mb_convert_encoding($res, "UTF-8", "EUC-JP");
                $this->log($res);
                logHomes("-- -- Login HOMES failed: Error insert article into Home match6.");
                $this->countError++;
                return $this->loginHome();
            }
            $url = $match6[1];
        }
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
        curl_setopt_array($curl, $this->option); // 共通オプションの設定
        $res = curl_exec($curl); // cURLセッションの実行
        if ($res === false) {
            $err = curl_error($curl);
            curl_close($curl);
            logHomes("-- -- Login HOMES failed (Step 5 - $url): $err.");
            logHomes("-- Login HOMES: End.");
            die("error $err");
        }
        curl_close($curl);

        // cURLセッション実行結果の解析
        $pattern = '/SfdcApp\.projectOneNavigator\.handleRedirect\(\'(.*?)\'\)\; \}  else/';
        preg_match($pattern, $res, $match7);

        if (count($match7) < 2) {
            $res = mb_convert_encoding($res, "UTF-8", "EUC-JP");
            $this->log($res);
            logHomes("-- -- Login HOMES: Error insert article into Home match7.");
            $this->countError++;
            return $this->loginHome();
        }
        $url = $match7[1];
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
        curl_setopt_array($curl, $this->option); // 共通オプションの設定
        $res = curl_exec($curl); // cURLセッションの実行
        if ($res === false) {
            $err = curl_error($curl);
            curl_close($curl);
            logHomes("-- -- Login HOMES failed (Step 6 - $url): $err.");
            logHomes("-- Login HOMES: End.");
            die("error $err");
        }
        curl_close($curl);

        logHomes('-- -- Login HOMES success.');
        logHomes("-- Login HOMES: End.");
    }

    function getOrgUrl($res, $shop){
        $dom = HtmlDomParser::str_get_html($res);
        $modeTable = $dom->find('.mod-table');
        foreach ($modeTable->find('tr') as $tr) {
            $th = @$tr->find('th')->plaintext[0] ?? '';
            $a = $tr->findOne('td a');
            if (isset($a)){
                $href = $a->getAttribute('href');
                if ($shop->homes_org_name === html_entity_decode($th) && strpos($href, 'https://manager.homes.co.jp/index.php?ref=cpf') !== false){
                    return $href;
                }
            }
        }
        return null;
    }


    function requestWithData($url, $data, $isPost = false, $headers = [], $followLocation = false)
    {
        logHomes('-- -- CURL Request with data: Start.');
        logHomes("-- -- -- CURL Data: url = $url, data = " . jsonEncodeJp($data));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        if ($isPost) {
            curl_setopt($curl, CURLOPT_POST, $isPost);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($curl, CURLINFO_HEADER_OUT, TRUE);
            curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
        }

        curl_setopt_array($curl, $this->option);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        if ($followLocation) {
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
        }
        //        $curl_log = fopen(base_path("curl.txt"), 'w');
        //        curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
        //        curl_setopt($curl, CURLOPT_STDERR, $curl_log);

        $response = curl_exec($curl);
        if ($response === false) {
            $err = curl_error($curl);
            curl_close($curl);
            logHomes("-- -- -- CURL Request with data failed: $err.");
            logHomes('-- -- CURL Request with data: End.');
            die("error $err");
        }

        curl_close($curl);
        logHomes('-- -- -- CURL Request with data: Success.');
        logHomes('-- -- CURL Request with data: End.');
        return $response;
    }

    function detectAndHandleSaveSuccess($response, $buildingId)
    {
        logHomes('-- -- detectAndHandleSaveSuccess: Start.');
        $user = $this->user;
        $shop = MstStore::getDataByCode($user->company_id, $user->store_id);

        $pattern = '/class="saveNotice">(.*?)/';
        preg_match_all($pattern, $response, $matchSaveSuccess);

        $pattern = '/<form name="bukken_confirm" method="post" action="index.php">([^$]+?)<\/div>/';
        preg_match_all($pattern, $response, $matchStep2);

        if (count($matchSaveSuccess) > 1 && count($matchSaveSuccess[0]) > 0) {
            // Get id and save into article
            $urlGetId = 'https://manager.homes.co.jp/index.php?action=sale_reg_top';
            $response = $this->requestWithData($urlGetId, []);
            $pattern = '/&b1=(.*?)"/';
            $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
            preg_match_all($pattern, $response, $matchId);
            if (count($matchId) > 1 && count($matchId[1]) > 0) {
                $pattern_td = '/<td>(.*?)<\/td>/';
                preg_match_all($pattern_td, $response, $match_td);
                if (count($match_td) > 1) {
                    if (count($match_td[1]) > 7) {
                        $second = time() - strtotime($match_td[1][7]);
                    } else {
                        $second = time() - strtotime($match_td[1][4]);
                    }
                }
                session()->flash('message_ok', 'HOMESに入稿されました');

                PortalStatusArticle::where('portal_id', end($matchId[1]))->where('portal_type', 2)->delete();
                $save_data = [
                    'article_id'    =>  $buildingId,
                    'portal_id'     =>  end($matchId[1]),
                    'portal_user'   =>  $shop->homes_id,
                    'portal_type'   =>  2
                ];
                PortalStatusArticle::insert($save_data);

                logHomes("-- -- -- Up to HOMES success (portal_status_articles = " . jsonEncodeJp($save_data) . ").");
                logHomes('-- -- detectAndHandleSaveSuccess: End.');
                return end($matchId[1]);
            } else {
                session()->flash('message_modal', '入稿できませんでした。物件詳細ページを見直してください。');
                $this->log($response);
                logHomes('-- -- -- Error: 入稿できませんでした。物件詳細ページを見直してください。.');
            }
        } else if (count($matchStep2) > 1 && count($matchStep2[0]) > 0) {
            logHomes('-- -- -- detectAndHandleSaveSuccess: 1.');
            return 1;
        } else {
            $this->log($response);
            $formPattern = '/<a.*?onClick="javascript:tabSwitch.*?>(.*?)<\/a>/';
            preg_match_all($formPattern, $response, $formMatches);
            logHomes('-- -- -- detectAndHandleSaveSuccess: 0.');
            if(count($formMatches) > 1){
                $error = '';
                foreach ($formMatches[1] as $i => $er) {
                    $j = $i + 1;
                    $error .= '<br>' . $j . '. ' . trim($er);
                }
                if (empty($formMatches[1])) {
                    session()->flash('message_ok', 'レコードが削除されたため、HOMESに入稿できませんでした');
                    logHomes('-- -- -- Error: Unable to submit to HOMES because the record has been deleted.');
                } else {
                    session()->flash('message_modal', '<strong>入稿できませんでした。物件詳細ページを見直してください。</strong> ' . $error);
                    logHomes("-- -- -- Error: Submit failed: $error.");
                }
            } else {
                session()->flash('message_modal', '入稿できませんでした。物件詳細ページを見直してください。');
                logHomes("-- -- -- Error: Submit failed: Check formMatches.");
            }

            logHomes('-- -- detectAndHandleSaveSuccess: End.');
            return 0;
        }
    }

    function moldingData($article)
    {
        $b1 = $article->homes_no;
       // if ($article->exterior != 1) {
            if ($article->kenchiku_year == $article->exterior_year && $article->kenchiku_month > $article->exterior_month) {

            } else if ($article->kenchiku_year >= $article->exterior_year) {

            } else {
                $exteriors = $article->exteriors;
                if (count($exteriors) > 0) {
                    $exteriorName = [
                        1 => '外壁',
                        2 => '屋根',
                        3 => 'その他'
                    ];
                    $note = '';
                    $option = '';
                    $note2 = '';

                    foreach ($exteriors as $exterior) {
                        if (($article->exterior == 2 || $article->exterior == 3) && $exterior->item_id == 3) {
                            $article->reform_exterior_other = $article->exterior_text;
                        }

                        //$article->{"reform_exterior_place{$exterior->item_id}"} = $exterior->item_id;
                        if (($article->exterior == 2) && $exterior->item_id == 2) {
                            $article->reform_exterior_year = $article->exterior_year;
                            $article->reform_exterior_month = $article->exterior_month;
                            $article->reform_exterior_place1 = 1;
                            // break;
                        }
                        if (($article->exterior == 2) && $exterior->item_id == 1) {
                            $article->reform_exterior_year = $article->exterior_year;
                            $article->reform_exterior_month = $article->exterior_month;
                            $article->reform_exterior_place2 = 2;
                            // break;
                        }

                        if ($article->exterior == 3 && ($exterior->item_id == 1 || $exterior->item_id == 2)) {
                            $note = '外装工事は';
                            $option .= $exteriorName[$exterior->item_id]. ',';
                            $note2 = $article->exterior_year . ' 年 ' . $article->exterior_month . ' 月 に完了予定' . '。';
                        }
                        if ($article->exterior == 3 && ($exterior->item_id == 3)) {
                            $note = '外装工事は';
                            $option .= $exteriorName[$exterior->item_id]. '('.$article->exterior_text.')'. ',';
                            $note2 = $article->exterior_year . ' 年 ' . $article->exterior_month . ' 月 に完了予定' . '。';
                        }
                    }
                    $article->reform_note = $note. $note2;
                }
            }
     //   }

        if ($article->interior != 1) {

            /*if ($article->kenchiku_year == $article->interior_year && $article->kenchiku_month > $article->interior_month) {
            } else if ($article->kenchiku_year >= $article->interior_year) {
            } else {

            }
            */

            $interior = $article->interior;
            //if (!empty($article->interior_text)) {
            // $article->reform_interior_year = $article->interior_year;
            // $article->reform_interior_month = $article->interior_month;
            // $article->reform_interior_other = $article->interior_text;
            switch ($interior) {
                case 1:
                    $article->reform_wet_area_year = (int) $article->interior_year;
                    $article->reform_wet_area_month = (int) $article->interior_month;
                    $article->reform_wet_area_place1 = 1;
                    $article->reform_interior_other = "キッチン";
                    break;
                case 2:
                    $article->reform_wet_area_year = (int) $article->interior_year;
                    $article->reform_wet_area_month = (int) $article->interior_month;
                    // $article->reform_wet_area_place2 = 2;
                    $article->reform_interior_other = "浴室";
                    break;
                case 3:
                    // $article->reform_wet_area_year = (int) $article->interior_year;
                    // $article->reform_wet_area_month = (int) $article->interior_month;
                    // $article->reform_wet_area_place3 = 3;
                    // $article->reform_interior_other = "トイレ";
                    break;
                case 4:
                    $article->reform_interior_place2 = 2;
                    break;
                case 5:
                    $article->reform_interior_place4 = 4;
                    break;
                case 6:
                    $article->reform_interior_place3 = 3;
                    break;
                case 7:
                    $article->reform_interior_other = $article->interior_text;
                    if (!empty($article->interior_text)) {
                        $article->reform_wet_area_year = (int) $article->interior_year;
                        $article->reform_wet_area_month = (int) $article->interior_month;
                        $article->reform_wet_area_other = '';
                    }
                    break;
            }
        }


        if ($article->event_schedule == 4) {
            if (!empty($article->from_event)) {
                $from_event = explode("-", $article->from_event);
                if (count($from_event) == 3) {
                    $article->or_open_y = $from_event[0];
                    $article->or_open_m = $from_event[1];
                    $article->or_open_d = $from_event[2];
                }
            }
            if (!empty($article->to_event)) {
                $to_event = explode("-", $article->to_event);
                if (count($to_event) == 3) {
                    $article->or_end_y = $to_event[0];
                    $article->or_end_m = $to_event[1];
                    $article->or_end_d = $to_event[2];
                }
            }
        } else if ($article->event_schedule == 3) {
            if (!empty($article->event_day)) {
                $from_event = explode("-", $article->event_day);
                if (count($from_event) == 3) {
                    $article->or_open_y = $from_event[0];
                    $article->or_open_m = $from_event[1];
                    $article->or_open_d = $from_event[2];
                }
            }
        }
        $article->or_time = "{$article->from_hour}時{$article->from_minute}分〜{$article->to_hour}時{$article->to_minute}分";
        $taiyou = "";
        switch ($article->company_manner) {
            case 1:
            case 2:
                $taiyou = 1;
                break;
            case 6:
                $taiyou = 2;
                break;
            case 3:
                $taiyou = 5;
                break;
            case 4:
                $taiyou = 4;
                break;
            case 5:
                $taiyou = 3;
                break;
            case 7:
                $taiyou = 6;
                break;
            case 9:
                $taiyou = 6;
                break;
        }
        $article->taiyou = $taiyou;
        if ($article->mansion_id == null) {
            switch ($article->pet) {
                case 0:
                    $article->ft109 = "";
                    break;
                case 1:
                    $article->ft109 = 3;
                    break;
                case 2:
                    $article->ft109 = 2;
                    break;
            }
        }
        $article->invest = $article->classfication == 1 ? 0 : 2;
        if ($article->mansion_id != null) {
            $mansion = $article->getMansion();
            if (!empty($mansion->sub_traffic2_line)) {
                if ($mansion->sub_traffic2 == 1) {
                    $article->traffic_other = "{$mansion->sub_traffic2_line} {$mansion->sub_traffic2_station}駅 徒歩{$mansion->else_traffic_time}分";
                } else {
                    $article->traffic_other = "{$mansion->sub_traffic2_line} {$mansion->sub_traffic2_station}駅 バス停{$mansion->sub_traffic2_bus}停 乗車{$mansion->sub_traffic2_bus_time}分 徒歩{$mansion->sub_traffic2_bus_walk}分";
                }
            }

            if (!empty($mansion->main_traffic_line)) {
                $ar_temporary_addr1 = [
                    14  =>  14,
                    11  =>  26,
                    12  =>  25,
                    28  =>  28,
                    27  =>  27
                ];
                $article->temporary_addr1 = $ar_temporary_addr1[$mansion->address1];

//                $mainTrafficLine = str_replace("JR", "ＪＲ", $mansion->main_traffic_line);
//                $searchLine = MstStationPortal::where('type', 1)->where('line_name', $mainTrafficLine)->where('station_name', $mansion->main_traffic_station);
//                if ($searchLine->count() == 0) {
//                    $searchLine = MstStationPortal::where('type', 1)->where('station_name', $mansion->main_traffic_station);
//                }
//                $line = $searchLine->first();

                $line = $this->getStationPortal($mansion->main_traffic_line, $mansion->main_traffic_station);

                $article->rosen_etc1 = "1";
                $article->rosen1 = $line->line_id ?? '';
                $article->eki1 = $line->station_id ?? '';
                $article->rosen1_name = $line->line_name ?? '';
                $article->eki1_name = $line->station_name ?? '';;

                if (!empty($mansion->main_traffic) && $mansion->main_traffic == 2) {
                    $article->walk_distance1 = $mansion->main_traffic_bus_walk;
                    $article->bus_time1 = $mansion->main_traffic_bus_time;
                    $article->bus_stop1 = $mansion->main_traffic_bus;
                } else {
                    $article->walk_distance1 = $mansion->main_traffic_time;
                    $article->bus_time1 = "";
                    $article->bus_stop1 = "";
                }
            }
            if (!empty($mansion->sub_traffic1_line)) {
                $ar_temporary_addr1 = [
                    14  =>  14,
                    11  =>  26,
                    12  =>  25,
                    28  =>  28,
                    27  =>  27
                ];
                $article->temporary_addr1 = $ar_temporary_addr1[$mansion->address1];
//                $mainTrafficLine = str_replace("JR", "ＪＲ", $mansion->sub_traffic1_line);
//                $searchLine = MstStationPortal::where('type', 1)->where('line_name', $mainTrafficLine)->where('station_name', $mansion->sub_traffic1_station);
//                if ($searchLine->count() == 0) {
//                    $searchLine = MstStationPortal::where('type', 1)->where('station_name', $mansion->sub_traffic1_station);
//                }
//                $line = $searchLine->first();

                $line = $this->getStationPortal($mansion->sub_traffic1_line, $mansion->sub_traffic1_station);

                $article->rosen_etc2 = "1";
                $article->rosen2 = $line->line_id ?? '';
                $article->eki2 = $line->station_id ?? '';
                if (!empty($mansion->sub_traffic1) && $mansion->sub_traffic1 == 2) {
                    $article->walk_distance2 = $mansion->sub_traffic1_bus_walk;
                    $article->bus_time2 = $mansion->sub_traffic1_bus_time;
                    $article->bus_stop2 = $mansion->sub_traffic1_bus;
                    $article->walk_distance_type2 = "";
                } else {
                    $article->bus_time2 = "";
                    $article->bus_stop2 = "";
                    $article->walk_distance2 = $mansion->sub_traffic1_time;
                }
            }
            if (!empty($mansion->sub_traffic2_line)) {
                if ($mansion->sub_traffic2 == 1) {
                    $article->traffic_other = "{$mansion->sub_traffic2_line} {$mansion->sub_traffic2_station}駅 徒歩{$mansion->sub_traffic2_time}分";
                } else {
                    $article->traffic_other = "{$mansion->sub_traffic2_line} {$mansion->sub_traffic2_station}駅 バス停{$mansion->sub_traffic2_bus}停 乗車{$mansion->sub_traffic2_bus_time}分 徒歩{$mansion->sub_traffic2_bus_walk}分";
                }
            }
            //dd($article->toArray());
        } else {
            if (!empty($article->sub_traffic2_line)) {
                $article->rosen_etc2 = "1";
                if ($article->sub_traffic2 == 1) {
                    $article->traffic_other = "{$article->sub_traffic2_line} {$article->sub_traffic2_station}駅 徒歩{$article->sub_traffic2_time}分";
                } else {
                    $article->traffic_other = "{$article->sub_traffic2_line} {$article->sub_traffic2_station}駅 バス停{$article->sub_traffic2_bus}停 乗車{$article->sub_traffic2_bus_time}分 徒歩{$article->sub_traffic2_bus_walk}分";
                }
            }
            if (!empty($article->main_traffic_line)) {
                $ar_temporary_addr1 = [
                    14  =>  14,
                    11  =>  26,
                    12  =>  25,
                    28  =>  28,
                    27 => 27
                ];
                $article->temporary_addr1 = $ar_temporary_addr1[$article->address1];

//                $mainTrafficLine = str_replace("JR", "ＪＲ", $article->main_traffic_line);
//                $searchLine = MstStationPortal::where('type', 1)->where('line_name', $mainTrafficLine)->where('station_name', $article->main_traffic_station);
//                if ($searchLine->count() == 0) {
//                    $searchLine = MstStationPortal::where('type', 1)->where('station_name', $article->main_traffic_station);
//                }
//                $line = $searchLine->first();

                $line = $this->getStationPortal($article->main_traffic_line, $article->main_traffic_station);

                $article->rosen_etc1 = "1";
                $article->rosen1 = $line->line_id ?? '';
                $article->eki1 = $line->station_id ?? '';
                $article->rosen1_name = $line->line_name ?? '';
                $article->eki1_name =  $line->station_name ?? '';

                if (!empty($article->main_traffic) && $article->main_traffic == 2) {
//                    $article->rosen_etc2 = "1";
                    $article->walk_distance1 = $article->main_traffic_bus_walk;
                    $article->bus_time1 = $article->main_traffic_bus_time;
                    $article->bus_stop1 = $article->main_traffic_bus;
                } else {
                    $article->walk_distance1 = $article->main_traffic_time;
                    $article->bus_time1 = "";
                    $article->bus_stop1 = "";
                }

                if (!empty($article->sub_traffic1_line)) {
                    $article->rosen_etc2 = "1";
                }
            }

            if (!empty($article->sub_traffic1_line)) {
//                $subTrafficLine = str_replace("JR", "", $article->sub_traffic1_line);
//                $searchLine = MstStationPortal::where('type', 1)->where('line_name', $subTrafficLine)->where('station_name', $article->sub_traffic1_station);
//                if ($searchLine->count() == 0) {
//                    $searchLine = MstStationPortal::where('type', 1)->where('station_name', $article->sub_traffic1_station);
//                }
//                $line = $searchLine->first();
                $line = $this->getStationPortal($article->sub_traffic1_line, $article->sub_traffic1_station);
                $article->rosen2 = $line->line_id ?? '';
                $article->eki2 = $line->station_id ?? '';
                if (!empty($article->sub_traffic1) && $article->sub_traffic1 == 2) {
                    $article->rosen_etc2 = "1";
                    $article->walk_distance2 = $article->sub_traffic1_bus_walk;
                    $article->bus_time2 = $article->sub_traffic1_bus_time;
                    $article->bus_stop2 = $article->sub_traffic1_bus;
                    $article->walk_distance_type2 = "";
                } else {
                    $article->bus_time2 = "";
                    $article->bus_stop2 = "";
                    $article->walk_distance2 = $article->sub_traffic1_time;
                }
            }
        }
        if (isset($article->land_chisei) && empty($article->land_chisei)) {
            $article->land_chisei = $article->terrain;
        } else {
            //$article->land_chisei = $article->terrain;
        }

        $article->money_sonota_str1 = $article->another_cost_name1;
        $article->money_sonota_str2 = $article->another_cost_name2;

        $time_limit = date('d/m/Y', strtotime('+2 weeks'));
        $day = explode('/', $time_limit);
        $article->timelimit_date_y = $day[2];
        $article->timelimit_date_m = $day[1];
        $article->timelimit_date_d = $day[0];

        // if ($article->mansion_id != null) {
        //     $article->reform_wet_area_year = '';
        //     $article->reform_wet_area_month = '';
        // }

        if ($article->land_shidou_flg == "") {
            $article->road_numerator = "";
            $article->road_denominator = "";
            $article->land_shidou_flg = 0;
        }
        if ($article->road_burden == 1) {
            $article->road_numerator = "";
            $article->road_denominator = "";
        }

        // if ($article->land_right == 2 || $article->land_right == 3 || $article->land_right == 5) {
        if ($article->land_right != 1 || $article->land_right != 0) {
            if ($article->security_deposit_cost == 1) {
                $article->money_shikikin_ck = 1;
                $article->money_shikikin = $article->security_deposit_cost_val;
                $article->shikiunit = "money";
            }
            if ($article->deposit_cost == 1) {
                $article->money_hoshoukin_ck = 1;
                $article->money_hoshoukin = $article->deposit_cost_val;
                $article->hoshouunit = "money";
            }
        }

        if ($article->interior == 2) {
            $article->reform_interior_year = $article->interior_year;
            $article->reform_interior_month = $article->interior_month;
            $article->reform_interior_other = $article->interior_text;
        }

        if ($article->interior == 3) {
            $interiorName = [
                1 => 'キッチン',
                2 => '浴室',
                3 => 'トイレ',
                4 => '壁',
                5 => '床',
                6 => '全室',
                7 => 'その他'
            ];

            $interior_place = RelationInterior::where('article_id', $article->building_id)->get();
            if ($interior_place) {
                $options = $options2 = '';
                $text = $text2 = '';
                foreach ($interior_place as $v) {
                    if ($v->item_id == 1 || $v->item_id == 2 || $v->item_id == 3) {
                        $text = '水回り工事は ';
                        $options .= $interiorName[$v->item_id] . ',';
                    }
                    if ($v->item_id == 4 || $v->item_id == 5 || $v->item_id == 6) {
                        $text2 = '内装工事は ';
                        $options2 .= $interiorName[$v->item_id] . ',';
                    }
                    if($v->item_id == 7){
                        $options2 .= $interiorName[$v->item_id] .'('. $article->interior_text .')'. ',';
                    }
                }
                $article->reform_note .= $text . $options;
                $article->reform_note .= ' が' . $article->interior_year . ' 年 ' . $article->interior_month . ' 月 に完了予定' . '。';
                $article->reform_note .= $text2 . $options2;
                $article->reform_note .= ' が' . $article->interior_year . ' 年 ' . $article->interior_month . ' 月 に完了予定';
            }
        }


        $response =  [
            "action" => "sale_reg_confirm",
            "pht_photo_delid" => "",
            "money_shuuzenkikin_ck" => $article->money_shuuzenkikin_ck ?? "",
            "money_shuuzenkikin" => (!empty($article->money_shuuzenkikin)) ? $article->money_shuuzenkikin / 10000 : "",
            "ispost" => "1",
            "b1" => $b1 ?? "",
            "b2" => "",
            "b2time" => "",
            "tk" => "1",
            "tab" => "base",
            "photo_order" => "",
            "bt" => $article->bt ?? "1201",
            "land_area_all" => $article->land_area_all ?? "",
            "money_shuuzen" => $article->money_shuuzen ?? "",
            "house_kanrinin" => $article->house_kanrinin ?? "",
            "house_kanri_keitai" => $article->house_kanri_keitai ?? "",
            "house_kanri_kaisha" => $article->house_kanri_kaisha ?? "",
            "b_name" => $article->b_name,
            "money_sonota1_ck" => $article->money_sonota1_ck ?? "",
            "money_sonota2_ck" => $article->money_sonota2_ck ?? "",
            "b_ruby" => "",
            "empty_contents" => $article->empty_contents ?? "",
            "flg_bukken_name" => $article->flg_bukken_name ?? "1",
            "status" => $article->status_h,
            "flg_open" => 0,
            "jss_alert" => "false",
            "timelimit_date_y" => $article->timelimit_date_y ?? "",
            "timelimit_date_m" => $article->timelimit_date_m ?? "",
            "timelimit_date_d" => $article->timelimit_date_d ?? "",
            "tantou_name" => $article->tantou_name,
            "local_id" => $article->building_id,
            "recommend" => "0",
            "post1" => $article->post1,
            "post2" => $article->post2,
            "addr1" => $article->addr1,
            "temporary_addr1" => $article->temporary_addr1 ?? "",
            "addr2" => $article->addr2 ?? "",
            "addr3" => $article->addr3 ?? "",
            "addr4" => "",
            "og_addr11" => "",
            "og_addr12" => "",
            "og_addr2" => "",
            "og_addr2_name" => "",
            "og_post1" => "",
            "og_post2" => "",
            "addr3_addr4_name" => $article->addr3_addr4_name,
            "flg_addr_hidden" => 0,
            "display_addr_name" => "",
            "nl" => "",
            "el" => "",
            "fullmatch" => "1",
            "flg_adjust" => "1",
            "rosen1" => $article->rosen1 ?? "",
            "eki1" => $article->eki1 ?? "",
            "bus_stop1" => $article->bus_stop1 ?? "",
            "bus_time1" => $article->bus_time1 ?? "",
            "walk_distance1" => $article->walk_distance1 ?? "",
            "walk_distance_type1" => "2",
            "money_shikikin_ck" => $article->money_shikikin_ck ?? "",
            "money_shikikin" => $article->money_shikikin * 10000 ?? "",
            "shikiunit" => $article->shikiunit ?? "money",
            "rosen2" => $article->rosen2 ?? "",
            "eki2" => $article->eki2 ?? "",
            "bus_stop2" => $article->bus_stop2 ?? "",
            "bus_time2" => $article->bus_time2 ?? "",
            "walk_distance2" => $article->walk_distance2 ?? "",
            "walk_distance_type2" => $article->walk_distance_type2 ?? "2",
            "traffic_other" => $article->traffic_other ?? "",
            "money_room" => $article->price,
            "money_tax" => $article->money_tax,
            "money_kyoueki" => $article->money_kyoueki ?? NULL,
            "money_kyoueki_tax" => $article->money_kyoueki_tax ?? "",
//            "money_shuuzen_ck"  =>  1,
//            "money_kyoueki_ck"  =>  $article->money_kyoueki_ck ?? "",
            "money_hoshoukin" => $article->money_hoshoukin * 10000 ?? "",
            "money_hoshoukin_ck" => $article->money_hoshoukin_ck ?? "",
            "hoshouunit" => $article->hoshouunit ?? "money",
            "commision" => "",
            "commisionunit" => "percent_money",
            "money_sonota1" => $article->money_sonota1 ?? "",
            "money_sonota_str1" => $article->money_sonota_str1 ?? "",
            "money_sonota2" => $article->money_sonota2 ?? "",
            "money_sonota_str2" => $article->money_sonota_str2 ?? "",
            "money_sonota3" => "",
            "money_sonota_str3" => "",
            "house_kaisuu" => $article->house_kaisuu ?? "",
            "house_kaisuu_chika" => $article->house_kaisuu_chika ?? "",
            "empty_number" => "",
            "all_number" => $article->all_number ?? "",
            "kenchiku_year" => $article->kenchiku_year,
            "kenchiku_month" => $article->kenchiku_month ?? '1',
            "flg_new" => $article->occupied ?? "0",
            "house_kouzou" => $article->house_kouzou ?? "",
            "house_kouzou_other" => "",
            "house_area" => $article->house_area ?? "567",
            "house_area_kind" => $article->house_area_kind ?? "",
            "kenchiku_num" => $article->architecture_no ?? "",
            "sekou_company_name" => $article->sekou_company_name ?? "",
//            "reform_wet_area_place1" => $article->reform_wet_area_place1 ?? null,
//            "reform_wet_area_place2" => $article->reform_wet_area_place2 ?? null,
//            "reform_wet_area_place3" => $article->reform_wet_area_place3 ?? null,
//            "reform_wet_area_place4" => $article->reform_wet_area_place4 ?? null,
//            "reform_wet_area_place5" => $article->reform_wet_area_place5 ?? null,
//            "reform_wet_area_place6" => $article->reform_wet_area_place6 ?? null,
            "reform_wet_area_other" => $article->reform_interior_other ?? null,
            "reform_wet_area_year" => $article->reform_wet_area_year ?? "",
            "reform_wet_area_month" => $article->reform_wet_area_month ?? "",
            "reform_interior_other" => $article->reform_interior_other ?? "",
            "reform_interior_year" =>  $article->reform_interior_year ?? "",
            "reform_interior_month" =>  $article->reform_interior_month ?? "",
//            "reform_interior_place1" => $article->reform_interior_place1 ?? "",
//            "reform_interior_place2" => $article->reform_interior_place2 ?? "",
//            "reform_interior_place3" => $article->reform_interior_place3 ?? "",
//            "reform_interior_place4" => $article->reform_interior_place4 ?? "",
//            "reform_interior_place5" => $article->reform_interior_place5 ?? "",
//            "reform_interior_place6" => $article->reform_interior_place6 ?? "",
//            "reform_exterior_place1" => $article->reform_exterior_place1 ?? "",
//            "reform_exterior_place2" => $article->reform_exterior_place2 ?? "",
            "reform_exterior_other" => $article->reform_exterior_other ?? "",
            "reform_exterior_year" => $article->reform_exterior_year ?? "",
            "reform_exterior_month" => $article->reform_exterior_month ?? "",
            "reform_note" => $article->reform_note ?? "",
            "madori_number_all" => $article->madori_number_all,
            "madori_kind_all" => $article->madori_kind_all,
            "flg_chijyo" => $article->flg_chijyo,
            "room_kaisuu" => $article->room_kaisuu ?? "",
            "window_angle" => $article->window_angle ?? "",
            "balcony_area" => $article->balcony_area ?? "",
            "balcony_umu" => $article->balcony_umu ?? "",
            "mdr_kind1" => "",
            "mdr_tatami1" => "",
            "mdr_floor1" => "",
            "mdr_numberof1" => "",
            "mdr_kind2" => "",
            "mdr_tatami2" => "",
            "mdr_floor2" => "",
            "mdr_numberof2" => "",
            "mdr_kind3" => "",
            "mdr_tatami3" => "",
            "mdr_floor3" => "",
            "mdr_numberof3" => "",
            "mdr_kind4" => "",
            "mdr_tatami4" => "",
            "mdr_floor4" => "",
            "mdr_numberof4" => "",
            "mdr_kind5" => "",
            "mdr_tatami5" => "",
            "mdr_floor5" => "",
            "mdr_numberof5" => "",
            "mdr_kind6" => "",
            "mdr_tatami6" => "",
            "mdr_floor6" => "",
            "mdr_numberof6" => "",
            "mdr_kind7" => "",
            "mdr_tatami7" => "",
            "mdr_floor7" => "",
            "mdr_numberof7" => "",
            "mdr_kind8" => "",
            "mdr_tatami8" => "",
            "mdr_floor8" => "",
            "mdr_numberof8" => "",
            "mdr_kind9" => "",
            "mdr_tatami9" => "",
            "mdr_floor9" => "",
            "mdr_numberof9" => "",
            "mdr_kind10" => "",
            "mdr_tatami10" => "",
            "mdr_floor10" => "",
            "mdr_numberof10" => "",
            "madori_etc" => "",
            "mdr_tatami1" => "",
            "mdr_floor1" => "",
            "mdr_numberof1" => "",
            "mdr_kind1" => "",
            "usable_status" => $article->usable_status,
            "usable_etc" => "",
            "usable_date_y" => $article->usable_date_y,
            "usable_date_m" => $article->usable_date_m,
            "usable_shun" => "",
            "genkyo_code" => $article->genkyo_code ?? "",
            "ft112" => "",
            "ft109" => $article->ft109 ?? "",
            "ft110" => $article->ft110 ?? "",
            "ft200" => $article->ft200 ?? "",
            "ft201" => $article->ft201 ?? "",
            "ft202" => $article->ft202 ?? "",
            "ft255" => $article->ft255 ?? "",
            "ft230" => $article->ft230 ?? "",
            "ft253" => $article->ft253 ?? "",
            "invest" => $article->invest ?? "",
            "ft224" => $article->ft224 ?? "",
            "ft225" => $article->ft225 ?? "",
            "ft227" => $article->ft227 ?? "",
            "ft223" => $article->ft223 ?? "",
            "ft244" => $article->ft244 ?? "",
            "ft426" => $article->ft426 ?? "",
            "ft289" => "",
            "ft290" => "",
            "ft218" => "",
            "ft213" => "",
            "ft203" => "",
            "ft204" => "",
            "ft207" => "",
            "ft208" => "",
            "ft234" => "",
            "parking_kubun" => $article->parking_kubun ?? "",
            "parking_keiyaku" => $article->parking_keiyaku ?? "0",
            "parking_money" => $article->parking_money ?? "",
            "parking_money_tax" => "2",
            "parking_number" => $article->parking_number ?? "",
            "parking_distance" => "",
            "parking_memo" => $article->parking_memo ?? "",
            "school_ele_name" => $article->school_ele_name ?? "",
            "school_ele_distance" => $article->school_ele_distance ?? "",
            "school_jun_name" => $article->school_jun_name ?? "",
            "school_jun_distance" => $article->school_jun_distance ?? "",
            "convenience_distance" => "",
            "super_distance" => "",
            "shopping_street_distance" => "",
            "drugstore_distance" => "",
            "hospital_distance" => "",
            "park_distance" => "",
            "bank_distance" => "",
            "est_other_name" => "",
            "est_other_distance" => "",
            "tokuchou" => $article->tokuchou ?? "",
            "etc" => $article->etc ?? "",
            "url_kind" => "0",
            "url" => "",
            "memo" => $article->homes_memo ?? "",
            "or_open_y" => $article->or_open_y ?? "",
            "or_open_m" => $article->or_open_m ?? "",
            "or_open_d" => $article->or_open_d ?? "",
            "or_end_y" => $article->or_end_y ?? "",
            "or_end_m" => $article->or_end_m ?? "",
            "or_end_d" => $article->or_end_d ?? "",
            "land_chisei" => $article->land_chisei ?? "",
            "or_time" => $article->or_time,
            "or_notes" => $article->or_notes ?? "",
            "taiyou" => $article->taiyou ?? "",
            "kyakuzuke_simple" => 0,
            "kyakuzuke" => $article->kyakuzuke ?? 0,
            "bunpai_a" => "",
            "kyakuzuke_msg" => "",
            "flg_own" => $article->company_manner == 9 ? 0 : 1,
            "baikai_keiyaku_date_y" => "",
            "baikai_keiyaku_date_m" => "",
            "baikai_keiyaku_date_d" => "",
            "owner_name" => "",
            "owner_tel1" => "",
            "owner_tel2" => "",
            "owner_tel3" => "",
            "owner_fax1" => "",
            "owner_fax2" => "",
            "owner_fax3" => "",
            "owner_etc" => "",
            "owner_post1" => "",
            "owner_post2" => "",
            "owner_addr1" => "",
            "owner_addr2" => "",
            "owner_addr3" => "",
            "owner_addr4" => "",
            "og_owner_addr11" => "",
            "og_owner_addr12" => "",
            "og_owner_addr2" => "",
            "og_owner_addr2_name" => "",
            "og_owner_post1" => "",
            "og_owner_post2" => "",
            "owner_addr3_name" => "",
            "moto_name" => $article->moto_name ?? "",
            "moto_tel1" => $article->moto_tel1 ?? "",
            "moto_tel2" => $article->moto_tel2 ?? "",
            "moto_tel3" => $article->moto_tel3 ?? "",
            "moto_fax1" => $article->moto_fax1 ?? "",
            "moto_fax2" => $article->moto_fax2 ?? "",
            "moto_fax3" => $article->moto_fax3 ?? "",
            "moto_tantou_name" => $article->moto_etc ?? "",
            "confirm_date_y" => $article->confirm_date_y ?? date('Y'),
            "confirm_date_m" => $article->confirm_date_m ?? date('m'),
            "confirm_date_d" => $article->confirm_date_d ?? date('d'),
            "moto_etc" => "",
            "moto_post1" => "",
            "moto_post2" => "",
            "moto_addr1" => "",
            "moto_addr2" => "",
            "moto_addr3" => "",
            "moto_addr4" => "",
            "og_moto_addr11" => "",
            "og_moto_addr12" => "",
            "og_moto_addr2" => "",
            "og_moto_addr2_name" => "",
            "og_moto_post1" => "",
            "og_moto_post2" => "",
            "moto_addr3_name" => "",
            "photo_dl_permission" => $article->photo_dl_permission ?? 0,
            "land_area" => $article->land_area,
            "land_area_kind" => $article->land_area_kind ?? "",
            "land_mochibun_b" => "",
            "land_mochibun_a" => "",
            "land_chimoku" => $article->land_chimoku ?? "",
            "land_toshi" => $article->land_toshi ?? "",
            "land_youto" => $article->land_youto ?? "",
            "land_kenpei" => $article->land_kenpei ?? "",
            "land_youseki" => $article->land_youseki ?? "",
            "land_youseki_etc" => "",
            "land_right" => $article->land_right,
            "keiyaku_year" => $article->keiyaku_year ?? "0",
            "keiyaku_month" => $article->keiyaku_month ?? "",
            "keiyaku_period_kind" => $article->keiyaku_period_kind,
            "money_shakuchi" => $article->money_shakuchi ?? "",
            "land_kokudohou" => $article->kokudoho ?? "",
            "land_seigen" => $article->land_seigen ?? "",
            "land_shidou_flg" => $article->land_shidou_flg ?? 0,
            "land_shidou" => $article->land_shidou ?? "",
            "land_shidou_b" => $article->road_numerator ?? "",
            "land_shidou_a" => $article->road_denominator ?? "",
            "land_setback_flg" => $article->land_setback_flg ?? "",
            "land_setback" => $article->land_setback ?? "",
            "land_road_cond" => "",
            "std_angle1" => $article->std_angle1 > 0 ? $article->std_angle1  : "",
            "std_width1" => $article->std_width1 ?? "",
            "std_kind1" => $article->std_kind1 > 0 ? $article->std_kind1  : "",
            "std_maguchi1" => $article->std_maguchi1 ?? "",
            "std_angle2" => $article->std_angle2 > 0 ? $article->std_angle2  : "",
            "std_width2" => $article->std_width2 ?? "",
            "std_kind2" => $article->std_kind2 > 0 ? $article->std_kind2  : "",
            "std_maguchi2" => $article->std_maguchi2 ?? "",
            "std_angle3" => $article->std_angle3 > 0 ? $article->std_angle3  : "",
            "std_width3" => $article->std_width3 ?? "",
            "std_kind3" => $article->std_kind3 > 0 ? $article->std_kind3  : "",
            "std_maguchi3" => $article->std_maguchi3 ?? "",
            "std_angle4" => "",
            "std_width4" => "",
            "std_kind4" => "",
            "std_maguchi4" => "",
            "pht_photo[]" => "(binary)",
            "pht_photo[]" => "(binary)",
            "photo_type1" => "2",
            "photo_comment1" => "",
            "pht_photo[]" => "(binary)",
            "photo_type2" => "1",
            "photo_comment2" => "",
            "pht_photo[]" => "(binary)",
            "photo_type3" => "11",
            "photo_comment3" => "",
            "pht_photo[]" => "(binary)",
            "photo_type4" => "5",
            "photo_comment4" => "",
            "pht_photo[]" => "(binary)",
            "photo_type5" => "12",
            "photo_comment5" => "",
            "pht_photo[]" => "(binary)",
            "photo_type6" => "15",
            "photo_comment6" => "",
            "pht_photo[]" => "(binary)",
            "photo_type7" => "16",
            "photo_comment7" => "",
            "pht_photo[]" => "(binary)",
            "photo_type8" => "17",
            "photo_comment8" => "",
            "pht_photo[]" => "(binary)",
            "photo_type9" => "13",
            "photo_comment9" => "",
            "pht_photo[]" => "(binary)",
            "photo_type10" => "14",
            "photo_comment10" => "",
            "pht_photo[]" => "(binary)",
            "photo_type11" => "9",
            "photo_comment11" => "",
            "pht_photo[]" => "(binary)",
            "photo_type12" => "9",
            "photo_comment12" => "",
            "pht_photo[]" => "(binary)",
            "photo_type13" => "9",
            "photo_comment13" => "",
            "pht_photo[]" => "(binary)",
            "photo_type14" => "9",
            "photo_comment14" => "",
            "pht_photo[]" => "(binary)",
            "photo_type15" => "9",
            "photo_comment15" => "",
            "pht_photo[]" => "(binary)",
            "photo_type16" => "9",
            "photo_comment16" => "",
            "pht_photo[]" => "(binary)",
            "photo_type17" => "9",
            "photo_comment17" => "",
            "pht_photo[]" => "(binary)",
            "photo_type18" => "9",
            "photo_comment18" => "",
            "pht_photo[]" => "(binary)",
            "photo_type19" => "9",
            "photo_comment19" => "",
            "pht_photo[]" => "(binary)",
            "photo_type20" => "9",
            "photo_comment20" => "",
            "pht_photo[]" => "(binary)",
            "photo_type21" => "9",
            "photo_comment21" => "",
            "pht_photo[]" => "(binary)",
            "photo_type22" => "9",
            "photo_comment22" => "",
            "pht_photo[]" => "(binary)",
            "photo_type23" => "9",
            "photo_comment23" => "",
            "pht_photo[]" => "(binary)",
            "photo_type24" => "9",
            "photo_comment24" => "",
            "pht_photo[]" => "(binary)",
            "photo_type25" => "9",
            "photo_comment25" => "",
            "pht_photo[]" => "(binary)",
            "photo_type26" => "9",
            "photo_comment26" => "",
            "pht_photo[]" => "(binary)",
            "photo_type27" => "9",
            "photo_comment27" => "",
            "pht_photo[]" => "(binary)",
            "photo_type28" => "9",
            "photo_comment28" => "",
            "pht_photo[]" => "(binary)",
            "photo_type29" => "9",
            "photo_comment29" => "",
            "pht_photo[]" => "(binary)",
            "photo_type30" => "9",
            "photo_comment30" => "",
            "MAX_FILE_SIZE" => "5242880",
            "panorama_uid" => "",
            "rosen_etc1" => (string)$article->rosen_etc1 ?? "2",
            "rosen1_name" => $article->rosen1_name ?? "",
            "eki1_name" => (string)$article->eki1_name ?? "",
            "rosen_etc2" => $article->rosen_etc2 ?? "3",
            "rosen2_name" => $article->sub_traffic1_line ?? "",
            "eki2_name" => $article->sub_traffic1_station ?? ""
        ];

        $fields = [
            'reform_wet_area_place1',
            'reform_wet_area_place2',
            'reform_wet_area_place3',
            'reform_wet_area_place4',
            'reform_wet_area_place5',
            'reform_wet_area_place6',
            'reform_interior_place1',
            'reform_interior_place2',
            'reform_interior_place3',
            'reform_interior_place4',
            'reform_interior_place5',
            'reform_interior_place6',
            'reform_exterior_place1',
            'reform_exterior_place2',
        ];
        foreach ($fields as $field){
            if (isset($article->{$field})){
                $response[$field] = $article->{$field};
            }
        }
        if(isset($article->money_kyoueki)){
            $response['money_kyoueki_ck'] = $article->money_kyoueki_ck ?? "";
        }
        if(isset($article->money_shuuzen)){
            $response['money_shuuzen_ck'] = 1;
        }

        return $response;
    }

    function moldingDataLand($article)
    {
        if ($article->property == 1) {
            $article->bt = "1101";
        } else if ($article->property == 2) {
            $article->bt = "1102";
        } else if ($article->property == 3) {
            $article->bt = "1103";
        } else {
            $article->bt = "1101";
        }

        $article->money_shakuchi = $article->land_rent_val;

        if ($article->event_schedule == 4) {
            if (!empty($article->from_event)) {
                $from_event = explode("-", $article->from_event);
                if (count($from_event) == 3) {
                    $article->or_open_y = $from_event[0];
                    $article->or_open_m = $from_event[1];
                    $article->or_open_d = $from_event[2];
                }
            }
            if (!empty($article->to_event)) {
                $to_event = explode("-", $article->to_event);
                if (count($to_event) == 3) {
                    $article->or_end_y = $to_event[0];
                    $article->or_end_y = $to_event[1];
                    $article->or_end_y = $to_event[2];
                }
            }
        } else if ($article->event_schedule == 3) {
            if (!empty($article->event_day)) {
                $from_event = explode("-", $article->event_day);
                if (count($from_event) == 3) {
                    $article->or_open_y = $from_event[0];
                    $article->or_open_m = $from_event[1];
                    $article->or_open_d = $from_event[2];
                }
            }
        }

        if (!empty($article->another_cost1)) {
            $article->money_sonota1_ck = 1;
            $article->money_sonota1 = $article->another_cost1;
            switch ($article->another_cost_unit1) {
                case 1:
                    $article->money_sonota_str1 = "月";
                    break;
                case 2:
                    $article->money_sonota_str1 = "年";
                    break;
                case 3:
                    $article->money_sonota_str1 = "一括";
                    break;
            }
        }

        if (!empty($article->another_cost2)) {
            $article->money_sonota2_ck = 1;
            $article->money_sonota2 = $article->another_cost2;
            switch ($article->another_cost_unit2) {
                case 1:
                    $article->money_sonota_str2 = "月";
                    break;
                case 2:
                    $article->money_sonota_str2 = "年";
                    break;
                case 3:
                    $article->money_sonota_str2 = "一括";
                    break;
            }
        }

        if ($article->age_year < 1926) {
            $article->kenchiku_year = 1926;
        } else {
            $article->kenchiku_year = $article->age_year;
        }
        $article->kenchiku_month = $article->age_month;
        $article->b_name = mb_substr($article->name_portal, 0, 42);

        // 物件担当者
        $user_info = UserInfo::getDataById($article->hp_charge);
        $name_info = '';
        $name_info = $user_info->last_name ?? '';
        if ($name_info != '') {
            $name_info .= ' ';
        }
        $name_info .= $user_info->first_name ?? '';
        $article->tantou_name = $name_info;

        if ($article->ground > 0 && $article->ground < 6) {
            $article->land_chimoku = $article->ground;
        } else {
            $article->land_chimoku = 9;
        }

        // 状態
        $isClose = [4, 5, 6];
        if (in_array($article->status, $isClose)) {
            // 販売中以外
            $article->status_h = "3";
        } else {
            // 販売中
            $article->status_h = "1";
        }

        // LIFULL HOME'S掲載
        if ($article->homes == 1) {
            $article->flg_open = "0";
        } elseif ($article->homes == 2) {
            $article->flg_open = "1";
        }

        // 2.所在地
        // 郵便番号
        $zip_info = $article->zip;
        $zip_list = explode('-', $zip_info);
        $article->post1 = $zip_list[0] ?? '';
        $article->post2 = $zip_list[1] ?? '';

        $ar_addr1 = [
            14  =>  "lubSWM0xC_rXi-RBdHFC_A",
            11  =>  "tl2t74MQfsbXi-RBdHFC_A",
            12  =>  "drv6Kix16svXi-RBdHFC_A",
            28  =>  "0hNR5oDOggnXi-RBdHFC_A",
            27 =>   "TOoNMbIEn2LXi-RBdHFC_A"
        ];
        $ar_temporary_addr1 = [
            14  =>  14,
            11  =>  26,
            12  =>  25,
            28  =>  28,
            27 => 27
        ];
        $article->addr1 = $ar_addr1[$article->address1];
        $article->temporary_addr1 = $ar_temporary_addr1[$article->address1];

        // 番地など
        $article->addr3_addr4_name = $article->address;
        if (is_null($article->address)) {
            // addr3_addr4_nameは必須項目
            $article->flg_addr_hidden = "0";
        } else {
            $article->flg_addr_hidden = "1";
        }
        $article->display_addr_name = $article->address;

        //緯度経度
        $article->nl = $article->lat;
        $article->el = $article->lng;

        // 1.価格
        if ($article->tax == 1) {
            // 税抜
            $article->money_tax = "3";
        } elseif ($article->tax == 2) {
            // 税込
            $article->money_tax = "2";
        }

        // 4.土地建物情報
        // 土地権利
        switch ($article->land_right) {
            case 0:
                $article->land_right = "";
                break;
            case 1:
                $article->land_right = 1;
                break;
            case 2:
                switch ($article->leasehold_kind) {
                    case 1:
                        $article->land_right = 3;
                        break;
                    case 2:
                        $article->land_right = 6;
                        break;
                    case 3:
                        $article->land_right = 7;
                        break;
                    case 4:
                        $article->land_right = 7;
                        break;
                    case 8:
                        $article->land_right = 5;
                        break;

                    case 5:
                        $article->land_right = 2;
                        break;
                    case 6:
                        $article->land_right = 4;
                        break;
                    case 7:
                        $article->land_right = 5;
                        break;
                }
                break;
            case 3:
                switch ($article->leasehold_kind) {
                    case 1:
                        $article->land_right = 3;
                        break;
                    case 2:
                        $article->land_right = 6;
                        break;
                    case 3:
                        $article->land_right = 7;
                        break;
                    case 4:
                        $article->land_right = 5;
                        break;
                    case 8:
                        $article->land_right = 5;
                        break;

                    case 5:
                        $article->land_right = 2;
                        break;
                    case 6:
                        $article->land_right = 4;
                        break;
                    case 7:
                        $article->land_right = 5;
                        break;
                }
                break;
        }

        // 構造
        if ($article->construction == 8) {
            $article->house_kouzou = 10;
        } else if ($article->construction == 9) {
            $article->house_kouzou = 11;
        } else if ($article->construction == 10 || $article->construction == 11) {
            $article->house_kouzou = "";
        } else {
            $article->house_kouzou = $article->construction;
        }
        // 建物階建て
        $article->house_kaisuu = $article->floor;
        $article->house_kaisuu_chika = $article->underground;
        if (!empty($article->house_kaisuu)) {
            $article->flg_chijyo = 1;
            $article->room_kaisuu = $article->house_kaisuu;
        } else {
            $article->flg_chijyo = -1;
            $article->room_kaisuu = $article->house_kaisuu_chika;
        }

        $article->house_area = $article->total_area_val;
        $article->madori_number_all = $article->floor_plan;
        switch ($article->floor_plan_type) {
            case 1:
                $article->madori_kind_all = 30;
                break;
            case 2:
                $article->madori_kind_all = 50;
                break;
            case 3:
                $article->madori_kind_all = 10;
                break;
            case 4:
                $article->madori_kind_all = 20;
                break;
            case 5:
                $article->madori_kind_all = 25;
                break;
            case 6:
                $article->madori_kind_all = 35;
                break;
            case 7:
                $article->madori_kind_all = 40;
                break;
            case 8:
                $article->madori_kind_all = 45;
                break;
            case 9:
                $article->madori_kind_all = 55;
                break;
        }

        switch ($article->current_status) {
            case 1:
                $article->genkyo_code = 1;
                break;
            case 2:
            case 3:
                $article->genkyo_code = 2;
                break;
            case 0:
                break;
        }

        switch ($article->land_condition) {
            case 0:
                $article->ft110 = 2;
                break;
            case 1:
                $article->ft110 = 1;
                break;
        }

        switch ($article->water_supply) {
            case 1:
                $article->ft200 = 1;
                break;
            case 2:
                $article->ft200 = 99;
                break;
            case 3:
                $article->ft200 = 2;
                break;
        }

        switch ($article->gas) {
            case 1:
                $article->ft201 = 1;
                break;
            case 2:
            case 3:
                $article->ft201 = 2;
                break;
            case 4:
                $article->ft244 = 1;
                $article->ft201 = 99;
                break;
            default:
                $article->ft201 = "";
                break;
        }

        switch ($article->sewerage) {
            case 1:
                $article->ft202 = 1;
                break;
            case 2:
            case 3:
                $article->ft202 = 2;
                break;
            case 0:
                $article->ft202 = "";
                break;
        }

        $article->parking_number = $article->parking_num;
        $article->parking_memo = '';
        if ($article->parking_num != '') {
            $article->parking_memo = '駐車可能台数 ' . $article->parking_num . '台';
        }

        $article->school_ele_name = optional($article->primarySchool)->name;
        $article->school_ele_distance = $article->primary_school_distance;
        $article->school_jun_name = optional($article->secondarySchool)->name;
        $article->school_jun_distance = $article->secondary_school_distance;
        $article->tokuchou = $article->homes_copy;
        $article->etc = $article->homes_comment;
        $article->or_notes = $article->event_comment;

        $vendor = $article->vendors()->first();
        if (isset($vendor)) {
            $firstRelation = \App\Models\RelationVendorArticle::firstRelationVendorArticle($article->building_id, $vendor->id);
            $article->moto_name = $vendor->name;
            $vendor_tel = $vendor->vendor_tel1;
            $vendor_fax = $vendor->vendor_fax;
            $vendor_tel = explode("-", $vendor_tel);
            if (count($vendor_tel) == 3) {
                $article->moto_tel1 = $vendor_tel[0];
                $article->moto_tel2 = $vendor_tel[1];
                $article->moto_tel3 = $vendor_tel[2];
            }
            $vendor_fax = explode("-", $vendor_fax);
            if (count($vendor_fax) == 3) {
                $article->moto_fax1 = $vendor_fax[0];
                $article->moto_fax2 = $vendor_fax[1];
                $article->moto_fax3 = $vendor_fax[2];
            }
            $ad_conf_day = $firstRelation->ad_conf_day;
            $ad_conf_day = explode("-", $ad_conf_day);
            if (count($ad_conf_day) == 3) {
                $article->confirm_date_y = $ad_conf_day[0];
                // $article->confirm_date_m = $ad_conf_day[1];
                // $article->confirm_date_d = $ad_conf_day[2];
                $article->confirm_date_m = date('m');
                $article->confirm_date_d = date('d');
            }
            $article->moto_etc = $firstRelation->charge;
        }
        $article->land_area_kind = $article->land_area != 0 ? $article->land_area : "";
        $article->land_area = $article->land_area_val;
        $article->land_toshi = $article->city_plan == 5 ? "" : $article->city_plan;
        $article->land_kenpei = $article->building_rate;
        $article->land_youseki = $article->volume_rate;
        if (!empty($article->leasehold_period_year)) {
            $article->keiyaku_year = $article->leasehold_period_year;
        }
        if (!empty($article->leasehold_period_month)) {
            $article->keiyaku_month = $article->leasehold_period_month;
        }
        if ($article->land_right == 1) {
            $article->keiyaku_year = '';
            $article->keiyaku_month = '';
        }
        switch ($article->road_burden) {
            case 0:
                $article->land_shidou_flg = 1;
                break;
            case 1:
                $article->land_shidou_flg = 2;
                $article->land_shidou = $article->road_burden_area;
                break;
            case 2:
                $article->land_shidou_flg = 2;
                $article->land_shidou = $article->road_burden_area;
                break;
            default:
                $article->land_shidou_flg = 0;
                break;
        }


        switch ($article->set) {
            case 1:
                $article->land_setback_flg = 1;
                break;
            case 2:
            case 3:
                $article->land_setback_flg = 2;
                $article->land_setback = $article->set_area;
                break;
            default:
                $article->land_setback_flg = "";
                break;
        }

        $article->std_angle1 = $article->land_direction1;
        $article->std_width1 = $article->road_width1;
        $article->std_kind1 = $article->land_kind1;
        $article->std_maguchi1 = $article->frontage1;

        $article->std_angle2 = $article->land_direction2;
        $article->std_width2 = $article->road_width2;
        $article->std_kind2 = $article->land_kind2;
        $article->std_maguchi2 = $article->frontage2;

        $article->std_angle3 = $article->land_direction3;
        $article->std_width3 = $article->road_width3;
        $article->std_kind3 = $article->land_kind3;
        $article->std_maguchi3 = $article->frontage3;
        $article->empty_contents = $article->name_gouchi;

        if ($article->land_delivery == 1) {
            $article->usable_status = 1;
        }
        if ($article->land_delivery == 2 || $article->land_delivery == 0 || $article->land_delivery == 4) {
            $article->usable_status = 2;
        }
        if ($article->land_delivery == 3) {
            $article->usable_status = 3;
        }

        if ($article->usable_status == 3) {
            $article->usable_date_y = $article->delivery_year;
            $article->usable_date_m = $article->delivery_month;
        }

        $article->land_youto = $article->use_area;
        $article->all_number = $article->section;
        $article->keiyaku_period_kind = 2;

        $lawrestrictions = $article->lawrestrictions;
        $land_seigen = "";
        foreach ($lawrestrictions as $key => $lawrestriction) {
            $old_land = $land_seigen;
            if ($key == 0) {
                $land_seigen .= "{$lawrestriction->name}";
            } else {
                $land_seigen .= ", {$lawrestriction->name}";
            }

            if (strlen($land_seigen) > 200) {
                $land_seigen = $old_land;
                break;
            }
        }
        $other_restrictions = $article->otherRestrictions;
        $other_names = [
            "", "一部都市計画道路", "一部協定通路", "日影制限有", "隅切り有",
            "接道と段差有", "敷地内段差有", "壁面後退有", "建築協定有",
            "崖上につき建築制限有", "崖下につき建築制限有", "不整形地"
        ];

        foreach ($other_restrictions as $key => $other_restriction) {
            $old_land = $land_seigen;

            if (isset($other_names[$other_restriction['item_id']])) {
                $land_seigen .= ", {$other_names[$other_restriction['item_id']]}";
            }

            if (strlen($land_seigen) > 200) {
                $land_seigen = $old_land;
                break;
            }
        }
        if ($article->other_comment != '') {
            $land_seigen .= ', ' . $article->other_comment;
        }

        $article->land_seigen = $land_seigen;
        $or_notes = '';
        if ($article->event_schedule == 1) {
            $or_notes .= '毎週土日祝開催 ';
        } elseif ($article->event_schedule == 2) {
            $or_notes .= '毎週土日開催 ';
        } elseif ($article->event_schedule == 5) {
            $or_notes .= '公開中 ';
        }
        if ($article->reservation == 1) {
            $or_notes .= '予約制';
        }
        $or_notes .= $article->event_comment;
        $article->or_notes = $or_notes;
        $article->kyakuzuke = 0;
        $article->photo_dl_permission = 2;
        if ($article->land_condition1 == 1) {
            $article->land_chisei = 5;
        }
        $time_limit = date('d/m/Y', strtotime('+2 weeks'));
        $day = explode('/', $time_limit);
        $article->timelimit_date_y = $day[2];
        $article->timelimit_date_m = $day[1];
        $article->timelimit_date_d = $day[0];
        //dd($article->toArray());

        return $article;
    }

    function moldingDataHouse($article)
    {
        if ($article->property == 4) {
            if ($article->property_sub == 1) {
                $article->bt = "1201";
                $article->occupied = "1";
            } else if ($article->property_sub == 2) {
                $article->bt = "1202";
            }
        } else if ($article->property == 5) {
            if ($article->property_sub == 1) {
                $article->bt = "1203";
            } else if ($article->property_sub == 2) {
                $article->bt = "1204";
            }
        } else {
            $article->bt = "1201";
        }

        if ($article->event_schedule == 4) {
            if (!empty($article->from_event)) {
                $from_event = explode("-", $article->from_event);
                if (count($from_event) == 3) {
                    $article->or_open_y = $from_event[0];
                    $article->or_open_m = $from_event[1];
                    $article->or_open_d = $from_event[2];
                }
            }
            if (!empty($article->to_event)) {
                $to_event = explode("-", $article->to_event);
                if (count($to_event) == 3) {
                    $article->or_end_y = $to_event[0];
                    $article->or_end_y = $to_event[1];
                    $article->or_end_y = $to_event[2];
                }
            }
        } else if ($article->event_schedule == 3) {
            if (!empty($article->event_day)) {
                $article->event_day = str_replace("/", "-", $article->event_day);
                $check_event_day = explode(",", $article->event_day);
                if (count($check_event_day) > 1) {
                    $article->event_day = $check_event_day[0];
                }
                $from_event = explode("-", $article->event_day);
                if (count($from_event) == 3) {
                    $article->or_open_y = $from_event[0];
                    $article->or_open_m = $from_event[1];
                    $article->or_open_d = $from_event[2];
                }
            }
        }

        $article->all_number = $article->total_unit;

        if (!empty($article->another_cost1)) {
            $article->money_sonota1_ck = 1;
            $article->money_sonota1 = $article->another_cost1;
            switch ($article->another_cost_unit1) {
                case 1:
                    $article->money_sonota_str1 = "月";
                    break;
                case 2:
                    $article->money_sonota_str1 = "年";
                    break;
                case 3:
                    $article->money_sonota_str1 = "一括";
                    break;
            }
        }

        if (!empty($article->another_cost2)) {
            $article->money_sonota2_ck = 1;
            $article->money_sonota2 = $article->another_cost2;
            switch ($article->another_cost_unit2) {
                case 1:
                    $article->money_sonota_str2 = "月";
                    break;
                case 2:
                    $article->money_sonota_str2 = "年";
                    break;
                case 3:
                    $article->money_sonota_str2 = "一括";
                    break;
            }
        }

        if ($article->age_year < 1926) {
            $article->kenchiku_year = 1926;
        } else {
            $article->kenchiku_year = $article->age_year;
        }

        $article->kenchiku_month = $article->age_month;
        $article->b_name = mb_substr($article->name_portal, 0, 42);

        // 物件担当者
        $user_info = UserInfo::getDataById($article->hp_charge);
        $name_info = '';
        $name_info = $user_info->last_name ?? '';
        if ($name_info != '') {
            $name_info .= ' ';
        }
        $name_info .= $user_info->first_name ?? '';
        $article->tantou_name = $name_info;

        // 状態
        $isClose = [4, 5, 6];
        if (in_array($article->status, $isClose)) {
            // 販売中以外
            $article->status_h = "3";
        } else {
            // 販売中
            $article->status_h = "1";
        }

        // LIFULL HOME'S掲載
        if ($article->homes == 1) {
            $article->flg_open = "0";
        } elseif ($article->homes == 2) {
            $article->flg_open = "1";
        }

        // 2.所在地
        // 郵便番号
        $zip_info = $article->zip;
        $zip_list = explode('-', $zip_info);
        $article->post1 = $zip_list[0] ?? '';
        $article->post2 = $zip_list[1] ?? '';

        $ar_addr1 = [
            14  =>  "lubSWM0xC_rXi-RBdHFC_A",
            11  =>  "tl2t74MQfsbXi-RBdHFC_A",
            12  =>  "drv6Kix16svXi-RBdHFC_A",
            28  =>  "0hNR5oDOggnXi-RBdHFC_A",
            27 =>   "TOoNMbIEn2LXi-RBdHFC_A"
        ];
        $ar_temporary_addr1 = [
            14  =>  14,
            11  =>  26,
            12  =>  25,
            28  =>  28,
            27 => 27
        ];
        $article->addr1 = $ar_addr1[$article->address1];
        $article->temporary_addr1 = $ar_temporary_addr1[$article->address1];


        // 番地など
        $article->addr3_addr4_name = $article->address;
        if (is_null($article->address)) {
            // addr3_addr4_nameは必須項目
            $article->flg_addr_hidden = "0";
        } else {
            $article->flg_addr_hidden = "1";
        }
        $article->display_addr_name = $article->address;

        //緯度経度
        $article->nl = $article->lat;
        $article->el = $article->lng;

        // 3.交通

        // 金銭・建物タブ
        // 1.価格
        if ($article->tax == 1) {
            // 税抜
            $article->money_tax = "3";
        } elseif ($article->tax == 2) {
            // 税込
            $article->money_tax = "2";
        }

        // 4.土地建物情報
        // 土地権利
        switch ($article->land_right) {
            case 0:
                $article->land_right = "";
                break;
            case 1:
                $article->land_right = 1;
                break;
            case 2:
                switch ($article->leasehold_kind) {
                    case 1:
                        $article->land_right = 3;
                        break;
                    case 2:
                        $article->land_right = 6;
                        break;
                    case 3:
                        $article->land_right = 7;
                        break;
                    case 4:
                        $article->land_right = 7;
                        break;
                    case 8:
                        $article->land_right = 5;
                        break;

                    case 5:
                        $article->land_right = 2;
                        break;
                    case 6:
                        $article->land_right = 4;
                        break;
                    case 7:
                        $article->land_right = 5;
                        break;
                }
                break;
            case 3:
                switch ($article->leasehold_kind) {
                    case 1:
                        $article->land_right = 3;
                        break;
                    case 2:
                        $article->land_right = 6;
                        break;
                    case 3:
                        $article->land_right = 7;
                        break;
                    case 4:
                        $article->land_right = 7;
                        break;
                    case 8:
                        $article->land_right = 5;
                        break;

                    case 5:
                        $article->land_right = 2;
                        break;
                    case 6:
                        $article->land_right = 4;
                        break;
                    case 7:
                        $article->land_right = 5;
                        break;
                }
                break;
        }

        // 構造
        if ($article->construction == 8) {
            $article->house_kouzou = 10;
        } else if ($article->construction == 9) {
            $article->house_kouzou = 11;
        } else if ($article->construction == 10) {
            $article->house_kouzou = 4;
        } else if ($article->construction == 11 || $article->construction_sub == 11) {
            $article->house_kouzou = 9;
        } else {
            $article->house_kouzou = $article->construction;
        }
        // 建物階建て
        $article->house_kaisuu = $article->floor;
        $article->house_kaisuu_chika = $article->underground;
        if (!empty($article->house_kaisuu)) {
            $article->flg_chijyo = 1;
            $article->room_kaisuu = $article->house_kaisuu;
        } else {
            $article->flg_chijyo = -1;
            $article->room_kaisuu = $article->house_kaisuu_chika;
        }
        //$article->flg_chijyo = "";
        //$article->room_kaisuu = "";
        $article->house_area = $article->total_area_val;
        $article->madori_number_all = $article->floor_plan;
        switch ($article->floor_plan_type) {
            case 1:
                $article->madori_kind_all = 30;
                break;
            case 2:
                $article->madori_kind_all = 50;
                break;
            case 3:
                $article->madori_kind_all = 10;
                break;
            case 4:
                $article->madori_kind_all = 20;
                break;
            case 5:
                $article->madori_kind_all = 25;
                break;
            case 6:
                $article->madori_kind_all = 35;
                break;
            case 7:
                $article->madori_kind_all = 40;
                break;
            case 8:
                $article->madori_kind_all = 45;
                break;
            case 9:
                $article->madori_kind_all = 55;
                break;
        }

        switch ($article->current_status) {
            case 4:
                $article->genkyo_code = 1;
                break;
            case 5:
                $article->genkyo_code = 2;
                break;
            case 8:
                break;
            case 6:
                $article->genkyo_code = 3;
                break;
            case 7:
            case 9:
                $article->genkyo_code = 4;
                break;
        }

        switch ($article->water_supply) {
            case 1:
                $article->ft200 = 1;
                break;
            case 2:
                $article->ft200 = 99;
                break;
            case 3:
                $article->ft200 = 2;
                break;
        }

        switch ($article->gas) {
            case 1:
                $article->ft201 = 1;
                break;
            case 2:
            case 3:
                $article->ft201 = 2;
                break;
            case 4:
                $article->ft244 = 1;
                $article->ft201 = 99;
                break;
            default:
                $article->ft201 = "";
                break;
        }

        switch ($article->sewerage) {
            case 1:
                $article->ft202 = 1;
                break;
            case 2:
                $article->ft202 = 2;
                break;
            case 3:
                $article->ft202 = 2;
                break;
            case 0:
                $article->ft202 = "";
                break;
        }

        $article->parking_number = $article->parking_num;
        $article->parking_memo = '';
        if ($article->parking_num != '') {
            $article->parking_memo = '駐車可能台数 ' . $article->parking_num . '台';
        }
        $article->parking_kubun = $article->parking == 1 ? "4" : "";

        $article->school_ele_name = optional($article->primarySchool)->name;
        $article->school_ele_distance = $article->primary_school_distance;
        $article->school_jun_name = optional($article->secondarySchool)->name;
        $article->school_jun_distance = $article->secondary_school_distance;
        $article->tokuchou = $article->homes_copy;
        $article->etc = $article->homes_comment;
        $article->or_notes = "駐車可能台数 {$article->parking_num}台";

        $vendor = $article->vendors()->first();
        if (isset($vendor)) {
            $firstRelation = \App\Models\RelationVendorArticle::firstRelationVendorArticle($article->building_id, $vendor->id);
            $article->moto_name = $vendor->name;
            $vendor_tel = $vendor->vendor_tel1;
            $vendor_fax = $vendor->vendor_fax;
            $vendor_tel = explode("-", $vendor_tel);
            if (count($vendor_tel) == 3) {
                $article->moto_tel1 = $vendor_tel[0];
                $article->moto_tel2 = $vendor_tel[1];
                $article->moto_tel3 = $vendor_tel[2];
            }
            $vendor_fax = explode("-", $vendor_fax);
            if (count($vendor_fax) == 3) {
                $article->moto_fax1 = $vendor_fax[0];
                $article->moto_fax2 = $vendor_fax[1];
                $article->moto_fax3 = $vendor_fax[2];
            }
            $ad_conf_day = $firstRelation->ad_conf_day;
            $ad_conf_day = explode("-", $ad_conf_day);
            if (count($ad_conf_day) == 3) {
                $article->confirm_date_y = $ad_conf_day[0];
                // $article->confirm_date_m = $ad_conf_day[1];
                // $article->confirm_date_d = $ad_conf_day[2];
                $article->confirm_date_m = date('m');
                $article->confirm_date_d = date('d');
            }
            $article->moto_etc = $firstRelation->charge;
        }
        $article->land_area_kind = $article->land_area != 0 ? $article->land_area : "";
        $article->land_area = $article->land_area_val;
        $article->land_toshi = $article->city_plan == 5 ? "" : $article->city_plan;
        $article->land_kenpei = $article->building_rate;
        $article->land_youseki = $article->volume_rate;
        $article->money_shakuchi = $article->land_rent_val;
        if (!empty($article->leasehold_period_year)) {
            $article->keiyaku_year = $article->leasehold_period_year;
        }
        if (!empty($article->leasehold_period_month)) {
            $article->keiyaku_month = $article->leasehold_period_month;
        }
        if ($article->land_right == 1) {
            $article->keiyaku_year = '';
            $article->keiyaku_month = '';
        }

        switch ($article->set) {
            case 1:
                $article->land_setback_flg = 1;
                break;
            case 2:
            case 3:
                $article->land_setback_flg = 2;
                $article->land_setback = $article->set_area;
                break;
            default:
                $article->land_setback_flg = "";
                break;
        }

        switch ($article->road_burden) {
            case 0:
                $article->land_shidou_flg = 1;
                break;
            case 1:
                $article->land_shidou_flg = 2;
                $article->land_shidou = $article->road_burden_area;
                break;
            case 2:
                $article->land_shidou_flg = 2;
                $article->land_shidou = $article->road_burden_area;
                break;
            default:
                $article->land_shidou_flg = "";
                break;
        }

        $article->std_angle1 = $article->land_direction1;
        $article->std_width1 = $article->road_width1;
        $article->std_kind1 = $article->land_kind1;
        $article->std_maguchi1 = $article->frontage1;

        $article->std_angle2 = $article->land_direction2;
        $article->std_width2 = $article->road_width2;
        $article->std_kind2 = $article->land_kind2;
        $article->std_maguchi2 = $article->frontage2;

        $article->std_angle3 = $article->land_direction3;
        $article->std_width3 = $article->road_width3;
        $article->std_kind3 = $article->land_kind3;
        $article->std_maguchi3 = $article->frontage3;
        $article->empty_contents = $article->name_gouchi;

        if ($article->move_in < 4 && $article->move_in != 0) {
            $article->usable_status = $article->move_in;
        } else {
            $article->usable_status = 2;
        }
        if ($article->usable_status == 3) {
            $article->usable_date_y = $article->move_in_year;
            $article->usable_date_m = $article->move_in_month;
        }
        $article->land_chisei = $article->land_condition1 == 1 ? 5 : "";

        $article->land_youto = $article->use_area;
        $article->keiyaku_period_kind = 2;

        $lawrestrictions = $article->lawrestrictions;
        $land_seigen = "";
        foreach ($lawrestrictions as $key => $lawrestriction) {
            $old_land = $land_seigen;
            if ($key == 0) {
                $land_seigen .= "{$lawrestriction->name}";
            } else {
                $land_seigen .= ", {$lawrestriction->name}";
            }

            if (strlen($land_seigen) > 200) {
                $land_seigen = $old_land;
                break;
            }
        }

        $other_restrictions = $article->otherRestrictions;
        $other_names = [
            "", "一部都市計画道路", "一部協定通路", "日影制限有", "隅切り有",
            "接道と段差有", "敷地内段差有", "壁面後退有", "建築協定有",
            "崖上につき建築制限有", "崖下につき建築制限有", "不整形地"
        ];

        foreach ($other_restrictions as $key => $other_restriction) {
            $old_land = $land_seigen;

            if (isset($other_names[$other_restriction['item_id']])) {
                $land_seigen .= ", {$other_names[$other_restriction['item_id']]}";
            }

            if (strlen($land_seigen) > 200) {
                $land_seigen = $old_land;
                break;
            }
        }
        if ($article->other_comment != '') {
            $land_seigen .= ', ' . $article->other_comment;
        }

        $article->land_seigen = $land_seigen;
        $or_notes = '';
        if ($article->event_schedule == 1) {
            $or_notes .= '毎週土日祝開催 ';
        } elseif ($article->event_schedule == 2) {
            $or_notes .= '毎週土日開催 ';
        } elseif ($article->event_schedule == 5) {
            $or_notes .= '公開中 ';
        }
        if ($article->reservation == 1) {
            $or_notes .= '予約制 ';
        }
        $or_notes .= $article->event_comment;
        $article->or_notes = $or_notes;
        $article->kyakuzuke_simple = 1;
        $article->kyakuzuke = 0;
        $article->photo_dl_permission = 2;
        if ($article->ground > 0 && $article->ground < 6) {
            $article->land_chimoku = $article->ground;
        } else {
            $article->land_chimoku = 9;
        }

        if ($article->interior == 2) {
            $interior_place = RelationInterior::where('article_id', $article->building_id)->get();
            if ($interior_place) {
                foreach ($interior_place as $v) {
                    if ($v->item_id == 1) {
                        $article->reform_wet_area_place1 = 1;
                    }
                    if ($v->item_id == 2) {
                        $article->reform_wet_area_place2 = 2;
                    }
                    if ($v->item_id == 3) {
                        $article->reform_wet_area_place3 = 3;
                    }
                    if ($v->item_id == 4) {
                        $article->reform_interior_place2 = 2;
                    }
                    if ($v->item_id == 6) {
                        $article->reform_interior_place3 = 3;
                    }
                    if ($v->item_id == 5) {
                        $article->reform_interior_place4 = 4;
                    }
                }
            }
        }
        //dd($article->toArray());

        return $article;
    }

    function moldingDataMansion($article, $mansion)
    {
        if ($mansion->property == 6) {
            if ($mansion->property_sub == 1) {
                $article->bt = "1301";
            } else if ($mansion->property_sub == 2) {
                $article->bt = "1302";
            }
        } else if ($mansion->property == 7) {
            if ($mansion->property_sub == 1) {
                $article->bt = "1307";
            } else if ($mansion->property_sub == 2) {
                $article->bt = "1308";
            }
        } else {
            $article->bt = "1301";
        }

        if ($article->event_schedule == 4) {
            if (!empty($article->from_event)) {
                $from_event = explode("-", $article->from_event);
                if (count($from_event) == 3) {
                    $article->or_open_y = $from_event[0];
                    $article->or_open_m = $from_event[1];
                    $article->or_open_d = $from_event[2];
                }
            }
            if (!empty($article->to_event)) {
                $to_event = explode("-", $article->to_event);
                if (count($to_event) == 3) {
                    $article->or_end_y = $to_event[0];
                    $article->or_end_y = $to_event[1];
                    $article->or_end_y = $to_event[2];
                }
            }
        } else if ($article->event_schedule == 3) {
            if (!empty($article->event_day)) {
                $article->event_day = str_replace("/", "-", $article->event_day);
                $check_event_day = explode(",", $article->event_day);
                if (count($check_event_day) > 1) {
                    $article->event_day = $check_event_day[0];
                }
                $from_event = explode("-", $article->event_day);
                if (count($from_event) == 3) {
                    $article->or_open_y = $from_event[0];
                    $article->or_open_m = $from_event[1];
                    $article->or_open_d = $from_event[2];
                }
            }
        }

        switch ($article->parking) {
            case 1:
                //$article->parking_kubun = 4;
                //break;
            case 2:
                $article->parking_kubun = 2;
                break;
            case 3:
                if ($article->parking_yes == 1) {
                    $article->parking_kubun = 1;
                    $article->parking_keiyaku = 0;
                    $article->parking_money = $article->parking_yes_cost_from;
                } else {
                    $article->parking_kubun = 1;
                    $article->parking_keiyaku = 3;
                    $article->parking_money = '';
                }
                break;
            case 4:
                $article->parking_kubun = 1;
                $article->parking_keiyaku = 1;
                break;
            case 5:
                $article->parking_kubun = 1;
                $article->parking_keiyaku = 0;
                $article->parking_money = '';
                break;
            case 6:
                if ($article->parking_yes == 1) {
                    $article->parking_kubun = 1;
                    $article->parking_keiyaku = 0;
                    $article->parking_money = $article->parking_designated_cost;
                }
                break;
        }
        if ($article->parking == 1 && $article->parking_out == 0) {
            $article->parking_kubun = 4;
        }
        if ($article->parking == 1 && $article->parking_out == 1) {
            $article->parking_kubun = 3;
        }

        $article->empty_contents = $article->room_num;
        $article->flg_bukken_name = $article->room_num_disp == 1 ? 1 : 2;
        $article->all_number = $mansion->total_unit;
        $article->land_area_all = $mansion->land_area_val;
        $article->sekou_company_name = $mansion->construction_company;
        $article->house_kanrinin = $this->setManagementForm($mansion->management_form)['manager'];
        $article->house_kanri_keitai = $this->setManagementForm($mansion->management_form)['managementForm'];
        if ($article->balcony_area == 1) {
            $article->ft227 = 1;
        }

        if ($article->garden_area == 1) {
            $article->ft225 = 1;
        }
        $article->house_kanri_kaisha = $mansion->management_company;
        $article->balcony_umu = $article->balcony_area == 0 ? 2 : 1;
        if ($article->balcony_umu == 1) {
            $article->balcony_area = $article->balcony_area_val;
        }
        foreach ($mansion->shareds as $shared) {
            $shared_id = $shared->item_id;
            switch ($shared_id) {
                case 2:
                    $article->ft255 = 1;
                    break;
                case 4:
                    $article->ft224 = 1;
                    break;
                case 5:
                    $article->ft230 = 1;
                    break;
                case 6:
                    $article->ft253 = 1;
                    break;
                case 8:
                    $article->ft223 = 1;
                    break;
                case 1:
                    $article->ft426 = 1;
                    break;
            }
        }

        if ($article->management == 1) {
            $article->money_kyoueki_ck = 1;
            $article->money_kyoueki_tax = 2;
            $article->money_kyoueki = $article->management_cost;
        }

        if ($article->repair == 1) {
            $article->money_shuuzen = $article->repair_cost;
        } else if ($article->repair == 0) {
            $article->money_shuuzen = 0;
        }

        if (!empty($article->another_cost1)) {
            $article->money_sonota1_ck = 1;
            $article->money_sonota1 = $article->another_cost1;
            switch ($article->another_cost_unit1) {
                case 1:
                    $article->money_sonota_str1 = "月";
                    break;
                case 2:
                    $article->money_sonota_str1 = "年";
                    break;
                case 3:
                    $article->money_sonota_str1 = "一括";
                    break;
            }
        }
        if ($article->repair_fund == 1) {
            $article->money_shuuzenkikin_ck = 1;
            $article->money_shuuzenkikin = $article->repair_fund_unit;
        } else {
            $article->money_shuuzenkikin_ck = "";
            $article->money_shuuzenkikin = "";
        }
        //$article->money_shuuzenkikin_ck = $article->parking_require_fund;
        //$article->money_shuuzenkikin = $article->parking_require_fund_cost;

        if (!empty($article->another_cost2)) {
            $article->money_sonota2_ck = 1;
            $article->money_sonota2 = $article->another_cost2;
            switch ($article->another_cost_unit2) {
                case 1:
                    $article->money_sonota_str2 = "月";
                    break;
                case 2:
                    $article->money_sonota_str2 = "年";
                    break;
                case 3:
                    $article->money_sonota_str2 = "一括";
                    break;
            }
        }

        if ($mansion->age_year < 1926) {
            $article->kenchiku_year = 1926;
        } else {
            $article->kenchiku_year = $mansion->age_year;
        }
        $article->kenchiku_month = $mansion->age_month;
        $article->b_name = mb_substr($article->name_portal, 0, 42);

        // 物件担当者
        $user_info = UserInfo::getDataById($article->hp_charge);
        $name_info = '';
        $name_info = $user_info->last_name ?? '';
        if ($name_info != '') {
            $name_info .= ' ';
        }
        $name_info .= $user_info->first_name ?? '';
        $article->tantou_name = $name_info;

        // 状態
        $isClose = [4, 5, 6];
        if (in_array($article->status, $isClose)) {
            // 販売中以外
            $article->status_h = "3";
        } else {
            // 販売中
            $article->status_h = "1";
        }

        // LIFULL HOME'S掲載
        if ($article->homes == 1) {
            $article->flg_open = "0";
        } elseif ($article->homes == 2) {
            $article->flg_open = "1";
        }
        $time_limit = date('d/m/Y', strtotime('+2 weeks'));
        $day = explode('/', $time_limit);
        $article->timelimit_date_y = $day[2];
        $article->timelimit_date_m = $day[1];
        $article->timelimit_date_d = $day[0];
        // 2.所在地
        // 郵便番号
        $zip_info = $mansion->zip;
        $zip_list = explode('-', $zip_info);
        $article->post1 = $zip_list[0] ?? '';
        $article->post2 = $zip_list[1] ?? '';

        $ar_addr1 = [
            14  =>  "lubSWM0xC_rXi-RBdHFC_A",
            11  =>  "tl2t74MQfsbXi-RBdHFC_A",
            12  =>  "drv6Kix16svXi-RBdHFC_A",
            28  =>  "0hNR5oDOggnXi-RBdHFC_A",
            27 =>   "TOoNMbIEn2LXi-RBdHFC_A"
        ];
        $ar_temporary_addr1 = [
            14  =>  14,
            11  =>  26,
            12  =>  25,
            28  =>  28,
            27 => 27
        ];
        $article->addr1 = $ar_addr1[$mansion->address1];
        $article->temporary_addr1 = $ar_temporary_addr1[$mansion->address1];

        $article->address2 = $mansion->address2;
        $article->address3 = $mansion->address3;

        // 番地など
        $article->addr3_addr4_name = $article->address;
        if (is_null($article->address)) {
            // addr3_addr4_nameは必須項目
            $article->flg_addr_hidden = "0";
        } else {
            $article->flg_addr_hidden = "1";
        }
        $article->display_addr_name = $article->address;

        //緯度経度
        $article->nl = $article->lat;
        $article->el = $article->lng;

        // 3.交通
        $article->window_angle = $article->balcony_direction == 0 ? "" : $article->balcony_direction;
        // 金銭・建物タブ
        // 1.価格
        if ($article->tax == 1) {
            $article->money_tax = 3;
        } else {
            $article->money_tax = 2;
        }

        switch ($article->land_right) {
            case 0:
                $article->land_right = "";
                break;
            case 1:
                $article->land_right = 1;
                break;
            case 2:
                switch ($article->leasehold_kind) {
                    case 1:
                        $article->land_right = 3;
                        break;
                    case 2:
                        $article->land_right = 6;
                        break;
                    case 3:
                        $article->land_right = 7;
                        break;
                    case 4:
                        $article->land_right = 5;
                        break;
                    case 8:
                        $article->land_right = 5;
                        break;

                    case 5:
                        $article->land_right = 2;
                        break;
                    case 6:
                        $article->land_right = 4;
                        break;
                    case 7:
                        $article->land_right = 5;
                        break;
                }
                break;
            case 3:
                switch ($article->leasehold_kind) {
                    case 1:
                        $article->land_right = 3;
                        break;
                    case 2:
                        $article->land_right = 6;
                        break;
                    case 3:
                        $article->land_right = 7;
                        break;
                    case 4:
                        $article->land_right = 7;
                        break;
                    case 8:
                        $article->land_right = 5;
                        break;

                    case 5:
                        $article->land_right = 2;
                        break;
                    case 6:
                        $article->land_right = 4;
                        break;
                    case 7:
                        $article->land_right = 5;
                        break;
                }
                break;
        }

        // 構造
        if ($mansion->construction == 8) {
            $article->house_kouzou = 10;
        } else if ($mansion->construction == 9) {
            $article->house_kouzou = 11;
        } else if ($mansion->construction == 11) {
            $article->house_kouzou = 9;
            $article->house_kouzou_other = 'RCB造';
        } else if ($mansion->construction == 10) {
            $article->house_kouzou = 4;
        } else {
            $article->house_kouzou = $mansion->construction;
        }

        switch ($mansion->pet) {
            case 0:
                $article->ft109 = "";
                break;
            case 1:
                $article->ft109 = 3;
                break;
            case 2:
                $article->ft109 = 2;
                break;
            case 3:
                $article->ft109 = 2;
                break;
        }

        // 建物階建て
        $article->house_kaisuu = $mansion->floor;
        $article->house_kaisuu_chika = $mansion->underground;
        if (!empty($article->house_kaisuu)) {
            $article->flg_chijyo = 1;
            $article->room_kaisuu = $article->whereabouts;
        } else {
            $article->flg_chijyo = -1;
            $article->room_kaisuu = $article->whereabouts;
        }
        if ($article->maisonette == 1) {
            $article->room_kaisuu = $article->maisonette_from;
        } else {
            $article->room_kaisuu = $article->whereabouts;
        }
        $article->house_area = $article->total_area_val;
        $article->house_area_kind = $article->total_area == 0 ? "" : $article->total_area;
        $article->madori_number_all = $article->floor_plan;
        switch ($article->floor_plan_type) {
            case 1:
                $article->madori_kind_all = 30;
                break;
            case 2:
                $article->madori_kind_all = 50;
                break;
            case 3:
                $article->madori_kind_all = 10;
                break;
            case 4:
                $article->madori_kind_all = 20;
                break;
            case 5:
                $article->madori_kind_all = 25;
                break;
            case 6:
                $article->madori_kind_all = 35;
                break;
            case 7:
                $article->madori_kind_all = 40;
                break;
            case 8:
                $article->madori_kind_all = 45;
                break;
            case 9:
                $article->madori_kind_all = 55;
                break;
        }
        if ($article->land_rent == 1) {
            $article->money_shakuchi = $article->land_rent_val;
        }
        switch ($article->current_status) {
            case 10:
                $article->genkyo_code = 1;
                break;
            case 11:
                $article->genkyo_code = 2;
                break;
            case 12:
                $article->genkyo_code = 3;
                break;
        }

        switch ($article->water_supply) {
            case 1:
                $article->ft200 = 1;
                break;
            case 2:
                $article->ft200 = 99;
                break;
            case 3:
                $article->ft200 = 2;
                break;
        }

        switch ($mansion->gas) {
            case 1:
                $article->ft201 = 1;
                break;
            case 2:
            case 3:
                $article->ft201 = 2;
                break;
            case 4:
                $article->ft244 = 1;
                $article->ft201 = 99;
                break;
            default:
                $article->ft201 = "";
                break;
        }

        switch ($article->sewerage) {
            case 1:
                $article->ft202 = 1;
                break;
            case 2:
            case 3:
                $article->ft202 = 2;
                break;
            case 0:
                $article->ft202 = "";
                break;
        }

        $article->parking_number = $article->parking_num;
        $article->parking_memo = '';
        if ($article->parking_num != '') {
            $article->parking_memo = '駐車可能台数 ' . $article->parking_num . '台';
        }

        $article->school_ele_name = optional($article->primarySchool)->name;
        $article->school_ele_distance = $article->primary_school_distance;
        $article->school_jun_name = optional($article->secondarySchool)->name;
        $article->school_jun_distance = $article->secondary_school_distance;
        $article->tokuchou = $article->homes_copy;
        $article->etc = $article->homes_comment;

        $or_notes = '';
        if ($article->event_schedule == 1) {
            $or_notes .= '毎週土日祝開催 ';
        } elseif ($article->event_schedule == 2) {
            $or_notes .= '毎週土日開催 ';
        } elseif ($article->event_schedule == 5) {
            $or_notes .= '公開中 ';
        }
        if ($article->reservation == 1) {
            $or_notes .= '予約制 ';
        }
        $or_notes .= $article->event_comment;
        $article->or_notes = $or_notes;
        //$article->or_notes = $article->event_comment;

        $vendor = $article->vendors()->first();
        if (isset($vendor)) {
            $firstRelation = \App\Models\RelationVendorArticle::firstRelationVendorArticle($article->building_id, $vendor->id);
            $article->moto_name = $vendor->name;
            $vendor_tel = $vendor->vendor_tel1;
            $vendor_fax = $vendor->vendor_fax;
            $vendor_tel = explode("-", $vendor_tel);
            if (count($vendor_tel) == 3) {
                $article->moto_tel1 = $vendor_tel[0];
                $article->moto_tel2 = $vendor_tel[1];
                $article->moto_tel3 = $vendor_tel[2];
            }
            $vendor_fax = explode("-", $vendor_fax);
            if (count($vendor_fax) == 3) {
                $article->moto_fax1 = $vendor_fax[0];
                $article->moto_fax2 = $vendor_fax[1];
                $article->moto_fax3 = $vendor_fax[2];
            }
            $ad_conf_day = $firstRelation->ad_conf_day;
            $ad_conf_day = explode("-", $ad_conf_day);
            if (count($ad_conf_day) == 3) {
                $article->confirm_date_y = $ad_conf_day[0];
                // $article->confirm_date_m = $ad_conf_day[1];
                // $article->confirm_date_d = $ad_conf_day[2];
                $article->confirm_date_m = date('m');
                $article->confirm_date_d = date('d');
            }
            $article->moto_etc = $firstRelation->charge;
        }
        $article->land_area_kind = $article->land_area != 0 ? $article->land_area : "";
        $article->land_area = $article->land_area_val;
        $article->land_toshi = $article->city_plan == 5 ? "" : $article->city_plan;
        $article->land_kenpei = $article->building_rate;
        $article->land_youseki = $article->volume_rate;
        if (!empty($mansion->leasehold_period_year)) {
            $article->keiyaku_year = $mansion->leasehold_period_year;
        }
        if (!empty($mansion->leasehold_period_month)) {
            $article->keiyaku_month = $mansion->leasehold_period_month;
        }
        if ($article->land_right == 1) {
            $article->keiyaku_year = '';
            $article->keiyaku_month = '';
        }

        switch ($article->road_burden) {
            case 0:
                $article->land_shidou_flg = 1;
                break;
            case 1:
                $article->land_shidou_flg = 2;
                $article->land_shidou = $article->road_burden_area;
                break;
            default:
                $article->land_shidou_flg = 0;
                break;
        }

        switch ($article->set) {
            case 1:
                $article->land_setback_flg = 1;
                break;
            case 2:
            case 3:
                $article->land_setback_flg = 2;
                $article->land_setback = $article->set_area;
                break;
            default:
                $article->land_setback_flg = "";
                break;
        }

        $article->std_angle1 = $article->land_direction1;
        $article->std_width1 = $article->road_width1;
        $article->std_kind1 = $article->land_kind1;
        $article->std_maguchi1 = $article->frontage1;

        $article->std_angle2 = $article->land_direction2;
        $article->std_width2 = $article->road_width2;
        $article->std_kind2 = $article->land_kind2;
        $article->std_maguchi2 = $article->frontage2;

        $article->std_angle3 = $article->land_direction3;
        $article->std_width3 = $article->road_width3;
        $article->std_kind3 = $article->land_kind3;
        $article->std_maguchi3 = $article->frontage3;

        if ($article->move_in < 4 && $article->move_in != 0) {
            $article->usable_status = $article->move_in;
        } else {
            $article->usable_status = 2;
        }
        if ($article->usable_status == 3) {
            $article->usable_date_y = $article->move_in_year;
            $article->usable_date_m = $article->move_in_month;
        }

        //$article->land_youto = $article->use_area;
        $article->keiyaku_period_kind = 2;

        $lawrestrictions = $mansion->lawrestrictions;
        $land_seigen = "";
        foreach ($lawrestrictions as $key => $lawrestriction) {
            $old_land = $land_seigen;
            if ($key == 0) {
                $land_seigen .= "{$lawrestriction->name}";
            } else {
                $land_seigen .= ", {$lawrestriction->name}";
            }

            if (strlen($land_seigen) > 200) {
                $land_seigen = $old_land;
                break;
            }
        }
        //$land_seigen = "";
        $other_restrictions = $mansion->otherRestrictions;
        $other_names = [
            "", "一部都市計画道路", "一部協定通路", "日影制限有", "隅切り有",
            "接道と段差有", "敷地内段差有", "壁面後退有", "建築協定有",
            "崖上につき建築制限有", "崖下につき建築制限有", "不整形地"
        ];

        foreach ($other_restrictions as $key => $other_restriction) {
            $old_land = $land_seigen;

            if (isset($other_names[$other_restriction['item_id']])) {
                $land_seigen .= ", {$other_names[$other_restriction['item_id']]}";
            }

            if (strlen($land_seigen) > 100) {
                $land_seigen = $old_land;
                break;
            }
        }
        if ($mansion->other_comment != '') {
            $land_seigen .= ', ' . $mansion->other_comment;
        }

        $article->land_seigen = $land_seigen;
        $article->all_number = $article->m_total_unit;
        $article->land_youto = $mansion->use_area;

        $article->photo_dl_permission = 2;
        $article->kyakuzuke = 0;
        //        if($article->interior == 1){
        ////            $article->reform_interior_place1 = "";
        ////        }
        if ($article->interior == 2) {
            $interior_place = RelationInterior::where('article_id', $article->building_id)->get();
            if ($interior_place) {
                foreach ($interior_place as $v) {
                    if ($v->item_id == 1) {
                        $article->reform_wet_area_place1 = 1;
                    }
                    if ($v->item_id == 2) {
                        $article->reform_wet_area_place2 = 2;
                    }
                    if ($v->item_id == 3) {
                        $article->reform_wet_area_place3 = 3;
                    }
                    if ($v->item_id == 4) {
                        $article->reform_interior_place2 = 2;
                    }
                    if ($v->item_id == 6) {
                        $article->reform_interior_place3 = 3;
                    }
                    if ($v->item_id == 5) {
                        $article->reform_interior_place4 = 4;
                    }
                }
            }
        }
        //dd($article->toArray());
        return $article;
    }

    function saveData($article)
    {
        logHomes('-- Save data: Start.');
        // 物件メンテ画面へアクセス 土地 登録確認
        $url = 'https://manager.homes.co.jp/index.php';
        $POST_DATA = $this->moldingData($article);
        $this->mergeAddress($article, $POST_DATA);

        if ($this->type == 2) {
            logHomes('-- -- Upload image: Start.');
            $dataUpload = $this->uploadImage($url, $POST_DATA, $article);

            $POST_DATA["tab"] = "img";
            $POST_DATA["b2"] = $dataUpload["b2"] ?? "";
            $POST_DATA["b2time"] = $dataUpload["b2time"] ?? "";
            $check_status = $dataUpload["status"] ?? "";
            if($check_status == '"fatal"'){
                session()->flash('message_ok', "HOME'Sに画像入稿できませんでした。");
                logHomes('-- -- -- Upload image failed.');
                logHomes('-- -- Upload image: End.');
                return false;
            }

            logHomes('-- -- -- Upload image success.');
            logHomes('-- -- Upload image: End.');
        }

        $buildingId = $this->argument('id');
        $portalId = $this->getPortalId($buildingId);

        if (!isset($portalId)){
            $portalId  = $article->homes_no;
        }

        logHomes("-- -- Data portal: building_id = $buildingId, portal_id = $portalId.");
        if (isset($portalId)) {
            PortalStatusArticle::updateOrCreate(['portal_type' => 2, 'article_id' => $buildingId, 'portal_user' =>  $this->getUserHomeId()],
                    ['portal_id' => $portalId]
                );
            $article->homes_no = $portalId;
            $this->setDataFromHomes($POST_DATA, $article);
            $this->update($article, $POST_DATA, $portalId, $url);

        }else {
            $this->upToHome($POST_DATA, $article );
        }


//        if (empty($article->homes_no)) {
//            $this->upToHome($POST_DATA, $url, $article);
//        } else {
//             //$dataHome = $this->getArticleHomes("https://manager.homes.co.jp/index.php?action=sale_reg_form&b=", $article->homes_no);
//            // $this->setDefaultValue($POST_DATA, $article);
//
//            $idMainHome = $this->getPortalId($buildingId);
//            if($idMainHome == 0){
//                PortalStatusArticle::where('article_id', $buildingId)->where('portal_id', $article->homes_no)->where('portal_type', 2)->delete();
//            }else if($article->homes_no !== $idMainHome){
//                PortalStatusArticle::where('article_id', $buildingId)->where('portal_id', $article->homes_no)->update([
//                    'portal_id' => $idMainHome
//                ]);
//            }
//            if (empty($dataHome)) {
//                // $this->setDefaultValue($POST_DATA, $article);
//                $buildingId = $this->argument('id');
//                $idMainHome = $this->getPortalId($buildingId);
//                if($idMainHome == 0){
//                    PortalStatusArticle::where('article_id', $buildingId)->where('portal_id', $article->homes_no)->where('portal_type', 2)->delete();
//                }else if($article->homes_no !== $idMainHome){
//                    PortalStatusArticle::where('article_id', $buildingId)->where('portal_id', $article->homes_no)->update([
//                        'portal_id' => $idMainHome
//                    ]);
//                }
//                $dataMainHome = $this->getArticleHomes("https://manager.homes.co.jp/index.php?action=sale_reg_form&b=", $idMainHome);
//
//                foreach ($dataMainHome as $key => $value) {
//                    if (is_string($dataMainHome[$key])) {
//                        $dataMainHome[$key] = mb_convert_encoding($dataMainHome[$key], 'EUC-JP', 'UTF-8');
//                    }
//                }
//
//                $arr = [];
//                $img_homes = 0;
//                $img_bukkens = $article->relationPortalPhotos()->type(config('const.HOMES'))->del(0)->limit(30)->count();
//
//                foreach ($dataMainHome as $key => $value) {
//                    if (array_key_exists($key, $POST_DATA) && array_key_exists($key, $dataMainHome)) {
//                        if ($POST_DATA[$key] !== $dataMainHome[$key]) {
//                            $arr[$key] = $POST_DATA[$key];
//                        }
//                    }
//                    if (array_key_exists($key, $POST_DATA) && !array_key_exists($key, $dataMainHome)) {
//                        $arr[$key] = $POST_DATA[$key];
//                    }
//
//                    if(strpos($key, 'hoto_type')){
//                        if($value != 9){
//                            $img_homes++;
//                            if($img_homes > $img_bukkens){
//                                $dataMainHome[$key] = 9;
//                            }
//                        }
//                    }
//                }
//
//                foreach ($arr as $key => $value) {
//                    $dataMainHome[$key] = $arr[$key];
//                }
//
//                if (empty($dataMainHome['reform_wet_area_year']) && empty($dataMainHome['reform_wet_area_month'])) {
//                    for ($i = 1; $i <= 6; $i++) {
//                        unset($dataMainHome['reform_wet_area_place' . $i]);
//                    }
//                }
//
//                if (empty($dataMainHome['reform_interior_year']) && empty($dataMainHome['reform_interior_month'])) {
//                    for ($i = 1; $i <= 6; $i++) {
//                        unset($dataMainHome['reform_interior_place' . $i]);
//                    }
//                }
//
//                if (empty($dataMainHome['reform_exterior_year']) && empty($dataMainHome['reform_exterior_year'])) {
//                    for ($i = 1; $i <= 2; $i++) {
//                        unset($dataMainHome['reform_exterior_place' . $i]);
//                    }
//                }
//
//                $dataMainHome['action'] = 'sale_reg_confirm';
//                $dataMainHome['tab'] = 'base';
//                $dataMainHome['b2'] = $POST_DATA["b2"];
//                $dataMainHome['b2time'] = $POST_DATA["b2time"];
//
//                $this->regisMainHouse($url, $dataMainHome, $article);
//
//                //Delete Image Response
//                if($this->type == 2){
//                    unset($POST_DATA['b2']);
//                    unset($POST_DATA['b2time']);
//                    unset($POST_DATA['tab']);
//
//                    if($img_homes > $img_bukkens){
//                        for($i = $img_bukkens + 1; $i <= $img_homes; $i++){
//                            $dataUpload = $this->deleteImage($url, $POST_DATA, $article,$i);
//                            $dataMainHome["b2"] = $dataUpload["b2"] ?? "";
//                            $dataMainHome["b2time"] = $dataUpload["b2time"] ?? "";
//
//                            $this->regisMainHouse($url, $dataMainHome, $article);
//                        }
//                    }
//                }
//            } else {
//                /*$panoramaUid = $this->uploadPanorama($article);
//                if (!empty($panoramaUid)) {
//                    $portalHomesPanoramaDefault = PortalHomesPanorama::ofImage($article->building_id, config('const.PANORAMA_TYPE_DEFAULT'))->first();
//                    if (!empty($portalHomesPanoramaDefault) && !empty($portalHomesPanoramaDefault->name)) {
//                        $urlPanorama = 'https://manager.homes.co.jp/ajax/index.php';
//                        $DataPanorama['action'] = 'sale_panorama_update';
//                        $DataPanorama['tk'] = '1';
//                        $DataPanorama['panorama_uid'] = $panoramaUid;
//                        $DataPanorama['panorama_name'] = $portalHomesPanoramaDefault->name;
//                        $DataPanorama['panorama_close'] = '閉じる';
//                        $DataPanorama['panorama_update'] = '登録';
//                        $headers = ["Referer: https://manager.homes.co.jp/index.php?action=sale_panorama_list&tk=1"];
//                        $this->requestWithData($urlPanorama, $DataPanorama, true, $headers);
//                    }
//                    $POST_DATA['panorama_link_status'] = !empty($portalHomesPanoramaDefault) ? $portalHomesPanoramaDefault->public_type : 1;
//                }
//                $POST_DATA['panorama_uid'] = $panoramaUid;*/
//
//                $this->upToHome($POST_DATA, $url, $article);
//            }
//        }
    }


    private function update($article, $POST_DATA, $idMainHome, $url){
        logHomes('-- -- Up to HOMES: Start.');
        $dataMainHome = $this->getArticleHomes("https://manager.homes.co.jp/index.php?action=sale_reg_form&b=", $idMainHome);
        foreach ($dataMainHome as $key => $value) {
            if (is_string($dataMainHome[$key])) {
                $dataMainHome[$key] = mb_convert_encoding($dataMainHome[$key], 'EUC-JP', 'UTF-8');
            }
        }
        $arr = [];
        $img_homes = 0;
        $img_bukkens = $article->relationPortalPhotos()->type(config('const.HOMES'))->del(0)->limit(30)->count();
        foreach ($dataMainHome as $key => $value) {
            if (array_key_exists($key, $POST_DATA) && array_key_exists($key, $dataMainHome)) {
                if ($POST_DATA[$key] !== $dataMainHome[$key]) {
                    $arr[$key] = $POST_DATA[$key];
                }
            }
            if (array_key_exists($key, $POST_DATA) && !array_key_exists($key, $dataMainHome)) {
                $arr[$key] = $POST_DATA[$key];
            }

            if(strpos($key, 'hoto_type')){
                if($value != 9){
                    $img_homes++;
                    if($img_homes > $img_bukkens){
                        $dataMainHome[$key] = 9;
                    }
                }
            }
        }

        foreach ($arr as $key => $value) {
            $dataMainHome[$key] = $arr[$key];
        }

        if (empty($dataMainHome['reform_wet_area_year']) && empty($dataMainHome['reform_wet_area_month'])) {
            for ($i = 1; $i <= 6; $i++) {
                unset($dataMainHome['reform_wet_area_place' . $i]);
            }
        }

        if (empty($dataMainHome['reform_interior_year']) && empty($dataMainHome['reform_interior_month'])) {
            for ($i = 1; $i <= 6; $i++) {
                unset($dataMainHome['reform_interior_place' . $i]);
            }
        }

        if (empty($dataMainHome['reform_exterior_year']) && empty($dataMainHome['reform_exterior_year'])) {
            for ($i = 1; $i <= 2; $i++) {
                unset($dataMainHome['reform_exterior_place' . $i]);
            }
        }

        $dataMainHome['action'] = 'sale_reg_confirm';
        $dataMainHome['tab'] = 'base';
        $dataMainHome['b2'] = $POST_DATA["b2"];
        $dataMainHome['b2time'] = $POST_DATA["b2time"];

        $this->regisMainHouse($url, $dataMainHome, $article, true);

        //Delete Image Response
        if($this->type == 2){
            unset($POST_DATA['b2']);
            unset($POST_DATA['b2time']);
            unset($POST_DATA['tab']);
            if($img_homes > $img_bukkens){
                for($i = $img_bukkens + 1; $i <= $img_homes; $i++){
                    $dataUpload = $this->deleteImage($url, $POST_DATA, $article,$i);
                    $dataMainHome["b2"] = $dataUpload["b2"] ?? "";
                    $dataMainHome["b2time"] = $dataUpload["b2time"] ?? "";
                    $this->regisMainHouse($url, $dataMainHome, $article, true);
                }
            }
        }

        logHomes('-- -- Up to HOMES: End.');
    }

    private function getUserHomeId(){
        $user = $this->user;
        $shop =  MstStore::getDataByCode($user->company_id, $user->store_id);
        return $shop->homes_id ?? "";
    }

    public function upToHome($POST_DATA, $article)
    {
        logHomes('-- -- Up to HOMES: Start.');
        foreach ($POST_DATA as $key => $value) {
            if (is_string($POST_DATA[$key])) {
                $POST_DATA[$key] = mb_convert_encoding($POST_DATA[$key], 'EUC-JP', 'UTF-8');
            }
        }
        logHomes('-- -- -- Data up to HOMES: ' . jsonEncodeJp($POST_DATA));
        $this->postConfirmAndDone($POST_DATA, $article);
        logHomes('-- -- Up to HOMES: End.');
//        return;
//        $response = $this->requestWithData($url, http_build_query($POST_DATA), true, array('Accept: application/form-data'));
//        $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
//
//        $idHomeNo = $this->detectAndHandleSaveSuccess($response, $article->building_id);
//
//        if ($idHomeNo !== 0) {
//            /**
//             * Request data to next step in bukken kanri
//             */
//            $dap = $this->getArticleHomes("https://manager.homes.co.jp/index.php?action=sale_reg_form&b1=", $idHomeNo);
//            $dap['tab'] = 'amount_req';
//            foreach ($dap as $key => $value) {
//                if (is_string($dap[$key])) {
//                    $dap[$key] = mb_convert_encoding($dap[$key], 'EUC-JP', 'UTF-8');
//                }
//            }
//
//            $this->regisMainHouse($url, $dap, $article);
//        }
    }

    private function postConfirmAndDone($POST_DATA, $article){
        $POST_DATA['action'] = 'sale_reg_confirm';
        $response = $this->requestWithData($this->indexUrl, http_build_query($POST_DATA), true, array('Accept: application/form-data'));
        $dom = HtmlDomParser::str_get_html($response);
        $errMessages = $dom->find('.errorMessage ul li');
        $error = null;
        foreach ($errMessages as $i => $er) {
            $error .= "<br>" . ($i + 1) . '. ' . html_entity_decode($er->innertext);
        }
        $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
        $this->log($response);
        if (isset($error)){
            session()->flash('message_modal', '<strong>入稿できませんでした。物件詳細ページを見直してください。</strong> ' . $error);
            logHomes("-- -- -- Up to HOMES failed: $error.");
        }else {
            $this->postDone($article, $response);
        }
    }


    private function postDone($article, $response){
        $formPattern = '/<form.*?name="bukken_confirm".*?>(.*?)<\/form>/s';
        preg_match($formPattern, $response, $formMatches);

        $pattern = '/<input.*?type="hidden".*?name="(?<name>.*?)".*?value="(?<value>.*?)".*?>/';
        if (!isset($formMatches[0])) return;
        preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
        $hiddenData = collect($matches)
            ->pluck('value', 'name')
            ->toArray();

        $response = $this->requestWithData($this->indexUrl, http_build_query($hiddenData), true, array('Accept: application/form-data'));
        $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
        $this->log($response);
        $pattern = '/<div class="compMessage">([^$]+?)<\/div>/';
        preg_match_all($pattern, $response, $matchSaveSuccess);

        $message = '';
        foreach ($matchSaveSuccess[1] as $value) {
            preg_match('/<h3>([^$]+?)<\/h3>/', $value, $matches);
            $message .= '<br>' . $matches[1];
        }
        $idMainHouse = substr($message, -13, 13);
        if (count($matchSaveSuccess) > 1 && count($matchSaveSuccess[0]) > 0) {
            PortalStatusArticle::where('portal_id', $idMainHouse)->where('portal_type', 2)->delete();
            $save_data = [
                'article_id'    =>  $article->building_id,
                'portal_id'     =>  $idMainHouse,
                'portal_user'   =>  $this->getUserHomeId(),
                'portal_type'   =>  2
            ];
            PortalStatusArticle::insert($save_data);
            session()->flash('message_ok', "HOMESに本登録されました");
            logHomes("-- -- -- Up to HOMES: success (idMainHouse = $idMainHouse, data = " . jsonEncodeJp($save_data) . ").");
        } else {
            logHomes("-- -- -- Up to HOMES: failed (idMainHouse = $idMainHouse).");
        }
    }


    public function regisMainHouse($url, $dap, $article, $isUpdate = false)
    {
        logHomes('-- -- Regis main house: Start.');
        logHomes('-- -- -- Data regis: ' . jsonEncodeJp($dap));
        $response = $this->requestWithData($url, http_build_query($dap), true, array('Accept: application/form-data'));

        $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
        $this->log($response);

        $step2 = $this->detectAndHandleSaveSuccess($response, $article->building_id);

        if ($step2 !== 0) {
            $formPattern = '/<form.*?name="bukken_confirm".*?>(.*?)<\/form>/s';
            preg_match($formPattern, $response, $formMatches);

            $pattern = '/<input.*?type="hidden".*?name="(?<name>.*?)".*?value="(?<value>.*?)".*?>/';
            preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
            $hiddenData = collect($matches)
                ->pluck('value', 'name')
                ->toArray();

            $response = $this->requestWithData($url, http_build_query($hiddenData), true, array('Accept: application/form-data'));
            $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
            $this->log($response);
            $pattern = '/<div class="compMessage">([^$]+?)<\/div>/';
            preg_match_all($pattern, $response, $matchSaveSuccess);

            $message = '';
            foreach ($matchSaveSuccess[1] as $value) {
                preg_match('/<h3>([^$]+?)<\/h3>/', $value, $matches);
                $message .= '<br>' . $matches[1];
            }
            $idMainHouse = substr($message, -13, 13);
            PortalStatusArticle::where('article_id', $article->building_id)->where('portal_type', 2)->where('portal_user', $this->getUserHomeId())->update([
                'portal_id' => $idMainHouse
            ]);
            if (count($matchSaveSuccess) > 1 && count($matchSaveSuccess[0]) > 0) {
                session()->flash('message_ok', "HOMESに本登録されました");
            }
        } else {
            $user = $this->user;
            $shop = MstStore::getDataByCode($user->company_id, $user->store_id);
            $portal = PortalStatusArticle::where('article_id', $article->building_id)
                ->where('portal_type', 2)
                ->where('portal_user', $shop->homes_id)
                ->orderBy('created_at', 'desc');
            $homesNo = $portal->first();
            if(!empty($homesNo)){
                $url = 'https://manager.homes.co.jp/index.php?action=sale_reg_top&del_id='.$homesNo->portal_id;
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
                curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
                curl_setopt_array($curl, $this->option); // 共通オプションの設定
                $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行
                curl_close($curl);

                if ($isUpdate === false){
                    $portal->delete();
                }
            }
        }

        logHomes('-- -- Regis main house: End.');
    }

    function getPortalId($id){
        logHomes('-- -- Get portal id: Start.');
        $url = 'https://manager.homes.co.jp/index.php';
        $data = [
            'action' => 'sale_list_view',
            'action_type' => '',
            'csv_output_header' => '',
            'tk' => 1,
            'view' => 1,
            'sort_key' => '',
            'sort_order' => '',
            'list_rows' => '',
            'rows_offset' => '',
            'src_pano' => '',
            'src_insp' => '',
            'src_rl' => '',
            'src_staff_comment' => '',
            'src_addr1' => '',
            'src_addr2' => '',
            'src_rosen_addr1' => '',
            'src_rosen' => '',
            'src_eki' => '',
            'src_tiku_from' => '',
            'src_tiku_to' => '',
            'src_walk_from' => '',
            'src_walk_to' => '',
            'src_money_from' => '',
            'src_money_to' => '',
            'src_madori' => '',
            'src_house_area_from' => '',
            'src_house_area_to' => '',
            'src_land_area_from' => '',
            'src_land_area_to' => '',
            'src_gr' => '',
            'src_moto' => '',
            'src_owner' => '',
            'src_b_from' => '',
            'src_b_to' => '',
            'src_l' => $id,
            'src_kyaku' => '',
            'src_advertise' => '',
            'src_saki' => '',
            'src_tt' => '',
            'src_view' => '',
            'src_b_num' => '',
            'src_realtor_info_ex' => '',
            'src_rimawari_from' => '',
            'src_rimawari_to' => '',
            'src_timelimit_end' => '',
            'src_open' => '',
            'src_own' => '',
            'src_toushi_ready' => '',
            'src_toushi_on' => '',
            'src_rakuzuke_bukken' => '',
            'src_bname' => '',
            'src_tl_date' => '',
            'src_tl_date_type' => 1,
            'src_status' => '',
            'src_keisai' => '',
            'src_photo' => '',
            'up_timelimit_date' => '',
            'up_status' => '',
            'up_keisai' => '',
            'up_recommend_level' => 0,
        ];

        $response = $this->requestWithData($url, http_build_query($data), true, array('Accept: application/form-data'));

        $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
        $patten = '/<input.*?id="chk_bukken_0".*?value="(?<name>.*?)".*?>/';
        preg_match($patten, $response, $match);
        $portalId = $match[1] ?? null;
        logHomes('-- -- -- Portal id: ' . ($portalId ?? 'null') . '.');
        logHomes('-- -- Get portal id: End.');

        return $portalId;
    }

    function uploadImage($url, &$POST_DATA, $article)
    {
        $data = [];

        foreach ($POST_DATA as $key => $value) {
            if ($POST_DATA[$key] != "") {
                if($key != 'b1'){
                    $data[$key] = $value;
                }
            }
        }

        if($article->homes_no == null){
            $data['b1'] = $article->homes_no;
        }else{
            $data['b'] = $article->homes_no;
        }

        $data["tab"] = "img";
        $data["action"] = "ajaxdata_photoupload";
        $data["bt"] = "1101";
        $count = 0;

        $files = [];
        $listImages = $article->relationPortalPhotos()->type(config('const.HOMES'))->del(0)->limit(30)->get();
        $arrProperty = [2, 1, 11, 5, 13, 14, 12, 15, 16, 17, 18, 19, 10, 20, 21, 22, 9, 3, 4, 23, 24, 25];

        foreach ($listImages as $j => $image) {
            $imagePath = storage_path() . "/app/" . $image->file_path;
            //            if (strpos($imagePath, ".JPG") === false && strpos($imagePath, ".jpg") === false) {
            //                continue;
            //            }
            $imageName = explode("/", $imagePath);

            $file = [
                "name" => "pht_photo[$j]",
                "index" => $j,
                "filename" => array_last($imageName),
                "type" => "image/jpeg",
                "content" => file_get_contents($imagePath),
            ];
            array_push($files, $file);

            $count++;
            $num_arrProperty = selectedPhotoPropertyHomes($image->facility, $image->property_sub, $article->property, $image->type_upload, $image->mansion) - 1;
            if ($num_arrProperty < 22) {
                $POST_DATA["photo_type{$count}"] = $arrProperty[$num_arrProperty];
            } else {
                $POST_DATA["photo_type{$count}"] = '';
            }
            $POST_DATA["photo_comment{$count}"] = $image->memo;
        }

        for ($i = 1; $i < 31; $i++) {
            $data['photo_type' . $i] = $POST_DATA['photo_type' . $i];
        }

        $boundary = uniqid();
        $delimiter = '----' . $boundary;
        $dataUpload = '';

        foreach ($data as $key => $value) {
            $dataUpload .= "--" . $delimiter . "\r\n"
                . 'Content-Disposition: form-data; name="' . $key . "\"\r\n\r\n"
                . $value . "\r\n";
        }

        foreach ($files as $content) {
            $dataUpload .= "--" . $delimiter . "\r\n"
                . 'Content-Disposition: form-data; name="' . $content["name"] . '"; filename="' . $content["filename"] . '"' . "\r\n"
                . 'Content-Type: ' . $content["type"] . "\r\n\r\n"
                . $content["content"] . "\r\n";
        }

        $dataUpload .= "--" . $delimiter . "--\r\n";

        $response = $this->requestPostBinary($url, $dataUpload, $delimiter);

        $patten = '/"status":(?<status>.*?),"type":(?<type>.*?),"b2":(?<b2>.*?),"b2time":(?<b2time>.*?),/s';

        preg_match($patten, $response, $match);

        return $match;
    }

    function deleteImage($url, &$POST_DATA, $article, $photo_id){
        $data = [];

        foreach ($POST_DATA as $key => $value) {
            if ($POST_DATA[$key] != "") {
                if($key != 'b1'){
                    $data[$key] = $value;
                }
            }
        }

        $data['b'] = $article->homes_no;
        $data["tab"] = "img";
        $data["pht_photo_delid"] = $photo_id;
        $data["action"] = "ajaxdata_photodelete";
        $data["bt"] = "1101";
        $count = 0;

        $boundary = uniqid();
        $delimiter = '----' . $boundary;
        $dataUpload = '';

        foreach ($data as $key => $value) {
            $dataUpload .= "--" . $delimiter . "\r\n"
                . 'Content-Disposition: form-data; name="' . $key . "\"\r\n\r\n"
                . $value . "\r\n";
        }


        $dataUpload .= "--" . $delimiter . "--\r\n";

        $response = $this->requestPostBinary($url, $dataUpload, $delimiter);

        $patten = '/"status":(?<status>.*?),"type":(?<type>.*?),"b2":(?<b2>.*?),"b2time":(?<b2time>.*?),/s';

        preg_match($patten, $response, $match);

        return $match;
    }

    private function requestPostBinary($url, $data, $delimiter)
    {
        logHomes('-- -- -- Upload image: Start post binary.');
        $curl = curl_init($url);

        curl_setopt_array($curl, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: multipart/form-data; boundary=' . $delimiter,
                'Content-Length: ' . strlen($data),
                'Referer: https://manager.homes.co.jp/index.php?action=sale_reg_form',
                'Origin: https://manager.homes.co.jp',
                'User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Mobile Safari/537.36',
            ],
            CURLOPT_POSTFIELDS => $data
        ]);

        curl_setopt_array($curl, $this->option);

        $response = curl_exec($curl);
        if ($response === false) {
            $err = curl_error($curl);
            curl_close($curl);
            logHomes("-- -- -- -- Post binary failed: $err.");
            logHomes('-- -- -- Upload image: End post binary.');
            die("error $err");
        }

        curl_close($curl);
        logHomes("-- -- -- -- Post binary success.");
        logHomes('-- -- -- Upload image: End post binary.');
        return $response;
    }

    private function mergeAddress($article,  &$POST_DATA)
    {
        $num = $POST_DATA['temporary_addr1'];

        if ($article->mansion_id != null) {
            $city = $article->getMansion()->city;
            $town = $article->getMansion()->town;
            $address4 = $article->getMansion()->address4;
        } else {
            $city = $article->city;
            $town = $article->town;
            $address4 = $article->address4;
        }
        $addresses = MstAddressPortal::where('type', 1)->where('pref_id', $num)->where('area_name', $city->name);
        if ($addresses->count() == 0) {
            //$addresses = [];
            $addresses = MstAddressPortal::where('type', 1)->where('pref_id', $POST_DATA['addr1'])->where('area_name', $city->name)->get();
        } else {
            $addresses = $addresses->get();
        }

        $dataCity = $this->mergeCity($addresses, $city, $town, $POST_DATA);

        if (is_null($dataCity)) return;

        $this->mergeTown($addresses, $town, $POST_DATA, $address4);
    }

    private function mergeTown($cityInHomes, $town, &$POST_DATA, $address4)
    {
        $townName = $town->name;
        /*$townsInHome = array_filter($cityInHomes["city"]->children, function ($townHome) use ($townName) {
            return strpos($townName, $townHome->name) !== false;
        });*/
        $townsInHome = [];
        foreach ($cityInHomes as $townHome) {
            if (strpos($townName, $townHome->town_name) !== false) {
                $townsInHome[] = $townHome;
            }
        }

        $address4 = str_replace('　', '', $address4);
        $address4 = str_replace(' ', '', $address4);
        if (str_contains($address4, '丁目')){
            $explodes = explode('丁目', $address4);
            $POST_DATA['addr3_addr4_name'] = $explodes[1] ?? '';
        }

        if (count($townsInHome) > 0) {
            $POST_DATA["addr4"] = $townsInHome[0]->town_more_id;
            foreach ($townsInHome as $townHome) {
                $POST_DATA["addr3"] = $townHome->town_id;
                $more_text_town = str_replace($townHome->town_name, '', $townName);

                if (!empty($more_text_town)) {
                    $numberInTown = $this->getNumberInAddress($townName);
                    if ($numberInTown != -1) {
                        $more_text_town = str_replace(
                            $this->textNumber[$numberInTown],
                            $this->textNumberjp[$numberInTown],
                            $more_text_town
                        );
                    }
                    if (strpos($more_text_town, $townHome->town_more_name) !== false) {
                        $POST_DATA["addr4"] = $townHome->town_more_id;
                        break;
                    }
                }

                $more_text_addr4 = $address4;
                if (str_contains($more_text_addr4, '丁目')){
                    $explodes = explode('丁目', $more_text_addr4);
                    $more_text_addr4 = $explodes[0] ?? $more_text_addr4;
                    $more_text_addr4 = $this->numberConverter[$more_text_addr4] ?? $more_text_addr4;
                    $more_text_addr4 = $this->textJpToNumber[$more_text_addr4] ?? $more_text_addr4;
                    $more_text_addr4 .= '丁目';
                }
                if (strpos($more_text_addr4, $townHome->town_more_name) !== false) {
                    $POST_DATA["addr4"] = $townHome->town_more_id;
                    break;
                }
            }
        }
    }

    private function mergeCity($addresses, $city, $town, &$POST_DATA)
    {
        foreach ($addresses as $area) {
            if ($area->area_name == $city->name) {
                $cityInHomes = $area;
                break;
            }
        }
        $haveNotAddressInHome = $cityInHomes->count() <= 0;

        if ($haveNotAddressInHome) {
            return null;
        }

        $isSameName = $cityInHomes->area_name == $city->name;
        if ($isSameName) {
            $POST_DATA["addr2"] = $cityInHomes->area_id;
            return [
                "city" => $cityInHomes,
                "more_text" => ""
            ];
        }
        $cityInHomess = [];
        foreach ($addresses as $area) {
            if (strpos($area->area_name, $city->name) !== false) {
                $cityInHomess[] = $area;
            }
        }

        foreach ($cityInHomess as $cityInHome) {
            $dataDetect = $this->detectCurrentCityWithTown($cityInHome->area_name, $city->name, $town->name);
            if ($dataDetect === false) continue;

            $isCorrectCity = $dataDetect["position"] !== false;

            if ($isCorrectCity) {
                $POST_DATA["addr2"] = $cityInHome->area_id;
                return [
                    "city" => $cityInHome,
                    "more_text" => $dataDetect["more_text"]
                ];
            }
        }

        return null;
    }
    private function detectCurrentCityWithTown($cityHomesName, $cityMicName, $townName)
    {
        $moreTextInCity = explode($cityMicName, $cityHomesName);
        if (count($moreTextInCity) <= 0 || ($moreTextInCity[0] == '' && $moreTextInCity[1] == '')) {
            return false;
        }

        $moreTextInCity = $moreTextInCity[1];
        return [
            "position" => strpos($townName, $moreTextInCity),
            "more_text" => $moreTextInCity
        ];
    }
    private function getNumberInAddress($address)
    {
        foreach ($this->textNumber as $index => $text) {
            if ($index == 0) continue;

            $indexTextInAddress = strpos($address, $text);
            if ($indexTextInAddress === false || $indexTextInAddress === 0) {
                continue;
            }

            return $index;
        }

        return -1;
    }

    private function panoramaOpen($panoramaHomesId)
    {
        $url = 'https://manager.homes.co.jp/index.php?action=panorama_open&tk=1';

        if (!empty($panoramaHomesId)) {
            $params = explode('_', $panoramaHomesId);
            $url = "https://manager.homes.co.jp/index.php?action=panorama_open&tk=1&tour_member_id=$params[1]&tour_link_id=$params[2]";
        }
        return $this->requestWithData($url, [], false, [], true);
    }

    private function uploadSphericalPhoto($csrfToken, $listImages)
    {
        $url = 'https://sso.theta360.biz/ja/console/tours/upload_spherical_photo';
        $scene = [];
        $spheres = [];
        $paranomaTitle = config('const.PANORAMA_TITLE');
        foreach ($listImages as $key => $image) {
            $data = [];
            $title = $paranomaTitle[$image->title - 1];
            $imagePath = storage_path() . "/app/" . $image->file_path;
            $data["file"] = new \CURLFile($imagePath, "image/jpeg");

            $response = $this->requestWithData($url, $data, true, [
                'X-Requested-With: XMLHttpRequest',
                "X-CSRF-Token: $csrfToken"
            ]);
            preg_match("/{(.*)/", $response, $matches);
            $sphericalPhoto = (array)json_decode($matches[0]);
            $itemScene = [
                "name" => "scene0" . $key . "_00_" . $sphericalPhoto['sphere_id'],
                "title" => $title,
                "thumburl" => $sphericalPhoto['thumbnail_source'],
                "toursphereurl" => $sphericalPhoto['toursphere_url'],
                "onstart" => "settelop(,-0);activatespot(spot00_17JTyF,undefined);setbottomurl();",
                "preview" => [
                    "type" => "SPHERE",
                    "url" => $sphericalPhoto['thumbnail_source'],
                ],
                "image" => [
                    "sphere" => [
                        "url" => $sphericalPhoto['equirectangular_source'],
                    ],
                ],
                "hotspot" => [
                    [
                        "name" => "bottom",
                        "style" => "cover_tripod_logo",
                    ],
                ],
                "view" => [
                    "hlookat" => "0.0",
                    "vlookat" => "0.0",
                    "fov_m" => "52.0",
                ],
            ];

            array_push($scene, $itemScene);

            $itemSpheres = [
                "id" => $sphericalPhoto['sphere_id'],
                "title" => $title,
                "used" => "true",
            ];
            array_push($spheres, $itemSpheres);
        }


        $tourParam =  [
            "krpano" => [
                "version" => "1.18",
                "title" => "",
                "onstart" => "startup();",
                "include" => [
                    ["url" => "https://theta-biz-statics.s3-ap-northeast-1.amazonaws.com/tour/skin/vtourskin.xml",],
                    ["url" => "https://theta-biz-statics.s3-ap-northeast-1.amazonaws.com/tour/plugins/tooltips.xml",],
                ],
                "layer" => [
                    [
                        "name" => "anno_cover",
                        "type" => "container",
                        "style" => "annotation_cover_style",
                    ],
                ],
                "corner_banner" => [],
                "scene" => $scene,
            ],
            "spheres" => $spheres,
            "metadata" => [
                "custom_key" => "",
                "note" => "",
            ],
            "published" => "true",
        ];
        return json_encode($tourParam);
    }

    private function createOrUpdatePanorama($signature, $csrfToken, $tourParam)
    {
        $url = "https://sso.theta360.biz/ja/console/tours/new";

        $data['authenticity_token'] = $csrfToken;
        $data['tour_param'] = $tourParam;
        $data['tour_title_param'] = '';
        $data['tour_custom_key_param'] = '';
        $data['tour_note_param'] = '';
        $data['tour_published_param'] = 'true';
        $data['tourdraft_update_at_param'] = '';
        $data['tour_update_at_param'] = '';
        $data['reedit_param'] = '';
        $data['tripod_player_setting'] = 'プレイヤー設定に従う (三脚消ししない)';

        $headers = ["Referer: https://sso.theta360.biz/ja/console/tours/new?signature=$signature"];

        $this->requestWithData($url, $data, true, $headers);
        return $this->panoramaList();
    }

    private function panoramaList()
    {
        $url = 'https://manager.homes.co.jp/index.php?action=sale_panorama_list&tk=1';
        $response = $this->requestWithData($url, []);
        preg_match('/<input type="checkbox" name="panorama_uid\[]" value="(.+?)" class="chkCell">/', $response, $matches);
        $panoramaId = $matches[1];
        return $panoramaId;
    }

    private function deletePanorama($panoramaUid)
    {
        $url = 'https://manager.homes.co.jp/index.php';
        $data['tk'] = '1';
        $data['action'] = 'sale_panorama_delete';
        $data['action_type'] = 'delete';
        $data['panorama_uid'] = $panoramaUid;

        $this->requestWithData($url, $data, true);
    }

    private function uploadPanorama($article)
    {
        $listImages = $article->portalHomesPanoramas()->type(config('const.PANORAMA_TYPE_IMAGE'))->del(0)->limit(16)->get();

        if (!$listImages->isEmpty()) {

            $panoramaHomesId = $article->panorama_homes;
            $response = $this->panoramaOpen($panoramaHomesId);
            preg_match("/signature=(.*)/", $response, $signatureMatches);
            $signature = $signatureMatches[1];

            preg_match('/<meta name="csrf-token" content="(.+?)" \/>/', $response, $matches);
            $csrfToken = $matches[1];

            $tourParam = $this->uploadSphericalPhoto($csrfToken, $listImages);

            $panoramaId = $this->createOrUpdatePanorama($signature, $csrfToken, $tourParam);

            if (empty($panoramaHomesId)) {
                //Article::find($article->id)->update(['panorama_homes' => $panoramaId]);
                PortalStatusArticle::where('article_id', $article->building_id)->where('portal_id', $article->homes_no)->update(['panorama_homes' => $panoramaId]);
            }
            return !empty($panoramaHomesId) ? $panoramaHomesId : $panoramaId;
        } else {
            $panoramaUid = $article->panorama_homes;
            if (!empty($panoramaUid)) {
                $this->deletePanorama($panoramaUid);
                PortalStatusArticle::where('article_id', $article->building_id)->where('portal_id', $article->homes_no)->update(['panorama_homes' => null]);
            }
            return '';
        }
    }

    private function getArticleHomes($url, $b1)
    {
        $url = $url . $b1;
        $response = $this->requestWithData($url, [], false);
        $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
        $this->log($response);
        $input = $this->parseDataInMainForm($response, 'input');
        $textarea = $this->parseDataInMainForm($response, 'textarea');
        $hidden = $this->parseDataInMainForm($response, 'hidden');
        $radio = $this->parseDataInMainForm($response, 'radio');
        $checkbox = $this->parseDataInMainForm($response, 'checkbox');
        $select = $this->parseDataInMainForm($response, 'select');
        $selectUnChecked = $this->parseDataInMainForm($response, 'selectuncheck');
        $radioUnChecked = $this->parseDataInMainForm($response, 'radiounchecked');
        $checkboxUnChecked = $this->parseDataInMainForm($response, 'checkboxuncheck');
        return array_merge($input, $textarea, $hidden, $radioUnChecked, $radio, $checkboxUnChecked, $checkbox, $selectUnChecked, $select);
    }

    private function parseDataInMainForm($response, $type)
    {
        $formPattern = '/<form.*?id="form_reg".*?>(.*?)<\/form>/s';
        preg_match($formPattern, $response, $formMatches);

        if (count($formMatches) < 2) return [];

        switch ($type) {
            case 'input':
                $pattern = '/<input.*?type="text".*?name="(?<name>.*?)".*?value="(?<value>.*?)".*?>/';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
                break;
            case 'textarea':
                $pattern = '/<textarea.*?name="(?<name>.*?)".*?>(?<value>.*?)<\/textarea>/';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
                break;
            case 'hidden':
                $pattern = '/<input.*?type="hidden".*?name="(?<name>.*?)".*?value="(?<value>.*?)".*?>/';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
                $pattern1 = '/<input.*?name="(?<name>.*?)" id="(.*)" type="hidden".*?.*?value="(?<value>.*?)".*?>/';
                preg_match_all($pattern1, $formMatches[0], $matches2, PREG_SET_ORDER);
                $matches = array_merge($matches, $matches2);
                break;
            case 'radio':
                $pattern = '/<input.*?type="radio".*?name="(?<name>.*?)".*?value="(?<value>.*?)".*?checked="checked">/';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
                $pattern2 = '/<input.*?name="(?<name>.*?)".*?value="(?<value>.*?)".*?checked.*?>/';
                preg_match_all($pattern2, $formMatches[0], $matches2, PREG_SET_ORDER);
                $matches = array_merge($matches, $matches2);
                break;
            case 'radiounchecked':
                $pattern = '<input.*?type="radio".*?name="(?<name>.*?)".*?value=".*?".*?>';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
                break;
            case 'checkbox':
                $pattern = '/<input.*?name="(?<name>.*?)".*?type="checkbox".*?value="(?<value>.*?)".*?checked.*?>/';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
                $pattern = '/<input.*?type="checkbox".*?name="(?<name>.*?)".*?value="(?<value>.*?)".*?checked="checked".*?>/';
                preg_match_all($pattern, $formMatches[0], $matches1, PREG_SET_ORDER);
                $matches = array_merge($matches, $matches1);
                break;
            case 'checkboxuncheck':
                $pattern = '/<input.*?type="checkbox".*?name="(?<name>.*?)".*?value=".*?".*?>/';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
                break;
            case 'selectuncheck':
                $pattern = '/<input.*?name="(?<name>.*?)".*?type="checkbox".*?.*?>/';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
                break;
            case 'select':
                $matches = $this->parseSelectInMainForm($formMatches);
                break;
        }

        if (!isset($matches)) return [];

        return collect($matches)
            ->pluck('value', 'name')
            ->toArray();
    }

    private function parseSelectInMainForm($formMatches)
    {
        $patternSelecte = '/<select.*?name="(?<name>.*?)".*?>([\S\s]*?)<\/select>/';

        preg_match_all($patternSelecte, $formMatches[0], $selectMatches, PREG_SET_ORDER);
        $patternOption = '/<option.*?value="(?<value>.*?)".*?selected.*?>/';
        foreach ($selectMatches as $key => $value) {
            preg_match_all($patternOption, $value[0], $optionMatches, PREG_SET_ORDER);
            if (isset($optionMatches[0])) {
                $selectMatches[$key]['value'] =  $optionMatches[0]['value'];
            } else {
                unset($selectMatches[$key]);
            }
        }
        return $selectMatches;
    }

    private function setDataFromHomes(&$POST_DATA, $article)
    {
        if (in_array($article->property, [1, 2, 3])) {
            // Remove flg_bukken_name
            $fields = [
                'b_ruby', 'flg_open', 'flg_addr_hidden', 'flg_adjust', 'money_kyoueki_tax', 'commision_ck', 'commisionunit',
                'ft202',
                'convenience_distance', 'super_distance', 'shopping_street_distance', 'drugstore_distance', 'hospital_distance', 'park_distance', 'bank_distance', 'est_other_ck',
                'url_kind', 'url', 'baikai_keiyaku_date_y', 'baikai_keiyaku_date_m', 'baikai_keiyaku_date_d', 'moto_post1',
                'moto_post2', 'moto_addr1', 'moto_addr2', 'moto_addr3', 'moto_addr4', 'moto_addr3_name', 'land_mochibun_b', 'land_mochibun_a',
                'land_chisei', 'land_road_cond', 'std_ichishitei1', 'std_ichishitei2', 'std_ichishitei3', 'std_ichishitei4', 'std_angle4',
                'std_width4', 'std_kind4', 'std_maguchi4', 'land_youseki_ck', 'land_youseki_etc', 'land_kokudohou'
            ];
        } elseif (in_array($article->property, [4, 5])) {
            // Remove flg_bukken_name
            $fields = [
                'b_ruby', 'flg_open', 'flg_addr_hidden', 'flg_adjust', 'money_tax', 'money_kyoueki_tax', 'commision_ck', 'commisionunit', 'empty_number', 'sekou_company_name',
                'mdr_kind1', 'mdr_tatami1', 'mdr_floor1', 'mdr_numberof1',
                'mdr_kind2', 'mdr_tatami2', 'mdr_floor2', 'mdr_numberof2',
                'mdr_kind3', 'mdr_tatami3', 'mdr_floor3', 'mdr_numberof3',
                'mdr_kind4', 'mdr_tatami4', 'mdr_floor4', 'mdr_numberof4',
                'mdr_kind5', 'mdr_tatami5', 'mdr_floor5', 'mdr_numberof5',
                'mdr_kind6', 'mdr_tatami6', 'mdr_floor6', 'mdr_numberof6',
                'mdr_kind7', 'mdr_tatami7', 'mdr_floor7', 'mdr_numberof7',
                'mdr_kind8', 'mdr_tatami8', 'mdr_floor8', 'mdr_numberof8',
                'mdr_kind9', 'mdr_tatami9', 'mdr_floor9', 'mdr_numberof9',
                'mdr_kind10', 'mdr_tatami10', 'mdr_floor10', 'mdr_numberof10',
                'ft241', 'ft239', 'ft247', 'ft273', 'ft248', 'ft249', 'ft250',
                'ft283', 'ft276', 'ft284', 'ft278', 'ft282', 'ft240', 'ft279', 'ft285', 'ft287', 'ft286', 'ft288',
                'ft289', 'ft290', 'ft291', 'ft293', 'ft292', 'ft218', 'ft213', 'ft210', 'ft228', 'ft237', 'ft256', 'ft274', 'ft296', 'ft297',
                'ft203', 'ft204', 'ft212', 'ft257', 'ft211', 'ft258', 'ft242', 'ft246', 'ft259', 'ft275', 'ft295',
                'ft207', 'ft208', 'ft209', 'ft245', 'ft260', 'ft261', 'ft268', 'ft215', 'ft269', 'ft270', 'ft216', 'ft271',
                'ft238', 'ft234', 'ft219', 'ft221', 'ft220', 'ft222', 'ft227', 'ft226', 'ft225',
                'parking_money_tax', 'parking_distance', 'ft294',
                'convenience_distance', 'super_distance', 'shopping_street_distance', 'drugstore_distance', 'hospital_distance', 'park_distance', 'bank_distance', 'est_other_ck',
                'url_kind', 'url', 'baikai_keiyaku_date_y', 'baikai_keiyaku_date_m', 'baikai_keiyaku_date_d', 'moto_post1',
                'moto_post2', 'moto_addr1', 'moto_addr2', 'moto_addr3', 'moto_addr4', 'moto_addr3_name', 'land_mochibun_b', 'land_mochibun_a',
                'land_road_cond', 'std_ichishitei1', 'std_ichishitei2', 'std_ichishitei3', 'std_ichishitei4', 'std_angle4',
                'std_width4', 'std_kind4', 'std_maguchi4', 'land_youseki_ck', 'land_youseki_etc', 'land_chisei'
            ];
        } else {
            //REMOVE DEFAULT VALUE 'house_kanri_keitai' kyakuzuke_simple, flg_bukken_name
            $fields = [
                'b_ruby', 'flg_open', 'flg_addr_hidden', 'flg_adjust', 'money_kyoueki_tax', 'money_shuuzen', 'money_shuuzenkikin_ck',
                'commision_ck', 'commisionunit', 'empty_number', 'house_kanri_kumiai',
                'mdr_kind1', 'mdr_tatami1', 'mdr_floor1', 'mdr_numberof1',
                'mdr_kind2', 'mdr_tatami2', 'mdr_floor2', 'mdr_numberof2',
                'mdr_kind3', 'mdr_tatami3', 'mdr_floor3', 'mdr_numberof3',
                'mdr_kind4', 'mdr_tatami4', 'mdr_floor4', 'mdr_numberof4',
                'mdr_kind5', 'mdr_tatami5', 'mdr_floor5', 'mdr_numberof5',
                'mdr_kind6', 'mdr_tatami6', 'mdr_floor6', 'mdr_numberof6',
                'mdr_kind7', 'mdr_tatami7', 'mdr_floor7', 'mdr_numberof7',
                'mdr_kind8', 'mdr_tatami8', 'mdr_floor8', 'mdr_numberof8',
                'mdr_kind9', 'mdr_tatami9', 'mdr_floor9', 'mdr_numberof9',
                'mdr_kind10', 'mdr_tatami10', 'mdr_floor10', 'mdr_numberof10',
                'ft202', 'ft233', 'ft243', 'ft241', 'ft272', 'ft273', 'ft247', 'ft248', 'ft249', 'ft250',
                'ft283', 'ft276', 'ft284', 'ft278', 'ft282', 'ft240', 'ft279', 'ft287', 'ft288',
                'ft289', 'ft290', 'ft291', 'ft293', 'ft254', 'ft218', 'ft213', 'ft210', 'ft228', 'ft237', 'ft256', 'ft274', 'ft296', 'ft297',
                'ft203', 'ft204', 'ft206', 'ft205', 'ft212', 'ft257', 'ft211', 'ft258', 'ft242', 'ft246', 'ft259', 'ft275', 'ft295',
                'ft207', 'ft208', 'ft209', 'ft245', 'ft229', 'ft260', 'ft261', 'ft268', 'ft215', 'ft214', 'ft269', 'ft216', 'ft270', 'ft271',
                'ft238', 'ft262', 'ft267', 'ft234', 'ft219', 'ft221', 'ft220', 'ft222', 'ft231', 'ft232', 'ft236', 'ft226', 'ft217',
                'parking_money_tax', 'parking_distance', 'ft294',
                'convenience_distance', 'super_distance', 'shopping_street_distance', 'drugstore_distance', 'hospital_distance', 'park_distance', 'bank_distance', 'est_other_ck',
                'url_kind', 'url', 'seller_interview_q1', 'seller_interview_q2',
                'baikai_keiyaku_date_y', 'baikai_keiyaku_date_m', 'baikai_keiyaku_date_d', 'moto_post1',
                'moto_addr1', 'moto_addr2', 'moto_addr3', 'moto_addr4', 'moto_addr3_name', 'land_chisei', 'land_kokudohou'
            ];
        }

        $data = $this->getArticleHomes("https://manager.homes.co.jp/index.php?action=sale_reg_form&b=", $POST_DATA['b1']);

        foreach ($fields as $field) {
            $POST_DATA[$field] = $data[$field] ?? '';
            if (isset($data['flg_addr_hidden']) && $field == 'flg_addr_hidden' && $data['flg_addr_hidden'] == 1) {
                $POST_DATA['display_addr_name'] = $article->address;
            }
            if (isset($data['kyakuzuke_simple']) && $field == 'kyakuzuke_simple' && $data['kyakuzuke_simple'] == 0) {
                $POST_DATA['kyakuzuke'] = 0;
            }
            if ($field == 'land_chisei') {
                if ($article->land_condition1 == 1) {
                    $POST_DATA['land_chisei'] = 5;
                }
            }
        }
    }
    private function SaleInquiryList()
    {
        $url = 'https://manager.homes.co.jp/index.php?action=sale_inquiry_reply';
        $data = [
            'action'    =>  'sale_inquiry_list',
            'reply_action'  =>  'https://manager.homes.co.jp/index.php?action=sale_inquiry_reply',
            'rows_offset'       =>  0,
            'list_rows' =>  20,
            'flg_search'    =>  1,
            'caller'        =>  'list',
            'searchYearFrom'    =>  2021,
            'searchMonthFrom'   =>  '08',
            'searchYearTo'      =>  2021,
            'searchMonthTo'     =>  '11',
            'timestampYear'     =>  2021,
            'timestampMonth'    =>  '11',
            'searchYMFrom'      =>  '202108',
            'searchDayFrom'     =>  '01',
            'searchYMTo'        =>  '202111',
            'searchDayTo'       =>  '05',
            'timestampDay'      =>  '05',
            'display_visit_reserve' =>  0

        ];
        $response = $this->requestWithData($url, $data, true);
        $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
        $this->log($response);
        die('done');
    }
    private function checkId($article)
    {
        $data = $this->getArticleHomes("https://manager.homes.co.jp/index.php?action=sale_reg_form&b1=", $article->homes_no);
        if (empty($data)) {
            $article->homes_no = null;
            $article->save();
        }
    }

    private function getStationPortal($line_name, $station_name){
//        $maps = [
//            'JR神戸線' => 'JR東海道・山陽本線',
//            'JR京都線' => 'JR東海道・山陽本線',
//            '神戸電鉄神戸高速線' => '神戸高速南北線'
//        ];
//        $line_name = $maps[$line_name] ?? $line_name;
//
//        $mainTrafficLine = str_replace("JR", "ＪＲ", $line_name);
//        $stationNames = [ $station_name, str_replace("駅", "", $station_name) ];
//        $searchLine = MstStationPortal::where('type', 1)
//            ->where('line_name', $mainTrafficLine)
//            ->whereIn('station_name', $stationNames)
//            ->orderByRaw('FIELD(station_name, '.'"'.implode('", "', $stationNames).'")');
//
//        if ($searchLine->count() == 0){
//            $searchLine = MstStationPortal::where('type', 1)->where('station_name', $station_name);
//        }
//
//        $line = $searchLine->first();
//        $line->rosen1_name = $line_name;
//        return $line;
        return MstStationPortal::findByNickName($line_name, $station_name, 1);
    }

    private function mergeFeature($article,  &$POST_DATA){
        foreach ($article->features as $feature){
            if (isset($feature->homes_id) && $feature->homes_id !== ''){
                $explodes = explode(',', $feature->homes_id);
                $POST_DATA[$explodes[0]] = $explodes[1] ?? 1;
            }
        }
        if ($article->isRoom && $article->maisonette == 1){
            $POST_DATA['ft272'] = 1;
        }
    }

    //管理人・管理形態変換
    private function setManagementForm($managementForm = null)
    {
        switch ($managementForm) {
            case 1:
                $manager = self::KANRININ_JOUCHU;
                $form = self::KANRIKEITAI_ZENBU_ITAKU;
                break;
            case 2:
                $manager = self::KANRININ_NIKKIN;
                $form = self::KANRIKEITAI_ZENBU_ITAKU;
                break;
            case 3:
                $manager = self::KANRININ_JUNKAI;
                $form = self::KANRIKEITAI_ZENBU_ITAKU;
                break;
            case 4:
            case 6:
                $manager = self::KANRININ_NONE;
                $form = self::KANRIKEITAI_ZENBU_ITAKU;
                break;
            case 5:
            case 15:
            case 16:
                $manager = self::KANRININ_NONE;
                $form = self::KANRIKEITAI_JISHU;
                break;
            case 7:
                $manager = self::KANRININ_NIKKIN;
                $form = self::KANRIKEITAI_ICHIBU_ITAKU;
                break;
            case 8:
                $manager = self::KANRININ_JOUCHU;
                $form = self::KANRIKEITAI_ICHIBU_ITAKU;
                break;
            case 9:
                $manager = self::KANRININ_JUNKAI;
                $form = self::KANRIKEITAI_ICHIBU_ITAKU;
                break;
            case 10:
            case 11:
                $manager = self::KANRININ_NONE;
                $form = self::KANRIKEITAI_ICHIBU_ITAKU;
                break;
            case 12:
                $manager = self::KANRININ_NIKKIN;
                $form = self::KANRIKEITAI_JISHU;
                break;
            case 13:
                $manager = self::KANRININ_JOUCHU;
                $form = self::KANRIKEITAI_JISHU;
                break;
            case 14:
                $manager = self::KANRININ_JUNKAI;
                $form = self::KANRIKEITAI_JISHU;
                break;
            default:
                $manager = '';
                $form = self::KANRIKEITAI_ICHIBU_ITAKU;
        }
        return [
            'manager' => $manager,
            'managementForm' => $form,
        ];
    }
}
