<?php

namespace App\Http\Controllers\Admin;

use App\Console\Commands\Converters\SaiKyotoContructConverter;
use App\Console\Commands\Uploads\SuumoUpload;
use App\Http\Controllers\Admin\Ajax\AjaxController;
use App\Models\RelationPortalFacility;
use App\Models\RelationPortalPhoto;
use App\Models\RelationPortalStatusPublic;
use App\Models\RelationPriceHistory;
use App\Services\CompanyApiService;
use App\Services\ImageService;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Routing\Redirector;
use App\Http\Requests\ArticlePost;
use App\Http\Requests\LandPost;
use App\Http\Requests\HousePost;
use App\Http\Requests\MansionPost;
use App\Http\Requests\RoomPost;
use App\Http\Requests\LotPost;
use App\Models\Article;
use App\Models\Facility;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\CustomContent;
use App\Models\MstPropertyType;
use App\Models\MstPropertyTypeSub;
use App\Models\MstStatus;
use App\Models\MstPrefecture;
use App\Models\MstCity;
use App\Models\MstTown;
use App\Models\MstSchool;
use App\Models\MstStation;
use App\Models\MstLawrestriction;
use App\Models\MstOtherrestriction;
use App\Models\RelationCitySchool;
use App\Models\MstStore;
use App\Models\MstFloorType;
use App\Models\MstGenkyou;
use App\Models\MstParking;
use App\Models\MstStructure;
use App\Models\MstStructureSub;
use App\Models\MstManner;
use App\Models\MstVendorManner;
use App\Models\MstFacilityType;
use App\Models\MstUseArea;
use App\Models\MstUseDistrict;
use App\Models\MstManagementForm;
use App\Models\MstShared;
use App\Models\MstOtherReason;
use App\Models\RelationVendorArticle;
use App\Models\RelationSpring;
use App\Models\RelationInterior;
use App\Models\RelationExterior;
use App\Models\RelationShared;
use App\Models\RelationLawrestriction;
use App\Models\RelationOtherrestriction;
use App\Models\RelationEventDay;
use App\Models\RelationArticlePhoto;
use App\Models\RelationCustomContent;
use App\Models\RelationArticleFacility;
use App\Models\TempImage;
use App\Models\History;
use App\Models\Vendor;
use Artisan;
use App\Models\Sai\Article as ArticleForSaiKyoto;
use App\Models\Sai\Search as SearchForSaiKyoto;
use App\Models\Sai\Contruct as ContructForSaiKyoto;
use App\Console\Commands\Converters\SaiKyotoArticleConverter;
use Illuminate\Support\Facades\Cookie;

use GuzzleHttp\Psr7;

class ArticleController extends Controller
{
    private $parentProperty;

    public function show_500()
    {
        return view('errors.500');
    }

    public function insertArticleIntoSai($article, $new = true, $mansion = null)
    {
        if ($article->own_company == 2) {
            $closeStatus = [4];
            $isCloseArticle = in_array($article->status, $closeStatus);

            if ($isCloseArticle) {
                if (is_null($mansion)) {
                    $dataForSaiKyoto = SaiKyotoContructConverter::convert($article->toArray());
                } else {
                    $dataForSaiKyoto = SaiKyotoContructConverter::convert($mansion->toArray(), $article->toArray());
                }

                $articleForSaiKyoto = ContructForSaiKyoto::find($article->building_id);

                if ($new) {
                    $articleForSaiKyoto = new ContructForSaiKyoto();
                    $dataForSaiKyoto["c_id"] = self::createBuildingIdOther($article->building_id, true);
                    $articleForSaiKyoto->fill($dataForSaiKyoto)->save();
                    $article->update(['building_id' => $articleForSaiKyoto->c_id]);
                    return;
                }

                if (!empty($articleForSaiKyoto)) {
                    $articleForSaiKyoto->fill($dataForSaiKyoto)->save();
                    $article->update(['sai_id' => $articleForSaiKyoto->c_id]);
                } else {
                    $articleForSaiKyoto = new ContructForSaiKyoto();
                    $dataForSaiKyoto["c_id"] = $article->building_id;
                    $articleForSaiKyoto->fill($dataForSaiKyoto)->save();
                    $article->update(['building_id' => $articleForSaiKyoto->c_id]);
                }
                return;
            }

            $masterData = $this->getMasterData(null, null, null, 3);
            if (is_null($mansion)) {
                $dataForSaiKyoto = SaiKyotoArticleConverter::convert($article->toArray(), $masterData);
            } else {
                $dataForSaiKyoto = SaiKyotoArticleConverter::convert($mansion->toArray(), $masterData,
                    $article->toArray());
            }
            $articleForSaiKyoto = SearchForSaiKyoto::find($article->building_id);
            $createTime = $this->convertDateTime($article->created_at);

            if (in_array($article->property, [1, 2, 3, 4, 5]) || empty($article->property)) {
                $updateTime = $this->convertDateTime($article->conf_day);
            } else {
                $updateTime = $this->convertDateTime($article->updated_at);
            }

            if ($new) {
                $articleForSaiKyoto = new SearchForSaiKyoto();
                $dataForSaiKyoto["OH"] = self::createBuildingIdOther($article->building_id, false);
                $articleForSaiKyoto->fill($dataForSaiKyoto)->save();
                $article->update(['building_id' => $articleForSaiKyoto->OH]);

                $articleForSaiKyoto->update(["OB" => $createTime, "OA" => $updateTime]);
                return;
            }

            if (!empty($articleForSaiKyoto)) {
                $articleForSaiKyoto->fill($dataForSaiKyoto)->save();
                $article->update(['sai_id' => $articleForSaiKyoto->OH]);

                $articleForSaiKyoto->update(["OB" => $createTime, "OA" => $updateTime]);
            } else {
                $articleForSaiKyoto = new SearchForSaiKyoto();
                $dataForSaiKyoto["OH"] = $article->building_id;
                $articleForSaiKyoto->fill($dataForSaiKyoto)->save();
                $article->update(['building_id' => $articleForSaiKyoto->OH]);

                $articleForSaiKyoto->update(["OB" => $createTime, "OA" => $updateTime]);
            }
        }
    }

    private function createBuildingIdOther($buildingId, $isContruct = false)
    {
        if ($isContruct) {
            $existsBuildingId = ContructForSaiKyoto::where("c_id", $buildingId)->exists();
        } else {
            $existsBuildingId = SearchForSaiKyoto::where("OH", $buildingId)->exists();
        }

        if ($existsBuildingId) {
            $this->createBuildingIdOther($buildingId++);
        }

        return $buildingId;
    }

    private function convertDateTime($date)
    {
        if (empty($date)) return "";
        $time = Carbon::parse($date);
        $month = strlen($time->month) == 1 ? " {$time->month}" : $time->month;
        $day = strlen($time->day) == 1 ? " {$time->day}" : $time->day;

        return "{$time->year}/{$month}/{$day}";
    }

    private function createOriginal($article, $request)
    {
        $article->customs()->delete();

        $originals = $request->original;

        $dataCustom = [
            "company_id" => \auth()->user()->company_id,
            "article_id" => $article->building_id,
            "type" => "",
            "code" => "",
            "contents" => "",
            "memo" => ""
        ];

        if (is_array($originals)) {
            foreach ($originals as $code => $original) {
                if (is_array($original)) {
                    foreach ($original as $value) {
                        $dataCustom["type"] = 1;
                        $dataCustom["code"] = $code;
                        $dataCustom["contents"] = $value;
                        $article->customs()->create($dataCustom);
                    }
                } else {
                    $dataCustom["type"] = 1;
                    $dataCustom["code"] = $code;
                    $dataCustom["contents"] = $original ? htmlspecialchars_decode($original) : null;
                    $article->customs()->create($dataCustom);
                }
            }
        }
    }

    private function getDataSaiKyoto($data)
    {
        return $data;

        $data["pref"] = [
            ["code" => 11, "name" => "京都府"],
            ["code" => 12, "name" => "滋賀県"],
        ];
        $data["city"] = [
            ["code" => 100, "name" => "京都市山科区"],
            ["code" => 102, "name" => "京都市伏見区"]
        ];
        $data["town"] = [
            ["code" => 100, "name" => "西野岸ノ下町"],
            ["code" => 101, "name" => "安朱堂ノ後町"],
            ["code" => 102, "name" => "梅林1丁目"],
            ["code" => 103, "name" => "稲葉台"],
            ["code" => 104, "name" => "醍醐僧尊坊町"],
            ["code" => 105, "name" => "安朱馬場ノ東町"],
            ["code" => 106, "name" => "御陵荒巻町"],
            ["code" => 107, "name" => "醍醐古道町"],
            ["code" => 108, "name" => "安朱馬場ノ東町"],
            ["code" => 109, "name" => "音羽山等地"],
            ["code" => 110, "name" => "安朱堂ノ後町"],
            ["code" => 111, "name" => "横木1丁目"],
            ["code" => 112, "name" => "茶戸町"],
            ["code" => 113, "name" => "北花山横田町"],
            ["code" => 114, "name" => "四ノ宮岩久保町"],
            ["code" => 115, "name" => "横木"],
            ["code" => 116, "name" => "安朱堂ノ後町"],
            ["code" => 117, "name" => "四ﾉ宮神田町"]
        ];
        return $data;
    }

    private function getCustomData()
    {
        return CustomContent::whereNotNull("name")->where('company_id', \auth()->user()->company_id)->get();
    }

    /**
     * 仮登録物件一覧画面の表示
     */
    public function showProvisionalForm(Request $request)
    {
        $user = Auth::user();
        $selected = $user->store_id;

        $params = $request->all();

        if (isset($params['store']) && !empty($params['store'])) {
            $store_info = MstStore::getDataByCode($user->company_id, $params['store']);
            if (is_null($store_info)) {
                print('不正なアクセスです。');
                exit;
            }
            $selected = $params['store'];
            $data['uri'] = '?store=' . $params['store'];
        }
        $data = [];
        $article = Article::getProvisionalData(20, $selected);
        foreach ($article as &$row) {
            $mansion = Article::getParentMansion($row->mansion_id);
            $row->mansion_info = $mansion;
            $row->manner_name = '-';
            if ($row->manner != null) {
                $row->manner_name = MstManner::where('code', '=', $row->manner)->first()['name'];
                /*if ($row->manner_name == '専任媒介') {
                    $row->manner_name = '一般媒介';
                }*/
            }
        }

        // 表示中のページの最初のアイテムのインデックス番号
        $first = $article->firstItem();

        // 表示中のページの最後のアイテムのインデックス番号
        $last = $article->lastItem();

        $data['article'] = $article;
        $data['first'] = $first;
        $data['last'] = $last;
        // 店舗一覧

        $data['store'] = MstStore::getDataAll($user->company_id);
        $data['selected_store'] = $selected;
        $data['pager_params'] = ['store' => $selected];

        return view('admin.pages.provisional', $data);
    }

    /**
     * 土地情報ー新規登録画面の表示
     */
    public function showRegistrationLandForm(Request $request)
    {
        $old = $request->session()->all();
        // マスターデータの取得
        $this->parentProperty = 1;
        $data = $this->getMasterData(null, null, $old, 1);
        $data['pref'] = Arr::prepend(($data['pref'] ?? []), ['code' => null, 'name' => '未選択']);
        $user = Auth::user();
        $data['company_id'] = $user->company_id;

        $data["customs"] = $this->getCustomData();

        if ($user->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }
        $data['store_user'] = MstStore::getDataByCode($user->company_id, $user->store_id);

        return view('admin.pages.regist-land', $data);
    }

    /**
     * 土地情報ー新規登録
     */
    public function registerLand(LandPost $request, CompanyApiService $apiService)
    {
        $this->parentProperty = 1;

        $user = Auth::user();
        $building_id = Article::getMaxNo();
        if (empty($building_id)) {
            $building_id = 0;
        }

        // 登録
        $article = new Article;
        $all = $request->all();

        if (!isset($all['reservation'])) {
            $all['reservation'] = 0;
        }
        if (!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if (!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if (!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if (!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if (!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
        }
        if (!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
        }
        if (!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
        }
        if (!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }

        $all['building_id'] = $building_id + 1;
        if ($all['own_company'] == 2) {
            $all['disp'] = 1;
        }
        $all['provisional'] = 0;

        if ($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }

        if ($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        if (isset($all["law_restriction"])) {
            unset($all["law_restriction"]);
        }

        $result = $article->fill($all)->save();

        $history_data = [];
        $history_data['company_id'] = $user->company_id;
        $history_data['article_id'] = $all['building_id'];
        $history_data['price'] = $all["price"];
        $history_data['regist_date'] = date('Y-m-d');
        $history = new RelationPriceHistory;
        $history->fill($history_data)->save();

        if (isset($article->building_id)) {
            // 温泉
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;
            foreach ($vendor_list as $key => $val) {
                if (empty($val)) {
                    continue;
                }

                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                $vendor['home_note'] = $request->home_note[$key];
                if (is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();

                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }
            }

        }
        if ($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->homes == 2) {
            Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->athome == 2) {
            try {
                Artisan::call('batch:athome', ['id' => $article->building_id, 'cid' => $user->company_id]);
            } catch (\Exception $exception) {
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if ($result) {
            $this->createOriginal($article, $request);
            if (\auth()->user()->isOwnerOfSaiKyoto()) {
                self::setPriceCustomContent($article);
                // $this->insertArticleIntoSai($article);
            }
            $data = [];
            $data['action'] = route('showEditLand', ['id' => $article->building_id]);
            $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article->building_id)->first();
            $dataSend['history_data']  = $history_data;
            $dataSend['vendor_list'] = RelationVendorArticle::where('article_id', $article->building_id)->get();
            $dataSend['original'] = $request->original;
            $apiService->registLand($dataSend);

            // 保存して画像編集画面へ
            if ($request->toimage == 1) {
                $URL = url('');
                header('Location: ' . $URL . '/admin/registImage/' . $article->building_id);
                die();
            }
            if ($request->toimageportal == 1) {
                header('Location: ' . route("admin.portal.image", $article->building_id));
                die();
            }

            if ($request->detailportal == 1) {
                header('Location: ' . route("admin.portal.image", $article->building_id).'?detail=1');
                die();
            }

            return view('admin.pages.redirect', $data);
        }
    }


    /**
     * 土地情報ー編集登録画面の表示
     */
    public function showEditLandForm(Request $request)
    {
        $old = $request->session()->all();

        $this->parentProperty = 1;
        $article = $this->getDataById($request->id);
        if (isset($article->sale_no)) {
            $lot = $this->getDataById($article->sale_no);
            $article->sale_name = $lot->article_name;
        } else {
            $article->sale_name = '';
        }

        $article->event_day = $article->events()->select("event_day")->pluck("event_day")->toArray();
        $messArray = [];
        if($article->name == null) {
            $messArray['name_article'] = '物件名は必須項目です。';
        }
        if ($article->shop == null) {
            $messArray['shop'] = '物件取扱店舗名は必須項目です。';
        }
        if ($article->main_traffic_line == null && $article->else_traffic_line == null) {
            $messArray['main_traffic_line'] = '主要交通は必須項目です。';
        }
        if ($article->current_status == 0) {
            $messArray['current_status'] = '現況は必須項目です。';
        }
        if ($article->land_delivery == 0) {
            $messArray['land_delivery'] = '引渡しは必須項目です。';
        }
        if ($article->land_condition == 2) {
            $messArray['land_condition'] = '建築条件は必須項目です。';
        }
        if ($article->ground == 0) {
            $messArray['ground'] = '地目は必須項目です。';
        }
//        if ($article->volume_rate == null) {
//            $messArray['volume_rate'] = '容積率は必須項目です。';
//        }
        if ($article->use_area == null) {
            $messArray['use_area'] = '用途地域は必須項目です。';
        }
        if ($article->classfication == 2 && $article->use_method == 0) {
            $messArray['classfication'] = '区分は必須項目です。';
        }
        if ($article->company_manner == null) {
            $messArray['company_manner'] = '取引態様は必須項目です。';
        }
        if ($article->price === null) {
            $messArray['price'] = '物件価格は必須項目です。';
        }
        if ($article->land_area_val == null) {
            $messArray['land_area_val'] = '土地面積は必須項目です。';
        }
        if ($article->building_rate == '') {
            $messArray['building_rate'] = '建ぺい率は必須項目です。';
        }
        if ($article->volume_rate == '') {
            $messArray['volume_rate'] = '容積率は必須項目です。';
        }

        if ((is_null($article->another_cost1) && !empty($article->another_cost_unit1)) || (!is_null($article->another_cost1) && empty($article->another_cost_unit1))) {
            $messArray['another_cost1'] = 'その他諸費用１を入力してください。';
        }

        if ((is_null($article->another_cost2) && !empty($article->another_cost_unit2)) || (!is_null($article->another_cost2) && empty($article->another_cost_unit2))) {
            $messArray['another_cost2'] = 'その他諸費用２を入力してください。';
        }

        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 1);
        $data['article'] = $article;
        $data['messArray'] = $messArray;
        $data["customs"] = $this->getCustomData();

        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        foreach ($facility as &$row) {
            $row->kind_name = MstFacilityType::find($row->kind)->name ?? '';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;
        $data['saved'] = $request->saved ?? '';
        if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }
        $user = Auth::user();
        $data['store'] = MstStore::getDataByCode($user->company_id, $article->shop);
        $data['store_user'] = MstStore::getDataByCode($user->company_id, $user->store_id);
        $data['public_portal'] = $article->portalPublic();

        return view('admin.pages.edit-land', $data);
    }

    /**
     * 土地情報ー編集登録
     */
    public function editLand(LandPost $request, CompanyApiService $apiService)
    {
        $user = Auth::user();

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();

        if ($article->price != $request->get("price")) {
            $history_data = [];
            $history_data['company_id'] = $user->company_id;
            $history_data['article_id'] = $article->building_id;
            $history_data['price'] = $request->get("price");
            $history_data['regist_date'] = date('Y-m-d');
            $history = new RelationPriceHistory;
            $history->fill($history_data)->save();
        }

        $all = $request->all();
        if (!isset($all['reservation'])) {
            $all['reservation'] = 0;
        }
        if (!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if (!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if (!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if (!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if (!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
        }
        if (!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
        }
        if (!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
        }
        if (!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }

        if ($all['own_company'] == 2) {
            $all['disp'] = 1;
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0;

        if ($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }

        if ($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        if (isset($all["law_restriction"])) {
            unset($all["law_restriction"]);
        }
        if ($user->company_id == 1) {
            if ($all['status'] == 4 || $all['status'] == 5) {
                $all['own_company'] = 1;
                $all['suumo'] = 1;
                $all['homes'] = 1;
                $all['athome'] = 1;
            }
        }

        if (!is_numeric($all['another_cost1'])) {
            $all['another_cost1'] = null;
        }

        if (!is_numeric($all['another_cost2'])) {
            $all['another_cost2'] = null;
        }

        $result = $article->fill($all)->save();

        if (isset($request->id)) {
            // 温泉
            RelationSpring::where('article_id', $request->id)->delete();
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者削除
            $del_vendor_list = explode(',', $request->delete_vendor_list);

            foreach ($del_vendor_list as $del_id) {
                RelationVendorArticle::where('article_id', '=', $article->building_id)->where('vendor_id', $del_id)->delete();
            }

            // 業者登録
            $vendor_list = $request->vendor_id;
            foreach ($vendor_list as $key => $val) {
                if (empty($val)) {
                    continue;
                }
                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                $vendor['home_note'] = $request->home_note[$key];
                if (is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();

                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }
            }

        }

        $this->createOriginal($article, $request);

        if (\auth()->user()->isOwnerOfSaiKyoto()) {
            self::setPriceCustomContent($article);
        }

        $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        $dataSend['spring_kind']  = $request->spring_kind;
        $dataSend['exterior_place']  = $request->exterior_place;
        $dataSend['interior_place']  = $request->interior_place;
        $dataSend['law_restriction']  = $request->law_restriction;
        $dataSend['other_restriction']  = $request->other_restriction;
        $dataSend['event_day']  = $request->event_schedule != 3 ? [null] : $request->event_day;
        $dataSend['vendor_list'] = RelationVendorArticle::where('article_id', $request->id)->get();
        $dataSend['delete_vendor_list'] = $request->delete_vendor_list;
        $dataSend['original'] = $request->original;
        $apiService->editLand($article->building_id, $dataSend);

        // 保存せずに画像編集画面へ
        if ($request->toimage == 1) {
            $URL = url('');
            header('Location: ' . $URL . '/admin/registImage/' . $request->id);
            die();
        }
        if ($request->duplicate_info_house == 1) {
            header('Location: ' . route("showCopyLand"). '?copy=' . $article->building_id);
            die();
        }
        if ($request->toimageportal == 1) {
            $URL = url('');
            header('Location: ' . route("admin.portal.image", $article->building_id));
            die();
        }
        if ($request->detailportal == 1) {
            header('Location: ' . route("admin.portal.image", $article->building_id).'?detail=1');
            die();
        }

        if ($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->homes == 2) {
            Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->athome == 2) {
            try {
                Artisan::call('batch:athome', ['id' => $article->building_id, 'cid' => $user->company_id]);
            } catch (\Exception $exception) {
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if ($result) {

            if (\auth()->user()->isOwnerOfSaiKyoto()) {
                // $this->insertArticleIntoSai($article, false);
            }

            $data = [];
            $provisional = '';
            if(!empty(request()->get('provisional'))){
                $provisional = '?provisional=1';
            }
            $data['action'] = route('showEditLand', ['id' => $article->building_id]).$provisional;

            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * 土地情報ー編集登録画面の表示
     */
    public function showCopyLandForm(Request $request)
    {
        $old = $request->session()->all();

        $this->parentProperty = 1;
        $article = $this->getDataById($request->copy);
//        if ($article->property != 99) {
//            print('存在しない物件、または不正なアクセスです。');
//            exit;
//        }

        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 1);
        $data['article'] = $article;
        $data['copy_id'] = $request->copy;
        $data["customs"] = $this->getCustomData();

        if (isset($article->sale_no)) {
            $lot = $this->getDataById($article->sale_no);
            $article->sale_name = $lot->article_name;
        } else {
            $article->sale_name = '';
        }
        $article->building_id = null;
        $article->article_name = null;
        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->copy);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->copy);
        foreach ($facility as &$row) {
            $row->kind_name = MstFacilityType::find($row->kind)->name ?? '';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;

        $user = Auth::user();
        $data['company_id'] = $user->company_id;

        return view('admin.pages.copy-land', $data);
    }

    /**
     * 土地情報ー新規登録
     */
    public function registerCopyLand(LandPost $request)
    {
        $this->parentProperty = 1;

        $user = Auth::user();
        $building_id = Article::getMaxNo();
        if (empty($building_id)) {
            $building_id = 0;
        }

        // 登録
        $article = new Article;
        $all = $request->all();

        if (!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if (!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if (!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if (!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if (!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
        }
        if (!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
        }
        if (!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
        }
        if (!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }

        $all['building_id'] = $building_id + 1;
        if ($all['own_company'] == 2) {
            $all['disp'] = 1;
        }
        $all['provisional'] = 0;

        if ($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }

        if ($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        $result = $article->fill($all)->save();

        if (isset($article->building_id)) {
            // 温泉
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;
            foreach ($vendor_list as $key => $val) {
                if (empty($val)) {
                    continue;
                }

                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if (is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();

                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }
            }
        }
        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if ($result) {
            // 保存して画像編集画面へ
            if ($request->toimage == 1) {
                $URL = url('');
                header('Location: ' . $URL . '/admin/registImage/' . $article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditLand', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }


    /**
     * 戸建情報ー新規登録画面の表示
     */
    public function showRegistrationHouseForm(Request $request)
    {
        $old = $request->session()->all();

        // マスターデータの取得
        $this->parentProperty = 2;
        $data = $this->getMasterData(null, 2, $old, 2);
        $data['pref'] = Arr::prepend(($data['pref'] ?? []), ['code' => null, 'name' => '未選択']);

        $data["customs"] = $this->getCustomData();

        $user = Auth::user();
        $data['company_id'] = $user->company_id;
        if ($user->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }
        foreach ($data["parking"] as $key => $parking) {
            if ($parking["name"] == "２台以上") {
                unset($data["parking"][$key]);
            }
        }
        $data['store_user'] = MstStore::getDataByCode($user->company_id, $user->store_id);

        return view('admin.pages.regist-house', $data);
    }

    /**
     * 戸建情報ー新規登録
     */
    public function registerHouse(HousePost $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $building_id = Article::getMaxNo();
        if (empty($building_id)) {
            $building_id = 0;
        }

        $article = new Article;
        $all = $request->all();

        $all['building_id'] = $building_id + 1;

        if (!isset($all['reservation'])) {
            $all['reservation'] = 0;
        }
        if (!isset($all['occupied'])) {
            $all['occupied'] = 0;
        }
        if (!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if (!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if (!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if (!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if (!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
            $all['land_condition_area1'] = null;
            $all['land_condition_unit1'] = 0;
        }
        if (!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
            $all['land_condition_area2'] = null;
            $all['land_condition_unit2'] = 0;
        }
        if (!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
            $all['land_condition_area3'] = null;
            $all['land_condition_unit3'] = 0;
        }
        if (!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }
        if (!isset($all['building_condition1'])) {
            $all['building_condition1'] = 0;
            $all['building_condition_area1'] = null;
        }
        if (!isset($all['building_condition2'])) {
            $all['building_condition2'] = 0;
            $all['building_condition_area2'] = null;
        }
        if (!isset($all['building_condition3'])) {
            $all['building_condition3'] = 0;
            $all['building_condition_area3'] = null;
        }
        if (!isset($all['building_condition4'])) {
            $all['building_condition4'] = 0;
            $all['building_condition_area4'] = 1;
        }

        if ($all['own_company'] == 2) {
            $all['disp'] = 1;
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0;

        if ($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }

        if ($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        if (isset($all["law_restriction"])) {
            unset($all["law_restriction"]);
        }

        $result = $article->fill($all)->save();

        $history_data = [];
        $history_data['company_id'] = $user->company_id;
        $history_data['article_id'] = $all['building_id'];
        $history_data['price'] = $all["price"];
        $history_data['regist_date'] = date('Y-m-d');
        $history = new RelationPriceHistory;
        $history->fill($history_data)->save();

        if (isset($article->building_id)) {
            // 温泉
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 外装
            if (isset($request->exterior_place)) {
                foreach ($request->exterior_place as $row) {
                    RelationExterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            if (isset($request->interior_place)) {
                foreach ($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;

            foreach ($vendor_list as $key => $val) {
                if (empty($val)) {
                    continue;
                }

                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                $vendor['home_note'] = $request->home_note[$key];

                // $vendor['manner'] = $request->manner;
                if (is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();
                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }
            }
        }
        if ($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->homes == 2) {
            Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->athome == 2) {
            try {
                Artisan::call('batch:athome', ['id' => $article->building_id, 'cid' => $user->company_id]);
            } catch (\Exception $exception) {
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if ($result) {
            $this->createOriginal($article, $request);

            if (\auth()->user()->isOwnerOfSaiKyoto()) {
                self::setPriceCustomContent($article);
                // $this->insertArticleIntoSai($article);
            }
            $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article->building_id)->first();
            $dataSend['spring_kind']  = $request->spring_kind;
            $dataSend['exterior_place']  = $request->exterior_place;
            $dataSend['interior_place']  = $request->interior_place;
            $dataSend['law_restriction']  = $request->law_restriction;
            $dataSend['other_restriction']  = $request->other_restriction;
            $dataSend['event_day']  = $request->event_schedule != 3 ? [null] : $request->event_day;
            $dataSend['history_data']  = $history_data;
            $dataSend['vendor_list'] = RelationVendorArticle::where('article_id', $article->building_id)->get();
            $dataSend['original'] = $request->original;
            $apiService->registHouse($dataSend);

            // 保存して画像編集画面へ
            if ($request->toimage == 1) {
                $URL = url('');
                header('Location: ' . $URL . '/admin/registImage/' . $article->building_id);
                die();
            }
            if ($request->toimageportal == 1) {
                $URL = url('');
                header('Location: ' . route("admin.portal.image", $article->building_id));
                die();
            }

            $data = [];
            $data['action'] = route('showEditHouse', ['id' => $article->building_id]);



            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * 戸建情報ー編集登録画面の表示
     */
    public function showEditHouseForm(Request $request)
    {
        $old = $request->session()->all();
        $this->parentProperty = 2;

        $article = $this->getDataById($request->id);

        if (isset($article->sale_no)) {
            $lot = $this->getDataById($article->sale_no);
            $article->sale_name = $lot->article_name;
        } else {
            $article->sale_name = '';
        }

        // マスターデータの取得
        $data = $this->getMasterData($article, 2, $old, 2);

        $data["customs"] = $this->getCustomData();

        foreach ($data["parking"] as $key => $parking) {
            if ($parking["name"] == "２台以上") {
                unset($data["parking"][$key]);
            }
        }

        $article->event_day = $article->events()->select("event_day")->pluck("event_day")->toArray();

        $messArray = [];
        if($article->name == null) {
            $messArray['name_article'] = '物件名は必須項目です。';
        }
        if ($article->company_manner == null) {
            $messArray['company_manner'] = '取引態様は必須項目です。';
        }

        if ($article->price == null) {
            $messArray['price'] = '物件価格は必須項目です。';
        }
        if ($article->land_area_val == null) {
            $messArray['land_area_val'] = '土地面積は必須項目です。';
        }
        if ($article->construction == 0) {
            $messArray['construction'] = '構造は必須項目です。';
        }
        if ($article->shop == null) {
            $messArray['shop'] = '物件取扱店舗名は必須項目です。';
        }
        if ($article->main_traffic_line == null && $article->else_traffic_line == null) {
            $messArray['main_traffic_line'] = '主要交通は必須項目です。';
        }
        if ($article->total_area_val == null || $article->total_area == 0) {
            $messArray['total_area_val'] = '建物面積は必須項目です。';
        }
        if ($article->use_area == null) {
            $messArray['use_area'] = '用途地域は必須項目です。';
        }
        if ($article->move_in == 0) {
            $messArray['move_in'] = '引渡しは必須項目です。';
        }
        if ($article->ground == 0) {
            $messArray['ground'] = '地目は必須項目です。';
        }
        if ($article->city_plan > 1 && $article->building_rate == '') {
            $messArray['building_rate'] = '建ぺい率は必須項目です。';
        }
        if ($article->city_plan > 1 && $article->volume_rate == '') {
            $messArray['volume_rate'] = '容積率は必須項目です。';
        }

        if ((is_null($article->another_cost1) && !empty($article->another_cost_unit1)) || (!is_null($article->another_cost1) && empty($article->another_cost_unit1))) {
            $messArray['another_cost1'] = 'その他諸費用１を入力してください。';
        }

        if ((is_null($article->another_cost2) && !empty($article->another_cost_unit2)) || (!is_null($article->another_cost2) && empty($article->another_cost_unit2))) {
            $messArray['another_cost2'] = 'その他諸費用２を入力してください。';
        }

        $data['article'] = $article;
        $data['public_portal'] = $article->portalPublic();
        $data['messArray'] = $messArray;
        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        foreach ($facility as &$row) {
            $row->kind_name = MstFacilityType::find($row->kind)->name ?? '';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;
        $data['saved'] = $request->saved ?? '';
        if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        $user = Auth::user();
        $data['store'] = MstStore::getDataByCode($user->company_id, $article->shop);
        $data['store_user'] = MstStore::getDataByCode($user->company_id, $user->store_id);

        return view('admin.pages.edit-house', $data);
    }

    /**
     * 戸建情報ー編集登録
     */
    public function editHouse(HousePost $request, CompanyApiService $apiService)
    {
        $user = Auth::user();

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        if ($article->price != $request->get("price")) {
            $history_data = [];
            $history_data['company_id'] = $user->company_id;
            $history_data['article_id'] = $article->building_id;
            $history_data['price'] = $request->get("price");
            $history_data['regist_date'] = date('Y-m-d');
            $history = new RelationPriceHistory;
            $history->fill($history_data)->save();
        }

        $all = $request->all();

        if (!isset($all['reservation'])) {
            $all['reservation'] = 0;
        }
        if (!isset($all['occupied'])) {
            $all['occupied'] = 0;
        }
        if (!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if (!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if (!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if (!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if (!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
            $all['land_condition_area1'] = null;
            $all['land_condition_unit1'] = 0;
        }
        if (!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
            $all['land_condition_area2'] = null;
            $all['land_condition_unit2'] = 0;
        }
        if (!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
            $all['land_condition_area3'] = null;
            $all['land_condition_unit3'] = 0;
        }
        if (!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }
        if (!isset($all['building_condition1'])) {
            $all['building_condition1'] = 0;
            $all['building_condition_area1'] = null;
        }
        if (!isset($all['building_condition2'])) {
            $all['building_condition2'] = 0;
            $all['building_condition_area2'] = null;
        }
        if (!isset($all['building_condition3'])) {
            $all['building_condition3'] = 0;
            $all['building_condition_area3'] = null;
        }
        if (!isset($all['building_condition4'])) {
            $all['building_condition4'] = 0;
            $all['building_condition_area4'] = 1;
        }

        if ($all['own_company'] == 2) {
            $all['disp'] = 1;
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0;

        if ($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }

        if ($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        if (isset($all["law_restriction"])) {
            unset($all["law_restriction"]);
        }

        if ($user->company_id == 1) {
            if ($all['status'] == 4 || $all['status'] == 5) {
                $all['own_company'] = 1;
                $all['suumo'] = 1;
                $all['homes'] = 1;
                $all['athome'] = 1;
            }
        }

        if (!is_numeric($all['another_cost1'])) {
            $all['another_cost1'] = null;
        }

        if (!is_numeric($all['another_cost2'])) {
            $all['another_cost2'] = null;
        }

        $result = $article->fill($all)->save();

        if (isset($request->id)) {

            // 温泉
            RelationSpring::where('article_id', $request->id)->delete();
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 外装
            RelationExterior::where('article_id', $request->id)->delete();
            if (isset($request->exterior_place)) {
                foreach ($request->exterior_place as $row) {
                    RelationExterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            RelationInterior::where('article_id', $request->id)->delete();
            if (isset($request->interior_place)) {
                foreach ($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者削除
            $del_vendor_list = explode(',', $request->delete_vendor_list);

            foreach ($del_vendor_list as $del_id) {
                RelationVendorArticle::where('article_id', '=', $article->building_id)->where('vendor_id', $del_id)->delete();
            }

            // 業者登録
            $vendor_list = $request->vendor_id;
            foreach ($vendor_list as $key => $val) {
                if (empty($val)) {
                    continue;
                }

                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                //$vendor['manner'] = $request->manner;
                $vendor['manner'] = $request->manner[$key];
                $vendor['home_note'] = $request->home_note[$key];
                if (is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();

                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }
            }

            // 施設削除
            $del_facility_list = explode(',', $request->delete_facility_list);

            foreach ($del_facility_list as $del_id) {
                RelationArticleFacility::where('article_id', '=', $article->building_id)->where('facility_id', $del_id)->delete();
            }
        }

        $this->createOriginal($article, $request);

        if (\auth()->user()->isOwnerOfSaiKyoto()) {
            self::setPriceCustomContent($article);
        }

        $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        $dataSend['spring_kind']  = $request->spring_kind;
        $dataSend['exterior_place']  = $request->exterior_place;
        $dataSend['interior_place']  = $request->interior_place;
        $dataSend['law_restriction']  = $request->law_restriction;
        $dataSend['other_restriction']  = $request->other_restriction;
        $dataSend['event_day']  = $request->event_schedule != 3 ? [null] : $request->event_day;
        $dataSend['relation_vendor_article'] = RelationVendorArticle::where('article_id', $request->id)->get();
        $dataSend['delete_vendor_list'] = $request->delete_vendor_list;
        $dataSend['original'] = $request->original;
        $apiService->editHouse($article->building_id, $dataSend);

        // 保存せずに画像編集画面へ
        if ($request->duplicate_info_house == 1) {
            header('Location: ' . route("showCopyHouse"). '?copy=' . $article->building_id);
            die();
        }
        if ($request->toimage == 1) {
            $URL = url('');
            header('Location: ' . $URL . '/admin/registImage/' . $request->id);
            die();
        }
        if ($request->toimageportal == 1) {
            $URL = url('');
            header('Location: ' . route("admin.portal.image", $article->building_id));
            die();
        }
        if ($request->detailportal == 1) {
            header('Location: ' . route("admin.portal.image", $article->building_id).'?detail=1');
            die();
        }

        if ($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'user' => $user]);
        }

        if ($article->homes == 2) {
            Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->athome == 2) {
            try {
                Artisan::call('batch:athome', ['id' => $article->building_id, 'cid' => $user->company_id]);
            } catch (\Exception $exception) {
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if ($result) {

            if (\auth()->user()->isOwnerOfSaiKyoto()) {
                // $this->insertArticleIntoSai($article, false);
            }
            $provisional = '';
            if(!empty(request()->get('provisional'))){
                $provisional = '?provisional=1';
            }
            $data = [];
            $data['action'] = route('showEditHouse', ['id' => $article->building_id]).$provisional;
            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * 戸建情報ー編集登録画面の表示
     */
    public function showCopyHouseForm(Request $request)
    {
        $old = $request->session()->all();
        $this->parentProperty = 2;

        $article = $this->getDataById($request->copy);
//        if ($article->property != 99) {
//            print('存在しない物件、または不正なアクセスです。');
//            exit;
//        }

        // マスターデータの取得
        $data = $this->getMasterData($article, 2, $old, 2);
        $data['article'] = $article;
        $data['copy_id'] = $request->copy;
        $data["customs"] = $this->getCustomData();

        if (isset($article->sale_no)) {
            $lot = $this->getDataById($article->sale_no);
            $article->sale_name = $lot->article_name;
        } else {
            $article->sale_name = '';
        }
        $article->building_id = null;
        $article->article_name = null;
        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->copy);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->copy);
        foreach ($facility as &$row) {
            $row->kind_name = MstFacilityType::find($row->kind)->name ?? '';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;

        $user = Auth::user();
        $data['company_id'] = $user->company_id;

        return view('admin.pages.copy-house', $data);
    }

    /**
     * 戸建情報ー新規登録
     */
    public function registerCopyHouse(HousePost $request)
    {
        $user = Auth::user();
        $building_id = Article::getMaxNo();
        if (empty($building_id)) {
            $building_id = 0;
        }

        $article = new Article;
        $all = $request->all();
        $all['building_id'] = $building_id + 1;

        if (!isset($all['occupied'])) {
            $all['occupied'] = 0;
        }
        if (!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if (!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if (!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if (!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if (!isset($all['land_condition1'])) {
            $all['land_condition1'] = 0;
            $all['land_condition_area1'] = null;
            $all['land_condition_unit1'] = 0;
        }
        if (!isset($all['land_condition2'])) {
            $all['land_condition2'] = 0;
            $all['land_condition_area2'] = null;
            $all['land_condition_unit2'] = 0;
        }
        if (!isset($all['land_condition3'])) {
            $all['land_condition3'] = 0;
            $all['land_condition_area3'] = null;
            $all['land_condition_unit3'] = 0;
        }
        if (!isset($all['land_not'])) {
            $all['land_not'] = 0;
        }
        if (!isset($all['building_condition1'])) {
            $all['building_condition1'] = 0;
            $all['building_condition_area1'] = null;
        }
        if (!isset($all['building_condition2'])) {
            $all['building_condition2'] = 0;
            $all['building_condition_area2'] = null;
        }
        if (!isset($all['building_condition3'])) {
            $all['building_condition3'] = 0;
            $all['building_condition_area3'] = null;
        }
        if (!isset($all['building_condition4'])) {
            $all['building_condition4'] = 0;
            $all['building_condition_area4'] = 1;
        }

        if ($all['own_company'] == 2) {
            $all['disp'] = 1;
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0;

        if ($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }

        if ($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        $result = $article->fill($all)->save();

        if (isset($article->building_id)) {
            // 温泉
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 外装
            if (isset($request->exterior_place)) {
                foreach ($request->exterior_place as $row) {
                    RelationExterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            if (isset($request->interior_place)) {
                foreach ($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;
            foreach ($vendor_list as $key => $val) {
                if (empty($val)) {
                    continue;
                }

                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                if (is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();

                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if ($result) {
            // 保存して画像編集画面へ
            if ($request->toimage == 1) {
                $URL = url('');
                header('Location: ' . $URL . '/admin/registImage/' . $article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditHouse', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }


    /**
     * マンション検索
     */
    public function showTopMansionForm(Request $request)
    {
        $user = $request->user();
        $old = $request->session()->all();
        $cookie = Cookie::forget('current_params');
        $params = $request->all();

        // マスターデータの取得
        $this->parentProperty = 3;
        $data = $this->getMasterData(null, null, $old, 3);
        $data['active'] = "top";

        if (!empty($request->all())) {
            $request->merge(['url_search' => url()->current()]);
            $cookie = cookie('current_params', json_encode($request->all(), 10));
            $mansion_list = Article::getMansionList($request, 20);
            foreach ($mansion_list as &$mansion) {
                $room_list = Article::getDataByRoom($mansion->building_id);
                $mansion->room_list = $room_list;
                $mansion->room_count = count($room_list);
                foreach ($room_list as &$room) {
                    $vendor = Vendor::getDataByArticleId($room->building_id);
                    $room->vendor = $vendor->name ?? '';
                    $room->vendor_tel = $vendor->vendor_tel ?? '';
                    $room->floor_plan_name = MstFloorType::find($room->floor_plan_type)->name ?? '';
                    $room->status_name = MstStatus::find($room->status)->name ?? '';
                    $vendor = RelationVendorArticle::getVendorDataByRainsNo($room->buiding_id);
                }

            }
            // 表示中のページの最初のアイテムのインデックス番号
            $first = $mansion_list->firstItem();

            // 表示中のページの最後のアイテムのインデックス番号
            $last = $mansion_list->lastItem();

            $data['list'] = $mansion_list;
            $data['first'] = $first;
            $data['last'] = $last;
        }

        // 都道府県マスターを取得
        //$data['pref'] = MstPrefecture::getData(null, $user->company_id);
        //$data['city'] = MstCity::getData(config('const.DEFAULT_PREF'));
        $data['town'] = [];
        if ($request->search_address2) {
            $data['town'] = MstTown::getData($request->search_address1, $request->search_address2);
        }

        $data['params'] = $params;
        $data['role_user'] = $user->role;

        return response()->view('admin.pages.top-mansion', $data)->withCookie($cookie);
    }

    /**
     * マンション情報ー新規登録画面の表示
     */
    public function showRegistrationMansionForm(Request $request)
    {
        $old = $request->session()->all();
        // マスターデータの取得
        $this->parentProperty = 3;
        $data = $this->getMasterData(null, null, $old, 3);
        $data['pref'] = Arr::prepend(($data['pref'] ?? []), ['code' => null, 'name' => '未選択']);

        $data["customs"] = $this->getCustomData();

        $data['active'] = "regist";

        $data['mansion_active'] = true;

        $user = Auth::user();
        $data['company_id'] = $user->company_id;
        if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.regist-mansion', $data);
    }

    /**
     * マンション情報ー新規登録
     */
    public function registerMansion(MansionPost $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $building_id = Article::getMaxNo();
        if (empty($building_id)) {
            $building_id = 0;
        }

        $article = new Article;
        $all = $request->all();

        $all['disp'] = 1;
        $all['provisional'] = 0;
        $all['first'] = 1;
        $all['building_id'] = $building_id + 1;
        unset($all['_token']);
        $all['name_apartment'] = $all['name'];
        $result = $article->fill($all)->save();
        $saved_id = $article->building_id;

        if (isset($article->building_id)) {
            // 共用部
            if (isset($request->shared)) {
                foreach ($request->shared as $row) {
                    RelationShared::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
            // 法律上の制限
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if ($result) {
            if ($user->isOwnerOfSaiKyoto() && $article->library == 1) {
                // save data to database SaiKyoto
                $masterData = $this->getMasterData(null, null, null, 3);
                $dataForSaiKyoto = SaiKyotoArticleConverter::convert($all, $masterData);
                if (!empty($dataForSaiKyoto)) {
                    $articleForSaiKyoto = new ArticleForSaiKyoto();
                    $dataForSaiKyoto["OH"] = $this->createBuildingId($article->building_id);
                    $articleForSaiKyoto->fill($dataForSaiKyoto)->save();
                    $article->update(['building_id' => $articleForSaiKyoto->OH]);
                    $createTime = $this->convertDateTime($article->created_at);
                    $updateTime = $this->convertDateTime($article->updated_at);

                    $articleForSaiKyoto->update(["OB" => $createTime, "OA" => $updateTime]);
                }
            }


            $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article->building_id)->first();
            $dataSend['shared']  = $request->shared;
            $dataSend['law_restriction']  = $request->law_restriction;
            $dataSend['other_restriction']  = $request->other_restriction;

            $apiService->registMansion($dataSend);

            // 保存して画像編集画面へ
            if ($request->toimage == 1) {
                $URL = url('');
                header('Location: ' . $URL . '/admin/registImage/' . $article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditMansion', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    private function createBuildingId($buildingId)
    {
        $existsBuildingId = ArticleForSaiKyoto::where("OH", $buildingId)->exists();
        if ($existsBuildingId) {
            $this->createBuildingId($buildingId++);
        }

        return $buildingId;
    }

    /**
     * マンション情報ー編集登録画面の表示
     */
    public function showEditMansionForm(Request $request)
    {
        $old = $request->session()->all();
        $this->parentProperty = 3;

        $article = $this->getDataById($request->id);
        $room = Article::getRoomList($article->building_id);

        foreach ($room as &$row) {
            $row->floor_plan_name = MstFloorType::find($row->floor_plan_type)->name ?? '';
        }

        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 3);
        $messArray = [];
        if ($article->name == null) {
            $messArray['name_article'] = 'マンション名は必須項目です';
        }
        if ($article->main_traffic_line == null && ($article->else_traffic_line == null || $article->else_traffic_station == null)) {
            $messArray['main_traffic_line'] = '主要交通の路線は必須項目です。';
        }
        if ($article->age_year == null || $article->age_month == null) {
            $messArray['age_year'] = '築年月は必須項目です。';
        }
        if ($article->construction == 0) {
            $messArray['construction'] = '構造は必須項目です。';
        }
        if ($article->floor == null || $article->underground === null) {
            $messArray['floor'] = '階数は必須項目です';
        }
        if ($article->use_area == null) {
            $messArray['use_area'] = '用途地域は必須項目です。';
        }
        if ($article->management_form == 0) {
            $messArray['management_form'] = '管理形態は必須項目です。';
        }

        $data["customs"] = $this->getCustomData();
        $data['article'] = $article;
        $data['messArray'] = $messArray;
        $data['room'] = $room;
        $data['mansion_active'] = true;
        $data['saved'] = $request->saved ?? '';
        return view('admin.pages.edit-mansion', $data);
    }

    /**
     * マンション情報ー編集登録
     */
    public function editMansion(MansionPost $request, CompanyApiService $apiService)
    {
        $user = Auth::user();

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        $address1Old = $article->address1;
        $address2Old = $article->address2;
        $address3Old = $article->address3;
        $address4Old = $article->address4;
        $all = $request->all();
        $all['disp'] = 1;
        //$all['provisional'] = 0;
        $all['first'] = 1;
        $all['name_apartment'] = $all['name'];
        if(isset($all['construction_sub']) && $all['construction_sub'] == null){
            $all['construction_sub'] = 0;
        }
        $result = $article->fill($all)->save();

        $roomList = Article::getDataByRoom($article->building_id);
        $dataRoom = $all;
        unset($dataRoom['name']);
        unset($dataRoom['memo1']);
        unset($dataRoom['memo2']);
        unset($dataRoom['build_note']);
        unset($dataRoom['comment']);
        unset($dataRoom['property_sub']);
        unset($dataRoom['property']);
        foreach ($roomList as $room) {
            $room->fill($dataRoom)->save();
        }

        if (isset($request->id)) {
            // 共用部
            RelationShared::where('company_id', '=', $user->company_id)->where('article_id', $request->id)->delete();
            if (isset($request->shared)) {
                foreach ($request->shared as $row) {
                    RelationShared::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }
        }

        $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        $dataSend['shared']  = $request->shared;
        $dataSend['law_restriction']  = $request->law_restriction;
        $dataSend['other_restriction']  = $request->other_restriction;
        $dataSend['event_day']  = $request->event_day;
        $apiService->editMansion($article->building_id, $dataSend);

        // 保存せずに画像編集画面へ
        if ($request->toimage == 1) {
            $URL = url('');
            header('Location: ' . $URL . '/admin/registImage/' . $request->id);
            die();
        } elseif (isset($request->toroom)) {
            $URL = url('');
            header('Location: ' . $URL . '/admin/editRoom/' . $request->id . '/' . $request->toroom);
            die();
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if ($result) {
            // save data to database SaiKyoto => not use
//            if ($user->isOwnerOfSaiKyoto() && $article->library == 1) {
//                $articleForSaiKyoto = ArticleForSaiKyoto::find($article->building_id);
//                $masterData = $this->getMasterData(null, null, null, 3);
//                $dataForSaiKyoto = SaiKyotoArticleConverter::convert($all, $masterData);
//                $createTime = $this->convertDateTime($article->created_at);
//                $updateTime = $this->convertDateTime($article->updated_at);
//
//                if (!empty($articleForSaiKyoto)) {
//                    $articleForSaiKyoto->fill($dataForSaiKyoto)->save();
//                    $articleForSaiKyoto->update(["OB" => $createTime, "OA" => $updateTime]);
//                } else {
//                    $articleForSaiKyoto = new ArticleForSaiKyoto();
//                    $dataForSaiKyoto["OH"] = $article->building_id;
//                    $articleForSaiKyoto->fill($dataForSaiKyoto)->save();
//                    $article->update(['building_id' => $articleForSaiKyoto->OH]);
//
//                    $articleForSaiKyoto->update(["OB" => $createTime, "OA" => $updateTime]);
//                }
//            }

            $URL = url('');
            if ($request->room == 1) {
                header('Location: ' . $URL . '/admin/registRoom/' . $request->id);
                die();
            } else {
                $data = [];
                $data['action'] = route('showEditMansion', ['id' => $article->building_id]);
                return view('admin.pages.redirect', $data);
            }

        }
    }

    /**
     * マンション情報ー新規登録画面の表示
     */
    public function showRegistrationRoomForm(Request $request)
    {
        $user = Auth::user();
        $old = $request->session()->all();
        // マンションデータの取得
        $article = $this->getDataById($request->id);
        $article->own_company = 1;
        if ($article->property != 6 && $article->property != 7) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }
        // 共用部
        $shared_text = "";

        $checked_shared = RelationShared::getDataByArticleId($user->company_id, $article->building_id);
        if (count($checked_shared) > 0) {
            foreach ($checked_shared as $row) {
                $shared_item = MstShared::getName($row);
                if ($shared_text != "") {
                    $shared_text .= " / ";
                }
                $shared_text .= $shared_item->name;
            }
        }
        $article->shared_text = $shared_text;


        // 学校データの取得
        $disp_school = "";
        if (isset($article->primary_school_school)) {
            $school_tmp = MstSchool::getSchoolByCode($article->primary_school_school);
            $article->primary_school_name = $school_tmp->name;
            if (isset($article->primary_school_distance)) {
                $article->primary_school_time = ceil($article->primary_school_distance / 80);
            }

        }
        if (isset($article->primary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($article->primary_school2_school);
            $article->primary_school_name2 = $school_tmp->name;
            if (isset($article->primary_school2_distance)) {
                $article->primary_school_time2 = ceil($article->primary_school2_distance / 80);
            }

        }

        if (isset($article->secondary_school_school) && $article->primary_school2_school != '') {
            $school_tmp = MstSchool::getSchoolByCode($article->secondary_school_school);
            $article->secondary_school_name = $school_tmp->name;
            if (isset($article->secondary_school_distance)) {
                $article->secondary_school_time = ceil($article->secondary_school_distance / 80);
            }
        }
        if (isset($article->secondary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($article->secondary_school2_school);
            $article->secondary_school_name2 = $school_tmp->name;
            if (isset($article->secondary_school2_distance)) {
                $article->secondary_school_time2 = ceil($article->secondary_school2_distance / 80);
            }
        }

        if (isset($article->other_primary_school_2)) {
            $school_tmp = MstSchool::getSchoolByCode($article->other_primary_school_2);
            if(isset($school_tmp))
            $article->other_primary_school_name = $school_tmp->name;
            else $article->other_primary_school_name = $article->other_primary_school_2;
            if (isset($article->other_primary_school_3)) {
                $article->other_primary_school_time = ceil($article->other_primary_school_3 / 80);
            }
        }

        if (isset($article->other_secondary_school_2)) {
            $school_tmp = MstSchool::getSchoolByCode($article->other_secondary_school_2);
            if(isset($school_tmp))
                $article->other_secondary_school_name = $school_tmp->name;
            else $article->other_secondary_school_name = $article->other_secondary_school_2;
            if (isset($article->other_secondary_school_3)) {
                $article->other_secondary_school_time = ceil($article->other_secondary_school_3 / 80);
            }
        }
        $data['store_user'] = MstStore::getDataByCode($user->company_id, $user->store_id);
        // マスターデータの取得
        $data = $this->getMasterData($article, 2, $old, 3);

        $data["customs"] = $this->getCustomData();

        $data['article'] = $article;

        return view('admin.pages.regist-room', $data);
    }

    /**
     * マンション情報ー新規登録
     */
    public function registerRoom(RoomPost $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $building_id = Article::getMaxNo();
        if (empty($building_id)) {
            $building_id = 0;
        }

        // 登録
        $article = new Article;
        $all = $request->all();

        if (!isset($all['reservation'])) {
            $all['reservation'] = 0;
        }
        if (!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if (!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if (!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if (!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if (!isset($all['maisonette'])) {
            $all['maisonette'] = 0;
        }
        $all['company_id'] = $user->company_id;
        $all['building_id'] = $building_id + 1;
        $all['mansion_id'] = $request->id;
        if ($all['own_company'] == 2) {
            $all['disp'] = 1;
            // 親マンションも本登録
            Article::where('building_id', $request->id)->where('company_id', '=', $user->company_id)->update(['provisional' => 0, 'own_company' => 2]);
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0;

        if ($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }

        if ($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        if (isset($all["law_restriction"])) {
            unset($all["law_restriction"]);
        }
        if($user->company_id == 3){
            $mansion = $this->getDataById($request->id);
            if(!empty($mansion)){
                $all['floor'] = $mansion->floor;
                $all['underground'] = $mansion->underground;
                $all['age_year'] = $mansion->age_year;
                $all['age_month'] = $mansion->age_month;
                $all['construction'] = $mansion->construction;
                $all['construction_sub'] = $mansion->construction_sub;
                $all['section'] = $mansion->section;
                $all['kokudoho'] = $mansion->kokudoho;
                $all['use_area'] = $mansion->use_area;
                $all['land_use'] = $mansion->land_use;
                $all['land_use2'] = $mansion->land_use2;
                $all['management_form'] = $mansion->management_form;
                $all['gas'] = $mansion->gas;
                $all['main_traffic_line'] = $mansion->main_traffic_line;
                $all['main_traffic_station'] = $mansion->main_traffic_station;
                $all['main_traffic'] = $mansion->main_traffic;
                $all['main_traffic_time'] = $mansion->main_traffic_time;
                $all['main_traffic_bus_time'] = $mansion->main_traffic_bus_time;
                $all['main_traffic_bus'] = $mansion->main_traffic_bus;
                $all['main_traffic_bus_walk'] = $mansion->main_traffic_bus_walk;
                $all['sub_traffic1_line'] = $mansion->sub_traffic1_line;
                $all['sub_traffic1_station'] = $mansion->sub_traffic1_station;
                $all['sub_traffic1'] = $mansion->sub_traffic1;
                $all['sub_traffic1_time'] = $mansion->sub_traffic1_time;
                $all['sub_traffic1_bus_time'] = $mansion->sub_traffic1_bus_time;
                $all['sub_traffic1_bus'] = $mansion->sub_traffic1_bus;
                $all['sub_traffic1_bus_walk'] = $mansion->sub_traffic1_bus_walk;
                $all['sub_traffic2_line'] = $mansion->sub_traffic2_line;
                $all['sub_traffic2_station'] = $mansion->sub_traffic2_station;
                $all['sub_traffic2'] = $mansion->sub_traffic2;
                $all['sub_traffic2_time'] = $mansion->sub_traffic2_time;
                $all['sub_traffic2_bus_time'] = $mansion->sub_traffic2_bus_time;
                $all['sub_traffic2_bus'] = $mansion->sub_traffic2_bus;
                $all['sub_traffic2_bus_walk'] = $mansion->sub_traffic2_bus_walk;
                $all['total_unit'] = $mansion->total_unit;
                $all['primary_school_city'] = $mansion->primary_school_city;
                $all['primary_school_school'] = $mansion->primary_school_school;
                $all['primary_school_distance'] = $mansion->primary_school_distance;
                $all['primary_school2_city'] = $mansion->primary_school2_city;
                $all['primary_school2_school'] = $mansion->primary_school2_school;
                $all['primary_school2_distance'] = $mansion->primary_school2_distance;
                $all['primary_school3_city'] = $mansion->primary_school3_city;
                $all['primary_school3_school'] = $mansion->primary_school3_school;
                $all['primary_school3_distance'] = $mansion->primary_school3_distance;
                $all['secondary_school_city'] = $mansion->secondary_school_city;
                $all['secondary_school_school'] = $mansion->secondary_school_school;
                $all['secondary_school_distance'] = $mansion->secondary_school_distance;
                $all['secondary_school2_city'] = $mansion->secondary_school2_city;
                $all['secondary_school2_school'] = $mansion->secondary_school2_school;
                $all['secondary_school2_distance'] = $mansion->secondary_school2_distance;
                $all['secondary_school3_city'] = $mansion->secondary_school3_city;
                $all['secondary_school3_school'] = $mansion->secondary_school3_school;
                $all['secondary_school3_distance'] = $mansion->secondary_school3_distance;
                $all['pet'] = $mansion->pet;
                $all['pet_count'] = $mansion->pet_count;
            }
        }

        $result = $article->fill($all)->save();
        $history_data = [];
        $history_data['company_id'] = $user->company_id;
        $history_data['article_id'] = $all['building_id'];
        $history_data['price'] = $all["price"];
        $history_data['regist_date'] = date('Y-m-d');
        $history = new RelationPriceHistory;
        $history->fill($history_data)->save();

        if (isset($article->building_id)) {
            // 温泉
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            if (isset($request->interior_place)) {
                foreach ($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者
            $vendor_list = $request->vendor_id;
            foreach ($vendor_list as $key => $val) {
                if (empty($val)) {
                    continue;
                }

                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = (int) $request->manner[$key];
                $vendor['home_note'] = $request->home_note[$key];
                if (is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();

                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }
            }
        }
        if ($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->homes == 2) {
            Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->athome == 2) {
            try {
                Artisan::call('batch:athome', ['id' => $article->building_id, 'cid' => $user->company_id]);
            } catch (\Exception $exception) {
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();

        if ($result) {
            $this->createOriginal($article, $request);

            if ($user->isOwnerOfSaiKyoto()) {
                self::setPriceCustomContent($article);
                $mansion = $article->getMansion();
                // $this->insertArticleIntoSai($article, true, $mansion);
            }

            $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article->building_id)->first();
            $dataSend['spring_kind']  = $request->spring_kind;
            $dataSend['interior_place']  = $request->interior_place;
            $dataSend['law_restriction']  = $request->law_restriction;
            $dataSend['other_restriction']  = $request->other_restriction;
            $dataSend['event_day']  = $request->event_schedule != 3 ? [null] : $request->event_day;
            $dataSend['history_data']  = $history_data;
            $dataSend['vendor_list'] = RelationVendorArticle::where('article_id', $article->building_id)->get();
            $dataSend['original'] = $request->original;

            $apiService->registRoom($dataSend);

            // 保存して画像編集画面へ
            if ($request->toimage == 1) {
                $URL = url('');
                header('Location: ' . $URL . '/admin/registImage/' . $article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditRoom', ['mid' => $request->id, 'id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    public function showCopyRoomForm(Request $request)
    {
        $user = Auth::user();
        $old = $request->session()->all();
        $this->parentProperty = 3;

        $mansion = $this->getDataById($request->mid);
        $article = $this->getDataById($request->copy);

        // マスターデータの取得
        $data = $this->getMasterData($mansion, null, $old, 3);

        $data['copy_id'] = $request->copy;
        $data["customs"] = $this->getCustomData();

        $article->sale_no = $article->building_id;
        $article->sale_name = $article->article_name;
        $article->building_id = null;
        $article->article_name = null;
        $mansion->shop = $article->shop;

        // 共用部


        $spring_kind = [
            ['code' => 1, 'name' => '加温'],
            ['code' => 2, 'name' => '加水'],
            ['code' => 3, 'name' => '運び湯'],
            ['code' => 4, 'name' => '循環装置使用'],
            ['code' => 5, 'name' => '循環ろ過装置使用'],
        ];
        $checked_spring = RelationSpring::getDataByArticleId($user->company_id, $article->building_id);

        if (count($checked_spring) > 0) {
            foreach ($spring_kind as &$row) {
                if (in_array($row['code'], $checked_spring)) {
                    $row['checked'] = 1;
                }
            }
        }
        $data['spring_kind'] = $spring_kind;

        $interior = [
            ['code' => '1', 'name' => 'キッチン'],
            ['code' => '2', 'name' => '浴室'],
            ['code' => '3', 'name' => 'トイレ'],
            ['code' => '4', 'name' => '壁'],
            ['code' => '5', 'name' => '床'],
            ['code' => '6', 'name' => '全室'],
            ['code' => '7', 'name' => 'その他'],
        ];
        $checked_interior = RelationInterior::getDataByArticleId($user->company_id, $article->building_id);

        if (count($checked_interior) > 0) {
            foreach ($interior as &$row) {
                if (in_array($row['code'], $checked_interior)) {
                    $row['checked'] = 1;
                }
            }
        }
        $data['interior'] = $interior;

        if (isset($mansion->primary_school_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->primary_school_school);
            if (request()->get("debug")) {
                dd($mansion->primary_school_school);
            }
            $mansion->primary_school_name = $school_tmp->name ?? '';
            if (isset($mansion->primary_school_distance)) {
                $mansion->primary_school_time = ceil($mansion->primary_school_distance / 80);
            }
        }
        if (isset($mansion->primary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->primary_school2_school);
            $mansion->primary_school_name2 = $school_tmp->name ?? '';
            if (isset($mansion->primary_school2_distance)) {
                $mansion->primary_school_time2 = ceil($mansion->primary_school2_distance / 80);
            }
        }

        if (isset($mansion->secondary_school_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->secondary_school_school);
            $mansion->secondary_school_name = $school_tmp->name  ?? '';;
            if (isset($mansion->secondary_school_distance)) {
                $mansion->secondary_school_time = ceil($mansion->secondary_school_distance / 80);
            }
        }
        if (isset($mansion->secondary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->secondary_school2_school);
            $mansion->secondary_school_name2 = $school_tmp->name  ?? '';;
            if (isset($mansion->secondary_school2_distance)) {
                $mansion->secondary_school_time2 = ceil($mansion->secondary_school2_distance / 80);
            }
        }
        if (isset($mansion->other_primary_school_2)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->other_primary_school_2);
            if(isset($school_tmp))
                $mansion->other_primary_school_name = $school_tmp->name;
            else $mansion->other_primary_school_name = $mansion->other_primary_school_2;
            if (isset($mansion->other_primary_school_3)) {
                $mansion->other_primary_school_time = ceil($mansion->other_primary_school_3 / 80);
            }
        }

        if (isset($mansion->other_secondary_school_2)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->other_secondary_school_2);
            if(isset($school_tmp))
                $mansion->other_secondary_school_name = $school_tmp->name;
            else $mansion->other_secondary_school_name = $mansion->other_secondary_school_2;
            if (isset($mansion->other_secondary_school_3)) {
                $mansion->other_secondary_school_time = ceil($mansion->other_secondary_school_3 / 80);
            }
        }


        $article->event_day = $article->events()->select("event_day")->pluck("event_day")->toArray();

        if($mansion->land_right == 2 or $mansion->land_right == 3){
            if($mansion->leasehold_period_year1 != null && $mansion->leasehold_period_month1 != null) {
                $dt = Carbon::create($mansion->leasehold_period_year1, $mansion->leasehold_period_month1)->lastOfMonth();
                $now = Carbon::now()->firstOfMonth();
                $df_new = $dt->diff($now);
                $mansion->leasehold_period_year = $df_new->format('%Y');
                $mansion->leasehold_period_month = $df_new->format('%m');
            }
        }

        $data['mansion'] = $mansion;
        $data['article'] = $article;
        $data['public_portal'] = $article->portalPublic();


        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->copy);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->copy);
        foreach ($facility as &$row) {
            $row->kind_name = MstFacilityType::find($row->kind)->name ?? '';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;
        $data['saved'] = $request->saved ?? '';

        $user = Auth::user();
        $data['store'] = MstStore::getDataByCode($user->company_id, $article->shop);
        $data['store_user'] = MstStore::getDataByCode($user->company_id, $user->store_id);

        return view('admin.pages.copy-room', $data);
    }

    /**
     * マンション情報ー編集登録画面の表示
     */
    public function showEditRoomForm(Request $request)
    {
        $user = Auth::user();
        $old = $request->session()->all();
        $this->parentProperty = 3;

        $mansion = $this->getDataById($request->mid);
        $article = $this->getDataById($request->id);
        $mansion->shop = $article->shop;

        // マスターデータの取得
        $data = $this->getMasterData($mansion, null, $old, 3);

        $data["customs"] = $this->getCustomData();

        // 共用部
        $shared_text = "";

        $checked_shared = RelationShared::getDataByArticleId($user->company_id, $mansion->building_id);
        if (count($checked_shared) > 0) {
            foreach ($checked_shared as $row) {
                $shared_item = MstShared::getName($row);
                if ($shared_text != "") {
                    $shared_text .= " / ";
                }
                $shared_text .= $shared_item->name;
            }
        }
        $mansion->shared_text = $shared_text;

        $spring_kind = [
            ['code' => 1, 'name' => '加温'],
            ['code' => 2, 'name' => '加水'],
            ['code' => 3, 'name' => '運び湯'],
            ['code' => 4, 'name' => '循環装置使用'],
            ['code' => 5, 'name' => '循環ろ過装置使用'],
        ];
        $checked_spring = RelationSpring::getDataByArticleId($user->company_id, $article->building_id);

        if (count($checked_spring) > 0) {
            foreach ($spring_kind as &$row) {
                if (in_array($row['code'], $checked_spring)) {
                    $row['checked'] = 1;
                }
            }
        }
        $data['spring_kind'] = $spring_kind;

        $interior = [
            ['code' => '1', 'name' => 'キッチン'],
            ['code' => '2', 'name' => '浴室'],
            ['code' => '3', 'name' => 'トイレ'],
            ['code' => '4', 'name' => '壁'],
            ['code' => '5', 'name' => '床'],
            ['code' => '6', 'name' => '全室'],
            ['code' => '7', 'name' => 'その他'],
        ];
        $checked_interior = RelationInterior::getDataByArticleId($user->company_id, $article->building_id);

        if (count($checked_interior) > 0) {
            foreach ($interior as &$row) {
                if (in_array($row['code'], $checked_interior)) {
                    $row['checked'] = 1;
                }
            }
        }
        $data['interior'] = $interior;


        // 学校データの取得
        $disp_school = "";
        // 学校データの取得
        $disp_school = "";
        if (isset($mansion->primary_school_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->primary_school_school);
            if (request()->get("debug")) {
                dd($mansion->primary_school_school);
            }
            $mansion->primary_school_name = $school_tmp->name ?? '';
            if (isset($mansion->primary_school_distance)) {
                $mansion->primary_school_time = ceil($mansion->primary_school_distance / 80);
            }
        }
        if (isset($mansion->primary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->primary_school2_school);
            $mansion->primary_school_name2 = $school_tmp->name ?? '';
            if (isset($mansion->primary_school2_distance)) {
                $mansion->primary_school_time2 = ceil($mansion->primary_school2_distance / 80);
            }
        }

        if (isset($mansion->secondary_school_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->secondary_school_school);
            $mansion->secondary_school_name = $school_tmp->name  ?? '';;
            if (isset($mansion->secondary_school_distance)) {
                $mansion->secondary_school_time = ceil($mansion->secondary_school_distance / 80);
            }
        }
        if (isset($mansion->secondary_school2_school)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->secondary_school2_school);
            $mansion->secondary_school_name2 = $school_tmp->name  ?? '';;
            if (isset($mansion->secondary_school2_distance)) {
                $mansion->secondary_school_time2 = ceil($mansion->secondary_school2_distance / 80);
            }
        }
        if (isset($mansion->other_primary_school_2)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->other_primary_school_2);
            if(isset($school_tmp))
            $mansion->other_primary_school_name = $school_tmp->name;
            else $mansion->other_primary_school_name = $mansion->other_primary_school_2;
            if (isset($mansion->other_primary_school_3)) {
                $mansion->other_primary_school_time = ceil($mansion->other_primary_school_3 / 80);
            }
        }

        if (isset($mansion->other_secondary_school_2)) {
            $school_tmp = MstSchool::getSchoolByCode($mansion->other_secondary_school_2);
            if(isset($school_tmp))
            $mansion->other_secondary_school_name = $school_tmp->name;
            else $mansion->other_secondary_school_name = $mansion->other_secondary_school_2;
            if (isset($mansion->other_secondary_school_3)) {
                $mansion->other_secondary_school_time = ceil($mansion->other_secondary_school_3 / 80);
            }
        }


        $article->event_day = $article->events()->select("event_day")->pluck("event_day")->toArray();

        if($mansion->land_right == 2 or $mansion->land_right == 3){
            if($mansion->leasehold_period_year1 != null && $mansion->leasehold_period_month1 != null) {
                $dt = Carbon::create($mansion->leasehold_period_year1, $mansion->leasehold_period_month1)->lastOfMonth();
                $now = Carbon::now()->firstOfMonth();
                $df_new = $dt->diff($now);
                $mansion->leasehold_period_year = $df_new->format('%Y');
                $mansion->leasehold_period_month = $df_new->format('%m');
            }
        }

        $data['mansion'] = $mansion;
        $data['article'] = $article;
        $data['public_portal'] = $article->portalPublic();

        $messArray = [];
        if ($article->name == null) {
            $messArray['name_article'] = 'マンション名は必須項目です。';
        }
        if ($article->price == null) {
            $messArray['price'] = '物件価格は必須項目です。';
        }
        if ($article->total_area_val == null) {
            $messArray['total_area_val'] = '専有面積は必須項目です。';
        }
        if ($article->company_manner == null) {
            $messArray['company_manner'] = '取引態様は必須項目です。';
        }
        if ($article->shop == null) {
            $messArray['shop'] = '物件取扱店舗名は必須項目です。';
        }
        if ($article->management == 2) {
            $messArray['management'] = '管理費は必須項目です。';
        }
        if ($article->repair == 2) {
            $messArray['repair'] = '修繕積立金は必須項目です。';
        }
        if ($article->move_in == 0) {
            $messArray['move_in'] = '引渡しは必須項目です。';
        }

        if ((is_null($article->another_cost1) && !empty($article->another_cost_unit1)) || (!is_null($article->another_cost1) && empty($article->another_cost_unit1))) {
            $messArray['another_cost1'] = 'その他諸費用１を入力してください。';
        }

        if ((is_null($article->another_cost2) && !empty($article->another_cost_unit2)) || (!is_null($article->another_cost2) && empty($article->another_cost_unit2))) {
            $messArray['another_cost2'] = 'その他諸費用２を入力してください。';
        }

        if ($article->balcony_area == 1 && ($article->balcony_direction == 0 || $article->balcony_area_val === null)) {
            $messArray['balcony_area'] = 'バルコニー面積は必須項目です。';
        }

        if ($article->loof_balcony_area == 1 &&
            ((!empty($article->loof_balcony_area_val) && !is_numeric($article->loof_balcony_area_val)) || empty($article->loof_balcony_area_val))) {
            $messArray['loof_balcony_area_val'] = 'ルーフバルコニー面積を入力してください。';
        } elseif ( ((!empty($article->loof_balcony_area_cost) && !is_numeric($article->loof_balcony_area_cost)) ||
            (empty($article->loof_balcony_area_cost) && !empty($article->loof_balcony_area_unit)))) {
            $messArray['loof_balcony_area_val'] = 'ルーフバルコニー金額を入力してください。';
        }

        if ($article->garden_area == 1 &&
            ((!empty($article->garden_area_val) && !is_numeric($article->garden_area_val)) ||
                empty($article->garden_area_val))) {
            $messArray['garden_area_val'] = '専用庭面積を入力してください。';
        } elseif (((!empty($article->garden_area_cost) && !is_numeric($article->garden_area_cost)) ||
            (empty($article->garden_area_cost) && !empty($article->garden_area_unit)))) {
            $messArray['garden_area_val'] = '専用庭金額を入力してください。';
        }


        if ($article->terrace_area == 1 &&
            ((!empty($article->terrace_area_val) && !is_numeric($article->terrace_area_val)) ||
                empty($article->terrace_area_val))) {
            $messArray['terrace_area_val'] = 'テラス面積を入力してください。';
        } elseif (((!empty($article->terrace_area_cost) && !is_numeric($article->terrace_area_cost)) ||
            (empty($article->terrace_area_cost) && !empty($article->terrace_area_unit)))) {
            $messArray['terrace_area_val'] = 'テラス金額を入力してください。';
        }

        if (empty($article->whereabouts) && empty($article->maisonette) && empty($article->maisonette_from) && empty($article->maisonette_to)) {
            $messArray['whereabouts'] = '階数は必須項目です。';
        }

        $data['messArray'] = $messArray;
        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        foreach ($facility as &$row) {
            $row->kind_name = MstFacilityType::find($row->kind)->name ?? '';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;
        $data['saved'] = $request->saved ?? '';

        $user = Auth::user();
        $data['store'] = MstStore::getDataByCode($user->company_id, $article->shop);
        $data['store_user'] = MstStore::getDataByCode($user->company_id, $user->store_id);

        return view('admin.pages.edit-room', $data);
    }

    /**
     * マンション情報ー編集登録
     */
    public function editRoom(RoomPost $request, CompanyApiService $apiService)
    {
        $user = Auth::user();

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();

        if ($article->price != $request->get("price")) {
            $history_data = [];
            $history_data['company_id'] = $user->company_id;
            $history_data['article_id'] = $article->building_id;
            $history_data['price'] = $request->get("price");
            $history_data['regist_date'] = date('Y-m-d');
            $history = new RelationPriceHistory;
            $history->fill($history_data)->save();
        }

        $all = $request->all();

        if (!isset($all['reservation'])) {
            $all['reservation'] = 0;
        }
        if (!isset($all['revenue'])) {
            $all['revenue'] = 0;
        }
        if (!isset($all['occupied'])) {
            $all['occupied'] = 0;
        }
        if (!isset($all['original1'])) {
            $all['original1'] = 0;
        }
        if (!isset($all['original2'])) {
            $all['original2'] = 0;
        }
        if (!isset($all['original4'])) {
            $all['original4'] = 0;
        }
        if (!isset($all['maisonette'])) {
            $all['maisonette'] = 0;
        }
        if ($all['own_company'] == 2) {

            $all['disp'] = 1;

            // 親マンションも本登録
            Article::where('building_id', $request->mid)->where('company_id', '=', $user->company_id)->update(['provisional' => 0, 'own_company' => 2]);
        } else {
            $all['disp'] = 0;
        }
        $all['provisional'] = 0;

        if ($all['event_schedule'] == 3) {
            $all['event_day'] = implode(',', $all['event_day']);
        } else {
            $all['event_day'] = null;
        }

        if ($all['event_schedule'] != 4) {
            $all['from_event'] = null;
            $all['to_event'] = null;
        }

        if (isset($all["law_restriction"])) {
            unset($all["law_restriction"]);
        }

        if ($user->company_id == 1) {
            if ($all['status'] == 4 || $all['status'] == 5) {
                $all['own_company'] = 1;
                $all['suumo'] = 1;
                $all['homes'] = 1;
                $all['athome'] = 1;
            }
        }

        if (!is_numeric($all['another_cost1'])) {
            $all['another_cost1'] = null;
        }

        if (!is_numeric($all['another_cost2'])) {
            $all['another_cost2'] = null;
        }
        $mansion = $this->getDataById($request->mid);
        if(!empty($mansion)){
            $all['floor'] = $mansion->floor;
            $all['underground'] = $mansion->underground;
            if($user->company_id == 3){
                $all['age_year'] = $mansion->age_year;
                $all['age_month'] = $mansion->age_month;
                $all['construction'] = $mansion->construction;
                $all['construction_sub'] = $mansion->construction_sub;
                $all['section'] = $mansion->section;
                $all['kokudoho'] = $mansion->kokudoho;
                $all['use_area'] = $mansion->use_area;
                $all['land_use'] = $mansion->land_use;
                $all['land_use2'] = $mansion->land_use2;
                $all['management_form'] = $mansion->management_form;
                $all['gas'] = $mansion->gas;
                $all['main_traffic_line'] = $mansion->main_traffic_line;
                $all['main_traffic_station'] = $mansion->main_traffic_station;
                $all['main_traffic'] = $mansion->main_traffic;
                $all['main_traffic_time'] = $mansion->main_traffic_time;
                $all['main_traffic_bus_time'] = $mansion->main_traffic_bus_time;
                $all['main_traffic_bus'] = $mansion->main_traffic_bus;
                $all['main_traffic_bus_walk'] = $mansion->main_traffic_bus_walk;
                $all['sub_traffic1_line'] = $mansion->sub_traffic1_line;
                $all['sub_traffic1_station'] = $mansion->sub_traffic1_station;
                $all['sub_traffic1'] = $mansion->sub_traffic1;
                $all['sub_traffic1_time'] = $mansion->sub_traffic1_time;
                $all['sub_traffic1_bus_time'] = $mansion->sub_traffic1_bus_time;
                $all['sub_traffic1_bus'] = $mansion->sub_traffic1_bus;
                $all['sub_traffic1_bus_walk'] = $mansion->sub_traffic1_bus_walk;
                $all['sub_traffic2_line'] = $mansion->sub_traffic2_line;
                $all['sub_traffic2_station'] = $mansion->sub_traffic2_station;
                $all['sub_traffic2'] = $mansion->sub_traffic2;
                $all['sub_traffic2_time'] = $mansion->sub_traffic2_time;
                $all['sub_traffic2_bus_time'] = $mansion->sub_traffic2_bus_time;
                $all['sub_traffic2_bus'] = $mansion->sub_traffic2_bus;
                $all['sub_traffic2_bus_walk'] = $mansion->sub_traffic2_bus_walk;
                $all['total_unit'] = $mansion->total_unit;
                $all['primary_school_city'] = $mansion->primary_school_city;
                $all['primary_school_school'] = $mansion->primary_school_school;
                $all['primary_school_distance'] = $mansion->primary_school_distance;
                $all['primary_school2_city'] = $mansion->primary_school2_city;
                $all['primary_school2_school'] = $mansion->primary_school2_school;
                $all['primary_school2_distance'] = $mansion->primary_school2_distance;
                $all['primary_school3_city'] = $mansion->primary_school3_city;
                $all['primary_school3_school'] = $mansion->primary_school3_school;
                $all['primary_school3_distance'] = $mansion->primary_school3_distance;
                $all['secondary_school_city'] = $mansion->secondary_school_city;
                $all['secondary_school_school'] = $mansion->secondary_school_school;
                $all['secondary_school_distance'] = $mansion->secondary_school_distance;
                $all['secondary_school2_city'] = $mansion->secondary_school2_city;
                $all['secondary_school2_school'] = $mansion->secondary_school2_school;
                $all['secondary_school2_distance'] = $mansion->secondary_school2_distance;
                $all['secondary_school3_city'] = $mansion->secondary_school3_city;
                $all['secondary_school3_school'] = $mansion->secondary_school3_school;
                $all['secondary_school3_distance'] = $mansion->secondary_school3_distance;
                $all['pet'] = $mansion->pet;
                $all['pet_count'] = $mansion->pet_count;
            }
        }

        $result = $article->fill($all)->save();

        if (isset($request->id)) {
            // 温泉
            RelationSpring::where('article_id', $request->id)->delete();
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 内装
            RelationInterior::where('article_id', $request->id)->delete();
            if (isset($request->interior_place)) {
                foreach ($request->interior_place as $row) {
                    RelationInterior::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }

            // 業者削除
            $del_vendor_list = explode(',', $request->delete_vendor_list);

            foreach ($del_vendor_list as $del_id) {
                RelationVendorArticle::where('article_id', '=', $article->building_id)->where('vendor_id', $del_id)->delete();
            }

            // 業者登録
            $vendor_list = $request->vendor_id;
            foreach ($vendor_list as $key => $val) {
                if (empty($val)) {
                    continue;
                }

                $relation = RelationVendorArticle::getArticleRelation($article->building_id, $val);
                $vendor = [];
                $vendor['article_id'] = $article->building_id;
                $vendor['vendor_id'] = $val;
                $vendor['company_id'] = $user->company_id;
                $vendor['charge'] = $request->vendor_charge[$key];
                $vendor['flyer'] = $request->flyer[$key];
                $vendor['freepaper'] = $request->freepaper[$key];
                $vendor['house_hp'] = $request->house_hp[$key];
                $vendor['portal'] = $request->portal[$key];
                $vendor['signboard'] = $request->signboard[$key];
                $vendor['ad_conf_day'] = $request->ad_conf_day[$key];
                $vendor['manner'] = $request->manner[$key];
                $vendor['home_note'] = $request->home_note[$key];
                if (is_null($relation)) {
                    $vendor_obj = new RelationVendorArticle;
                    $vendor_obj->fill($vendor)->save();

                } else {
                    RelationVendorArticle::where('id', $relation->id)->update($vendor);
                }
            }
        }

        $this->createOriginal($article, $request);

        if ($user->isOwnerOfSaiKyoto()) {
            self::setPriceCustomContent($article);
        }

        $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        $dataSend['spring_kind']  = $request->spring_kind;
        $dataSend['interior_place']  = $request->interior_place;
        $dataSend['law_restriction']  = $request->law_restriction;
        $dataSend['other_restriction']  = $request->other_restriction;
        $dataSend['event_day']  = $request->event_schedule != 3 ? [null] : $request->event_day;
        $dataSend['vendor_list'] = RelationVendorArticle::where('article_id', $request->id)->get();
        $dataSend['delete_vendor_list'] = $request->delete_vendor_list;
        $dataSend['original'] = $request->original;
        $apiService->editRoom($article->building_id, $dataSend);

        // 保存せずに画像編集画面へ
        if ($request->toimage == 1) {
            $URL = url('');
            header('Location: ' . $URL . '/admin/registImage/' . $request->id);
            die();
        }
        if ($request->duplicate_info_house == 1) {
            $URL = url('');
            header('Location: ' . route("showCopyRoom", ['mid' => $article->mansion_id]) . '?copy=' . $article->building_id);
            die();
        }
        if ($request->toimageportal == 1) {
            $URL = url('');
            header('Location: ' . route("admin.portal.image", $article->building_id));
            die();
        }
        if ($request->detailportal == 1) {
            header('Location: ' . route("admin.portal.image", $article->building_id).'?detail=1');
            die();
        }

        if ($article->suumo == 2) {
            Artisan::call('batch:test', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->homes == 2) {
            Artisan::call('batch:test2', ['id' => $article->building_id, 'cid' => $user->company_id]);
        }

        if ($article->athome == 2) {
            try {
                Artisan::call('batch:athome', ['id' => $article->building_id, 'cid' => $user->company_id]);
            } catch (\Exception $exception) {
            }
        }

        // 学校に紐づく件数、駅に紐づく件数の更新
        $this->setCount();
        if ($result) {
            $mansion = $article->getMansion();
            $mansion->close_date = $article->close_date;
            if(isset($all['original']) && isset($all['original'][3])){
                $mansion->original_add = $all['original'][3];
            } else {
                $mansion->original_add = '';
            }
            if ($user->isOwnerOfSaiKyoto()) {
                // $this->insertArticleIntoSai($article, false, $mansion);
            }
            $provisional = '';
            if(!empty(request()->get('provisional'))){
                $provisional = '?provisional=1';
            }
            $data = [];
            $data['action'] = route('showEditRoom', ['mid' => $article->mansion_id, 'id' => $request->id]).$provisional;

            return view('admin.pages.redirect', $data);
        }
    }


    /**
     * マンション情報ー編集登録画面の表示
     */
    public function showTopLotForm(Request $request)
    {
        $old = $request->session()->all();

        $cookie = Cookie::forget('current_params');
        // マスターデータの取得
        $this->parentProperty = 3;

        $data = $this->getMasterData($request->all(), null, $old, 4);
        $data['active'] = "top";
        $data['search'] = $request->all();

        if (!empty($request->all())) {
            $request->merge(['url_search' => url()->current()]);
            $cookie = cookie('current_params', json_encode($request->all(), 10));
            $list = Article::getLotDataByCondition($request);
            foreach ($list as &$row) {
                $row->count = Article::getCountBySaleNo($row->building_id);

                $row->relation_article = Article::getDataBySaleNo($row->building_id);
                foreach ($row->relation_article as $info) {
                    $vendor = Vendor::getDataByArticleId($info->building_id);
                    $info->vendor = $vendor->name ?? '';
                    if ($info->property == 1) {
                        $info->url = '/admin/editLand/' . $info->building_id;
                    } elseif ($info->property == 2) {
                        $info->url = '/admin/editLand/' . $info->building_id;
                    } elseif ($info->property == 3) {
                        $info->url = '/admin/editLand/' . $info->building_id;
                    } elseif ($info->property == 4) {
                        $info->url = '/admin/editHouse/' . $info->building_id;
                    } elseif ($info->property == 5) {
                        $info->url = '/admin/editHouse/' . $info->building_id;
                    }

                    if (isset($info->status)) {
                        $info->status_name = MstStatus::find($info->status)->name ?? '';
                    }
                }
            }
            $data['list'] = $list;
        }
        return response()->view('admin.pages.top-lot', $data)->withCookie($cookie);
    }

    /**
     * マンション情報ー編集登録画面の表示
     */
    public function showPostTopLotForm(Request $request)
    {
        $old = $request->session()->all();

        // マスターデータの取得
        $this->parentProperty = 3;
        $data = $this->getMasterData($request->all(), null, $old, 4);
        $data['active'] = "top";
        $data['search'] = $request->all();
        if (!empty($request->all())) {
            $request->merge(['url_search' => url()->current()]);
            $cookie = cookie('current_params', json_encode($request->all(), 10));

            $list = Article::getLotDataByCondition($request);
            foreach ($list as &$row) {
                $row->count = Article::getCountBySaleNo($row->building_id);

                $row->relation_article = Article::getDataBySaleNo($row->building_id);
                foreach ($row->relation_article as $info) {
                    $vendor = Vendor::getDataByArticleId($info->building_id);
                    $info->vendor = $vendor['name'];
                    if ($info->property == 1) {
                        $info->url = '/admin/editLand/' . $info->building_id;
                    } elseif ($info->property == 2) {
                        $info->url = '/admin/editLand/' . $info->building_id;
                    } elseif ($info->property == 3) {
                        $info->url = '/admin/editLand/' . $info->building_id;
                    } elseif ($info->property == 4) {
                        $info->url = '/admin/editHouse/' . $info->building_id;
                    } elseif ($info->property == 5) {
                        $info->url = '/admin/editHouse/' . $info->building_id;
                    }

                    if (isset($info->status)) {
                        $info->status_name = MstStatus::find($info->status)->name ?? '';
                    }
                }
            }
            $data['list'] = $list;
        }
        return response()->view('admin.pages.top-lot', $data)->withCookie($cookie);
    }

    /**
     * 分譲地情報ー新規登録画面の表示
     */
    public function showRegistrationLotForm(Request $request)
    {
        $old = $request->session()->all();

        // マスターデータの取得
        $this->parentProperty = 4;
        $data = $this->getMasterData(null, null, $old, 4);
        $data['pref'] = Arr::prepend(($data['pref'] ?? []), ['code' => null, 'name' => '未選択']);

        $data["customs"] = $this->getCustomData();

        $data['active'] = "regist";

        $user = Auth::user();
        $data['company_id'] = $user->company_id;
        if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }

        return view('admin.pages.regist-lot', $data);
    }

    /**
     * 分譲地情報ー新規登録
     */
    public function registerLot(LotPost $request, CompanyApiService $apiService)
    {
        $this->parentProperty = 4;

        $user = Auth::user();
        $building_id = Article::getMaxNo();
        if (empty($building_id)) {
            $building_id = 0;
        }

        // 登録
        $article = new Article;
        $all = $request->all();

        $all['disp'] = 1;
        $all['provisional'] = 0;
        $all['building_id'] = $building_id + 1;
        $result = $article->fill($all)->save();

        if (isset($article->building_id)) {
            // 温泉
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }
        }

        if ($result) {
            $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article->building_id)->first();
            $dataSend['spring_kind']  = $request->spring_kind;
            $dataSend['law_restriction']  = $request->law_restriction;
            $dataSend['other_restriction']  = $request->other_restriction;
            $dataSend['event_day']  = $request->event_day;

            $apiService->registLot($dataSend);
            // 保存して画像編集画面へ
            if ($request->toimage == 1) {
                $URL = url('');
                header('Location: ' . $URL . '/admin/registImage/' . $article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditLot', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * 分譲地情報ー編集登録画面の表示
     */
    public function showEditLotForm(Request $request)
    {
        $old = $request->session()->all();

        $this->parentProperty = 4;

        $article = $this->getDataById($request->id);

        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 4);

        $data["customs"] = $this->getCustomData();
        $messArray = [];
        if ($article->main_traffic_line == null && $article->else_traffic_line == null) {
            $messArray['main_traffic_line'] = '主要交通の路線は必須項目です。';
        }
        if ($article->city_plan > 1 && $article->building_rate == '') {
            $messArray['building_rate'] = '建ぺい率は必須項目です。';
        }
        if ($article->city_plan > 1 && $article->volume_rate == '') {
            $messArray['volume_rate'] = '容積率は必須項目です。';
        }
        $data['article'] = $article;
        $data['messArray'] = $messArray;
        $data['saved'] = $request->saved ?? '';
        if (auth()->user()->isOwnerOfSaiKyoto()) {
            $data = $this->getDataSaiKyoto($data);
        }
        $lots = Article::getLotList($request->id);
        $floor_type_list = MstFloorType::getData();
        $floor_type = [];
        foreach ($floor_type_list as $row) {
            $floor_type[$row['code']] = $row['name'];
        }
        foreach ($lots as &$lot) {
            $lot->floor_plan_name = MstFloorType::find($lot->floor_plan_type)->name ?? '';
            if (isset($lot->floor_plan_type)) {
                $lot->floor_plan_text = $lot->floor_plan . $floor_type[$lot->floor_plan_type];
            }
        }
        $data['lots'] = $lots;

        return view('admin.pages.edit-lot', $data);
    }

    /**
     * 分譲地情報ー編集登録
     */
    public function editLot(LotPost $request, CompanyApiService $apiService)
    {
        $user = Auth::user();

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        $all = $request->all();

        $all['disp'] = 1;
        $all['provisional'] = 0;
        $result = $article->fill($all)->save();

        if (isset($request->id)) {
            // 温泉
            RelationSpring::where('article_id', $request->id)->delete();
            if (isset($request->spring_kind)) {
                foreach ($request->spring_kind as $row) {
                    RelationSpring::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // 法律上の制限
            RelationLawrestriction::where('article_id', $request->id)->delete();
            if (isset($request->law_restriction)) {
                foreach ($request->law_restriction as $row) {
                    RelationLawrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // その他制限事項
            RelationOtherrestriction::where('article_id', $request->id)->delete();
            if (isset($request->other_restriction)) {
                foreach ($request->other_restriction as $row) {
                    RelationOtherrestriction::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'item_id' => $row]);
                }
            }

            // イベント日付
            RelationEventDay::where('article_id', $request->id)->delete();
            if (isset($request->event_day)) {
                foreach ($request->event_day as $row) {
                    RelationEventDay::create(['company_id' => $user->company_id, 'article_id' => $article->building_id, 'event_day' => $row]);
                }
            }
        }

        $apiService->editLot($request->id, $all);

        // 保存せずに画像編集画面へ
        if ($request->toimage == 1) {
            $URL = url('');
            header('Location: ' . $URL . '/admin/registImage/' . $request->id);
            die();
        }

        if ($result) {
            $data = [];
            $data['action'] = route('showEditLot', ['id' => $article->building_id]);


            return view('admin.pages.redirect', $data);
        }
    }

    /**
     * 分譲地情報ー編集登録画面の表示
     */
    public function showCopyLotForm(Request $request)
    {
        $old = $request->session()->all();

        $this->parentProperty = 4;

        $article = $this->getDataById($request->copy);

        if ($article->property != 1 && $article->property != 2 && $article->property != 3 &&
            $article->property != 4 && $article->property != 5) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }

        $article->building_id = null;
        $article->article_name = null;

        // マスターデータの取得
        $data = $this->getMasterData($article, null, $old, 4);
        $data['article'] = $article;
        $data['copy_id'] = $request->copy;
        $data["customs"] = $this->getCustomData();

        $user = Auth::user();
        $data['company_id'] = $user->company_id;

        return view('admin.pages.copy-lot', $data);
    }

    public function copyLot(LotPost $request)
    {
        $this->parentProperty = 4;

        $user = Auth::user();
        $building_id = Article::getMaxNo();
        if (empty($building_id)) {
            $building_id = 0;
        }

        // 登録
        $article = new Article;
        $all = $request->all();
        $all['disp'] = 1;
        $all['provisional'] = 0;
        $all['building_id'] = $building_id + 1;
        $result = $article->fill($all)->save();

        if (isset($article->building_id)) {
            // 元の物件をこの分譲地に登録
            Article::where('building_id', $request->copy)->where('company_id', '=', $user->company_id)->update(['sale_no' => $article->building_id]);

        }

        if ($result) {
            // 保存して画像編集画面へ
            if ($request->toimage == 1) {
                $URL = url('');
                header('Location: ' . $URL . '/admin/registImage/' . $article->building_id);
                die();
            }

            $data = [];
            $data['action'] = route('showEditLot', ['id' => $article->building_id]);
            return view('admin.pages.redirect', $data);
        }
    }


    /**
     * 画像情報ー編集登録画面の表示
     */
    public function showRegistrationImageForm(Request $request)
    {
        header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
        header("Pragma: no-cache");
        header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
        $user = Auth::user();
        $data = [];
        TempImage::where('article_id', '=', $request->id)->delete();
        $article = $this->getDataById($request->id);
        $referer = $_SERVER['HTTP_REFERER'] ?? null;

        if (isset($request->referer)) {
            $referer = $request->referer;
        }
        $property = $article->property;

        if (empty($property)) {
            $back = route('showEditRoom', ['mid' => $article->mansion_id, 'id' => $request->id]);
        } elseif ($property < 4) {
            $back = route('showEditLand', ['id' => $request->id]);
        } elseif ($property < 6) {
            $back = route('showEditHouse', ['id' => $request->id]);
        }else{
            $back = route('showEditMansion', ['id' => $request->id]);
        }
        if ($property === MstPropertyType::LOT_ID){
            $back = route('showEditLot', ['id' => $request->id]);
        }

        /*$back = str_replace(url(''), '', $referer);

        if (strpos($referer, '/admin/registLand') !== false) {
            $back = route('showEditLand', ['id' => $request->id]);
        }*/

        if (is_null($referer) || (
                strpos($referer, route('showRegistLand')) === false && strpos($referer, route('showEditLand', ['id' => $request->id])) === false &&
                strpos($referer, route('showRegistHouse')) === false && strpos($referer, route('showEditHouse', ['id' => $request->id])) === false &&
                strpos($referer, route('regist-mansion')) === false && strpos($referer, route('showEditMansion', ['id' => $request->id])) === false &&
                strpos($referer, route('regist-room', ['id' => $article->mansion_id])) === false && strpos($referer, route('showEditRoom', ['mid' => $article->mansion_id, 'id' => $request->id])) === false &&
                strpos($referer, route('regist-lot')) === false && strpos($referer, route('showEditLot', ['id' => $request->id])) === false &&
                strpos($referer, route('showCopyLand')) === false && strpos($referer, route('showCopyHouse')) === false &&
                strpos($referer, route('copy-lot')) === false && strpos($referer, route('showRegistImage', ['id' => $request->id])) === false) &&
                strpos($referer, route('admin.portal.image.update', ['id' => $article->building_id])) === false &&
                strpos($referer, route('showCopyRoom', ['mid' => $article->mansion_id])) === false) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }

        $data['back'] = $back;
        $data['referer'] = $referer;
        $data['saved'] = $request->saved ?? '';
        $data['article_id'] = $request->id;

        $old = $request->session()->all();


        $data['article'] = $article;

        $property_name = $this->getPropertyName($article->property, $article->property_sub);
        $title = "物件登録-" . $property_name . "-画像登録「{$article->article_name}」";
        $data['main_title'] = $title;

        $disp_flag = 1;
        if ($article->property == 6 || $article->property == 7) {
            $disp_flag = 2;
        } else if ($article->property == 99) {
            $disp_flag = 3;
        }

        if (isset($article->file_path2)){
            $article->file_path2 = str_replace('public', '/storage', $article->file_path2);
        }

        //dd($article);

        $data["is_room"] = false;

        $data['disp_flag'] = $disp_flag;

        // 業者の取得
        $vendor = RelationVendorArticle::getVendorDataByRainsNo($request->id);
        $data['vendor'] = $vendor;

        // 施設の取得
        $facility = RelationArticleFacility::getFacilityDataByRainsNo($request->id);
        if (empty($article->property)) {
            $data["is_room"] = true;
            $facility = RelationArticleFacility::getFacilityDataByRainsNo($article->mansion_id);
        }

        foreach ($facility as &$row) {
            $row->kind_name = MstFacilityType::where('code', $row->kind)->first()->name ?? '';
            $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
        }
        $data['facility'] = $facility;

        $data['image_kind'] = [
            ['code' => 1, 'name' => '区画図'],
            ['code' => 2, 'name' => '間取り'],
            ['code' => 3, 'name' => '参考プラン'],
//            ['code' => 0, 'name' => '未選択'],
        ];

        if (empty($article->property)) {
            $data['photo_property'] = [];
            $arr = config('const.PHOTO_PROPERTY_BUKKEN_ROOM');
            foreach ($arr as $key => $value) {
                $item = ['code' => $key+1, 'name' => $value];
                array_push($data['photo_property'], $item);
            }
            array_splice($data['photo_property'], 7, 0, [['code' => 23, 'name' => 'サービスルーム']]);
        } elseif ($article->property < 4) {
            $data['photo_property'] = [];
            $arr = config('const.PHOTO_PROPERTY_BUKKEN_LAND');
            foreach ($arr as $key => $value) {
                $item = ['code' => $key+1, 'name' => $value];
                array_push($data['photo_property'], $item);
            }
        } elseif ($article->property < 6) {
            $data['photo_property'] = [];
            $arr = config('const.PHOTO_PROPERTY_BUKKEN_HOUSE');
            foreach ($arr as $key => $value) {
                $item = ['code' => $key+1, 'name' => $value];
                array_push($data['photo_property'], $item);
            }
            array_splice($data['photo_property'], 12, 0, [['code' => 35, 'name' => 'サービスルーム']]);
        } else {
            $data['photo_property'] = [];
            $arr = config('const.PHOTO_PROPERTY_BUKKEN_MANSION');
            foreach ($arr as $key => $value) {
                $item = ['code' => $key+1, 'name' => $value];
                array_push($data['photo_property'], $item);
            }
        }


        // イベント予約
        $data['vendor_building_photo'] = [
            ['code' => 1, 'name' => '優先使用'],
            ['code' => 2, 'name' => '不使用'],
        ];

        $facility_area = Facility::getFacilityArea($user->company_id);
        $data['facility_area'] = $facility_area;
        $data['facility_property'] = MstFacilityType::getData();
        $data['facility_distance'] = [
            ['code' => 0, 'name' => 0],
            ['code' => 5, 'name' => 5],
            ['code' => 10, 'name' => 10],
            ['code' => 15, 'name' => 15],
            ['code' => 20, 'name' => 20],
            ['code' => 25, 'name' => 25],
            ['code' => 30, 'name' => 30],
            ['code' => 35, 'name' => 35],
            ['code' => 40, 'name' => 40],
            ['code' => 45, 'name' => 45],
            ['code' => 50, 'name' => 50],
            ['code' => 55, 'name' => 55],
            ['code' => 60, 'name' => 60],
            ['code' => 65, 'name' => 65],
        ];
        return view('admin.pages.edit-image', $data);
    }

    /**
     * 土地情報ー編集登録
     */
    public function registImage(Request $request, CompanyApiService $apiService, ImageService $imageService)
    {
        //dd($request->all());

        $user = Auth::user();

        // 登録
        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        if (is_null($article)) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }
        $all = $request->all();

        Article::where('building_id', $request->id)->where('company_id', '=', $user->company_id)->update([
            'floor_file_type' => $request->floor_file_type,
            'sheet_file_type' => $request->sheet_file_type,
            'floor_file_comment' => $request->floor_file_comment,
            'vertical' => $request->vertical
        ]);

        if (isset($request->id)) {
            // 間取り画像
            if (isset($request->floor_file_delete_flg)) {
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['floor_file_path' => '']);
            }
            if(isset($article->floor_file_path) && $article->floor_file_path != ''){
                $explodePath = explode('/', $article->floor_file_path);
                if (File::exists(storage_path('app/'.$article->floor_file_path))){
                    $imageService->resizeHorizontalFloor(file_get_contents(storage_path('app/'.$article->floor_file_path)), $explodePath[count($explodePath) - 1]);
                }
            }

            if (isset($request->file_single_input)) {
                $extension = $request->file_single_input->getClientOriginalExtension();
                $image_url = $request->file_single_input->storeAs('public/company_'.$user->company_id.'/floor', 'floor_image_' . $article->building_id . '.' . $extension);
                $imageService->resizeHorizontalFloor($request->file_single_input, 'floor_image_' . $article->building_id . '.' . $extension);
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['floor_file_path' => $image_url]);
                if($user->company_id == 1){
                    $this->uploadRemoteMic($image_url);
                }
            }

            if (isset($request->file_single_input_consent)) {
                $extension = $request->file_single_input_consent->getClientOriginalExtension();


                $query = Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id);
                $building = $query->first();

                //delete exist file
                $deletePath = $building->consent_form;
                if(isset($deletePath) && $deletePath != ''){
                    Storage::delete($deletePath);
                }
                $image_url = $request->file_single_input_consent->storeAs('public/company_'.$user->company_id.'/consent', 'consent_form_' . $article->building_id . '.' . $extension);

                //resize if img file
                if($extension != 'pdf'){
                    $imageService->resizeHorizontalFloor($request->file_single_input_consent, 'consent_form_' . $article->building_id . '.' . $extension);
                }

                //update new path
                $query->update(['consent_form' => $image_url]);

                if($user->company_id == 1){
                    $this->uploadRemoteMic($image_url);
                }
            }

            if (isset($request->floor_file_delete_flg_consent)) {
                $query = Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id);
                $building = $query->first();
                //check & delete file storage
                $deletePath = $building->consent_form;
                Storage::delete($deletePath);
                //set null consent_form
                $query->update(['consent_form' => '']);
            }

            if (isset($request->floor_file_delete_flg4)) {
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)
                    ->update(['file_path2' => '', 'file_type2' => '']);
            }

            if (isset($request->file_single_input4)) {
                $extension = $request->file_single_input4->getClientOriginalExtension();
                $image_url = $request->file_single_input4->storeAs('public/company_'.$user->company_id.'/floor', 'floor_image2_' . $article->building_id . '.' . $extension);
                $imageService->resizeVerticalFloor($request->file_single_input4, 'floor_image2_' . $article->building_id . '.' . $extension);

                Article::where('building_id', $article->building_id)
                    ->where('company_id', '=', $user->company_id)
                    ->update(['file_path2' => $image_url, 'file_type2' => $extension]);

                if($user->company_id == 1){
                    $this->uploadRemoteMic($image_url);
                }
            }


            // 間取り画像
            if (isset($request->floor_file_delete_flg2)) {
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['sheet_file_path2' => '']);
            }
            if (isset($request->file_single_input2)) {
                $extension = $request->file_single_input2->getClientOriginalExtension();
                $image_url = $request->file_single_input2->storeAs('public/company_'.$user->company_id.'/sheet', 'sheet_image_' . $article->building_id . '.' . $extension);
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['sheet_file_path2' => $image_url]);
                if($user->company_id == 1){
                    $this->uploadRemoteMic($image_url);
                }
            }

            // 間取り画像
            if (isset($request->floor_file_delete_flg3)) {
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['sheet_file_path3' => '']);
            }
            if (isset($request->file_single_input3)) {
                $extension = $request->file_single_input3->getClientOriginalExtension();
                $image_url = $request->file_single_input3->storeAs('public/company_'.$user->company_id.'/sheet', 'sub_sheet_image_' . $article->building_id . '.' . $extension);
                Article::where('building_id', $article->building_id)->where('company_id', '=', $user->company_id)->update(['sheet_file_path3' => $image_url]);
                if($user->company_id == 1){
                    $this->uploadRemoteMic($image_url);
                }
            }

            $photoCount = $request->photo_count ?? 0;
            $photos = RelationArticlePhoto::where('article_id', $article->building_id)->get();
            $photoIdsRemove = $photos->pluck('id')->toArray();
            for ($order = 0; $order < $photoCount; $order ++){
                $filePath = '';
                $fileType = '';
                $photoId = '';
                if (isset($request->{'article_photo_id'.$order})){
                    $photo = RelationArticlePhoto::find($request->{'article_photo_id'.$order});
                    $filePath = $photo->file_path ?? "";
                    $fileType = $photo->file_type ?? "";
                    $photoId = $request->{'article_photo_id'.$order};
                }

                if (isset($request->{'temp_photo_id' . $order})){
                    $photoId = '';
                    $photo = TempImage::find($request->{'temp_photo_id'.$order});
                    $filePath = $photo->file_path;
                    $fileType = $photo->file_type;
                    $photo->delete();
                }

                $photo_data = [
                    'article_id' => $article->building_id,
                    'file_path' => $filePath,
                    'file_type' => $fileType,
                    'file_disp' => 1,
                    'property_sub' => $request->{'photo_property_sub' . $order},
                    'memo'       => $request->{'photo_comment' . $order},
                    'company_id' => $article->company_id,
                    'order'      => $order
                ];
                if ($photoId != ''){
                    RelationArticlePhoto::where('id', $photoId)->update($photo_data);
                    if (($key = array_search($photoId, $photoIdsRemove)) !== false) {
                        unset($photoIdsRemove[$key]);
                    }
                }else {
                    RelationArticlePhoto::create($photo_data);
                }
            }

            if (count($photoIdsRemove) > 0)
                RelationArticlePhoto::whereIn('id', $photoIdsRemove)->delete();

           // dd($request->all());
            //////////////
  //          $tmp_image = TempImage::where('article_id', $article->building_id)->get();
//            $rlsArticlesId = [];

//            if (!empty($tmp_image)) {
//                $saved_photo_id = explode(',', $request->saved_photo_id);
//
//                $runk = count($saved_photo_id) - count($tmp_image);
//                foreach ($tmp_image as $key => $tg) {
//                    $photo_data = [
//                        'article_id' => $tg->article_id,
//                        'file_path' => $tg->file_path,
//                        'file_type' => $tg->file_type,
//                        'file_disp' => 0,
//                        'property_sub' => $request->{'photo_property_sub' . $runk},
//                        'memo'       => $request->{'photo_comment' . $runk},
//                        'company_id' => $tg->company_id,
//                        'order'      => $runk
//                    ];
//                    if (!empty($tg->relation_article_photo_id)) {
//                        $relationArticlePhoto = RelationArticlePhoto::where('id', $tg->relation_article_photo_id)->first();
//                        if (!empty($relationArticlePhoto)) {
//                            $relationArticlePhoto->update($photo_data);
//                        }
//                    } else {
//                        $art = RelationArticlePhoto::create($photo_data);
//                        array_push($rlsArticlesId, $art['id']);
//
//                    }
//                    TempImage::where('id', $tg->id)->delete();
//                    $runk++;
//                }
//            }
//            $request->merge(['rls_articles_id' => $rlsArticlesId]);
            // 写真
//            $this->updateImage($request, $article);

            // 施設削除
            $del_facility_list = explode(',', $request->delete_facility_list);
            foreach ($del_facility_list as $del_id) {
                RelationArticleFacility::where('article_id', '=', $article->building_id)->where('facility_id', $del_id)->delete();
            }

            // 施設登録
            $facility_id_list = $request->save_facility_id ?? [];
            if(!is_null($article->mansion_id)){
                RelationArticleFacility::where('article_id', '=', $article->building_id)->delete();
            }

            foreach ($facility_id_list as $key => $value) {
                if (is_null($value)) {
                    continue;
                }
                $relation = RelationArticleFacility::getArticleRelation($article->building_id, $value);
                $facility = [];
                $facility['article_id'] = $article->building_id;
                $facility['company_id'] = $user->company_id;
                $facility['facility_id'] = $value;
                $facility['distance'] = $request->save_facility_distance[$key];
                $facility['facility_area'] = $request->facility_area[$key];
                $facility['facility_property'] = $request->facility_property[$key];
                $facility['facility'] = $request->facility[$key];
                $facility["order"] = $key;
                $facility['time'] = ceil($request->save_facility_distance[$key] / 80);

                if (is_null($relation)) {
                    $facility_obj = new RelationArticleFacility;
                    $facility_obj->fill($facility)->save();

                } else {
                    RelationArticleFacility::where('id', $relation->id)->update($facility);
                }
            }
            if(in_array($article->property, [6,7])){
                $room = Article::getRoomList($article->building_id);

                foreach ($room as $ro) {
                    RelationArticleFacility::where('article_id', '=', $ro->building_id)->delete();
                    foreach ($facility_id_list as $key => $value) {
                        if (is_null($value)) {
                            continue;
                        }
                        $relation = RelationArticleFacility::getArticleRelation($ro->building_id, $value);
                        $facility = [];
                        $facility['article_id'] = $ro->building_id;
                        $facility['company_id'] = $user->company_id;
                        $facility['facility_id'] = $value;
                        $facility['distance'] = $request->save_facility_distance[$key];
                        $facility['facility_area'] = $request->facility_area[$key];
                        $facility['facility_property'] = $request->facility_property[$key];
                        $facility['facility'] = $request->facility[$key];
                        $facility["order"] = $key;
                        $facility['time'] = ceil($request->save_facility_distance[$key] / 80);

                        if (is_null($relation)) {
                            $facility_obj = new RelationArticleFacility;
                            $facility_obj->fill($facility)->save();

                        } else {
                            RelationArticleFacility::where('id', $relation->id)->update($facility);
                        }
                    }
                }
            }

        }

        $user = Auth::user();
        $history_data = [
            'company_id' => $user->company_id,
            'name' => '物件番号' . $article->building_id . "を更新しました。",
        ];
        $history = new History;
        $history->fill($history_data)->save();

        $facility_area = Facility::getFacilityArea($user->company_id);
        $data['facility_area'] = $facility_area;

        $data = [];
        $data['action'] = route('showRegistImage', ['id' => $article->building_id]);
        $data['referer'] = $request->referer;

        $dataSend = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $request->id)->first();
        $dataSend['tmp_image']  = RelationArticlePhoto::where('article_id', '=', $article->building_id)->whereNotNull('file_path')->get();
        $dataSend['save_facility_list'] = RelationArticleFacility::where('article_id', '=', $article->building_id)->get();
        $dataSend['del_photo_id'] = $request->del_photo_id;
        $dataSend['delete_facility_list'] = $request->delete_facility_list;

        $apiService->registImage($article->building_id, $dataSend);

        if ($request->toportal == 1 && $article->property < 6) {
            //$this->uploadPortalImage($article->building_id);
            //$this->uploadPortalFacility($article->building_id);
            header('Location: ' . route("admin.portal.image", [$article->building_id, 'saved' => 1]));
            die();
        }

        return view('admin.pages.redirect', $data);
    }
    public function uploadPortalImage($id)
    {
        $user = Auth::user();
        RelationPortalPhoto::where('article_id', '=', $id)->where('del', '=', 1)->delete();

        RelationPortalPhoto::where('article_id', '=', $id)->update(['del' => 1]);

        $list = RelationArticlePhoto::where('article_id', '=', $id)->where('company_id', '=', $user->company_id)->get();
        $check_room = Article::where('company_id', '=', $user->company_id)->where('building_id', $id)->first();
        if($check_room->floor_file_path != null){
            $article_id = $id;
            $property_sub = $check_room->floor_file_type;

            $photo_data = [
                'article_id' => $article_id,
                'file_type'  => '',
                'file_path' =>  $check_room->floor_file_path,
                'file_disp' =>  1,
                'order'     =>  1,
                'memo'      =>  $check_room->floor_file_comment,
                'company_id' => $user->company_id,
                'portal_id' =>  $article_id,
                'property_sub' =>  $property_sub,
                'facility'    =>  config('const.TYPE_FLOOR_PLAN'),
                'type_upload' =>  config('const.TYPE_UPLOAD_BUKKEN'),
                'del'         =>  0
            ];
            $types = [ config('const.SUUMO'), config('const.HOMES'), config('const.ATHOME')];
            foreach ($types as $type) {
                $photo_data['type'] = $type;
                $obj = RelationPortalPhoto::ofImage($article_id, $article_id, $type)->first();
                if (!empty($obj)){
                    $photo_data['order'] = $obj->order;
                    $photo_data['del'] = 0;
                    $obj->update($photo_data);
                }else{
                    $obj = RelationPortalPhoto::create($photo_data);
                }
            }
            $num_order = 1;
        }else{
            $num_order = 0;
        }
        if($check_room->mansion_id != null){
            $list_mansion = RelationArticlePhoto::where('article_id', '=', $check_room->mansion_id)->where('company_id', '=', $user->company_id)->get();
        }
        $last_order = RelationPortalPhoto::where('article_id', $id)->where('company_id', '=', $user->company_id)->orderBy('order', 'desc')->first();

        if(!empty($last_order)){
            $num_order = $last_order->order;
        }
        foreach ($list as $img) {
            $article_id = $img->article_id;
            $property_sub = $img->property_sub;

            $num_order++;
            $photo_data = [
                'article_id' => $article_id,
                'file_type'  => $img->file_type,
                'file_path' =>  $img->file_path,
                'file_disp' =>  $img->file_disp,
                'order'     =>  $num_order,
                'memo'      =>  $img->memo,
                'company_id' => $img->company_id,
                'portal_id' =>  $img->id,
                'property_sub' =>  $property_sub,
                'facility' =>  $img->facility == config('const.TYPE_FLOOR_PLAN') ? config('const.TYPE_FLOOR_PLAN') : config('const.TYPE_IMAGE_PORTAL'),
                'type_upload' =>  config('const.TYPE_UPLOAD_BUKKEN')
            ];
            $types = [config('const.SUUMO'), config('const.HOMES'), config('const.ATHOME')];
            foreach ($types as $type) {
                $photo_data['type'] = $type;
                $obj = RelationPortalPhoto::ofImage($img->id, $img->article_id, $type)->first();
                if (!empty($obj)){
                    $photo_data['order'] = $obj->order;
                    $photo_data['del'] = 0;
                    $obj->update($photo_data);
                }else{
                    $obj = RelationPortalPhoto::create($photo_data);
                }
            }
        }

        if(isset($list_mansion) && !empty($list_mansion)){
            foreach ($list_mansion as $img) {
                $article_id = $id;
                $property_sub = $img->property_sub;
                $num_order++;
                $photo_data = [
                    'article_id' => $article_id,
                    'file_type'  => $img->file_type,
                    'file_path' =>  $img->file_path,
                    'file_disp' =>  $img->file_disp,
                    'order'     =>  $num_order,
                    'memo'      =>  $img->memo,
                    'company_id' => $img->company_id,
                    'portal_id' =>  $img->id,
                    'mansion'   =>  1,
                    'property_sub' =>  $property_sub,
                    'facility'   =>  config('const.TYPE_IMAGE_PORTAL'),
                    'type_upload' =>  config('const.TYPE_UPLOAD_BUKKEN')
                ];
                $types = [config('const.SUUMO'), config('const.HOMES'), config('const.ATHOME')];
                foreach ($types as $type) {
                    $photo_data['type'] = $type;

                    $obj = RelationPortalPhoto::ofImage($img->id, $article_id, $type)->first();
                    if (!empty($obj)){
                        $photo_data['order'] = $obj->order;
                        $obj->update($photo_data);
                    }else{
                        $obj = RelationPortalPhoto::create($photo_data);
                    }
                }
            }
        }
    }

    public function uploadPortalFacility($id)
    {
        $user = Auth::user();
        RelationPortalFacility::where('article_id', '=', $id)->where('del', '=', 1)->delete();

        RelationPortalFacility::where('article_id', '=', $id)->update(['del' => 1]);

        $list = RelationArticleFacility::where('article_id', '=', $id)->where('company_id', '=', $user->company_id)->get();
        if(count($list) >0){
            $last_order = RelationPortalFacility::where('article_id', $id)->where('company_id', '=', $user->company_id)->orderBy('order', 'desc')->first();
        }

        $num_order = 0;
        if(!empty($last_order)){
            $num_order = $last_order->order;
        }

        $last_order_photo = RelationPortalPhoto::where('article_id', $id)->where('company_id', '=', $user->company_id)->orderBy('order', 'desc')->first();
        $num_order_photo = 0;
        if(!empty($last_order_photo)){
            $num_order_photo = $last_order_photo->order;
        }

        foreach ($list as $img) {
            $num_order++;
            $num_order_photo++;
            $fac = Facility::where('id', '=', $img->facility)->where('company_id', '=', $user->company_id)->first();
            $facility_memo = '施設名: '.$fac->name.'
現地からの距離: '.$img->distance.'m';

            $facility_data = [
                'company_id' => $img->company_id,
                'article_id' => $img->article_id,
                'article_facility_id' => $img->id,
                'facility_name' =>  $fac->name,
                'facility_memo' =>  $fac->memo,
                'file_path' =>  $fac->file_path,
                'distance' =>  $img->distance,
                'order' => $num_order,
                'del'   =>  0,
                'facility_area' => $img->facility_area,
                'facility_property' =>  $img->facility_property,
                'facility'  =>  $img->facility,
                'type_upload'  =>  config('const.TYPE_UPLOAD_BUKKEN')
            ];

            $photo_data = [
                'article_id' => $img->article_id,
                'file_type'  => $img->file_type,
                'file_path' =>  $fac->file_path,
                'company_id' => $img->company_id,
                'portal_id' =>  $img->id,
                'order'     => $num_order_photo,
                'del'   =>  0,
                'property_sub' =>  $img->facility_property,
                'facility' =>  config('const.TYPE_FACILITY_PORTAL'),
                'memo' =>  $facility_memo,
                'type' => config('const.HOMES'),
                'type_upload'  =>  config('const.TYPE_UPLOAD_BUKKEN')
            ];

            $relationPortalPhoto = RelationPortalPhoto::ofImage($img->id, $img->article_id, config('const.HOMES'), config('const.TYPE_FACILITY_PORTAL'))->first();
            if (!empty($relationPortalPhoto)){
                $relationPortalPhoto->update($photo_data);
            }else{
                $relationPortalPhoto = RelationPortalPhoto::create($photo_data);
            }

            $facility_data_suumo = $facility_data;
            $obj_suumo = RelationPortalFacility::where('article_facility_id', $img->id)->type( config('const.SUUMO') )->first();
            $facility_data_suumo['type'] = config('const.SUUMO');
            if (!empty($obj_suumo)){
                $obj_suumo->update($facility_data_suumo);
            }else{
                $obj_suumo = RelationPortalFacility::create($facility_data_suumo);
            }
            $facility_data_athome = $facility_data;
            $obj_athome = RelationPortalFacility::where('article_facility_id', $img->id)->type(config('const.ATHOME'))->first();
            $facility_data_athome['type'] = config('const.ATHOME');
            if (!empty($obj_athome)){
                $obj_athome->update($facility_data_athome);
            }else{
                $obj_athome = RelationPortalFacility::create($facility_data_athome);
            }
        }
        if(isset($obj_suumo) && isset($obj_athome)){
            return 1;
        }

    }

    public static function getPropertyName($property, $property_sub)
    {
        $res = '';
        if ($property == 4 || $property == 5 || $property == 6 || $property == 7) {
            $res .= MstPropertyTypeSub::find($property_sub)->name ?? '';
        }

        if (is_null($property)) {
            $res .= 'マンション（部屋）';
        } elseif ($property == 99) {
            $res .= '分譲地';
        } else {
            $res .= MstPropertyType::find($property)->name ?? '';
        }


        return $res;
    }


    public function getMasterData($article_data = null, $type = null, $old = null, $property = null)
    {
        $user = Auth::user();

        $data = [];

        // 独自項目
        $custom = CustomContent::getData($user->company_id);

        // 種別
        if ($this->parentProperty < 4) {
            $data['property'] = MstPropertyType::getDataByParentId($this->parentProperty);
            $data['property_sub'] = MstPropertyTypeSub::getData();
        }

        // ステータス
        $data['statuses'] = MstStatus::getData();

        // 取引態様
        $data['manner'] = MstManner::getData();

        // 都道府県マスターを取得
        if (isset($old['_old_input'])) {

            $save_vendor_list = isset($old['_old_input']['save_vendor_list']) ? $old['_old_input']['save_vendor_list'] : "";

            if ($save_vendor_list != "") {
                $vendorIds = explode(",", $save_vendor_list);
                $vendors = [];
                foreach ($vendorIds as $vId) {
                    if ($vId != "") {
                        $vendors[] = Vendor::find($vId);
                    }
                }
                $data['vendors'] = $vendors;
            }

            $data['pref'] = MstPrefecture::getData();

            if (auth()->user()->company_id === 1) {
                $city = MstCity::getData($old['_old_input']['address1'], null, auth()->user()->company_id);
                $data['city'] = $city;
            } else {
                $data['city'] = MstCity::getData($old['_old_input']['address1'], null, auth()->user()->company_id);
            }
            $data['town'] = MstTown::getData($old['_old_input']['address1'], $old['_old_input']['address2']);
            $sres = $data['city'];
            foreach ($sres as $key => $s) {
                $sres[$key]['code'] = $s['name'];
            }
            $data['school_town'] = $sres;

            if (!isset($old['_old_input']['primary_school_city']) || empty($old['_old_input']['primary_school_city'])) {
                $data['primary_school_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $old['_old_input']['primary_school_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $primarySchools = $this->getSchoolByCityName($cityCode, "primary", optional($cityArticle)->code);

                $data['primary_school_list'] = $primarySchools;
            }

            if (!isset($old['_old_input']['primary_school2_city']) || empty($old['_old_input']['primary_school2_city'])) {
                $data['primary_school2_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $old['_old_input']['primary_school2_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $primarySchools = $this->getSchoolByCityName($cityCode, "primary", optional($cityArticle)->code);

                $data['primary_school2_list'] = $primarySchools;
            }

            if (!isset($old['_old_input']['primary_school3_city']) || empty($old['_old_input']['primary_school3_city'])) {
                $data['primary_school3_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $old['_old_input']['primary_school3_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $primarySchools = $this->getSchoolByCityName($cityCode, "primary", optional($cityArticle)->code);

                $data['primary_school3_list'] = $primarySchools;
            }

            if (!isset($old['_old_input']['secondary_school_city']) || empty($old['_old_input']['secondary_school_city'])) {
                $data['secondary_school_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $old['_old_input']['secondary_school_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $juniorSchools = $this->getSchoolByCityName($cityCode, "junior", optional($cityArticle)->code);

                $data['secondary_school_list'] = $juniorSchools;
            }
            if (!isset($old['_old_input']['secondary_school2_city']) || empty($old['_old_input']['secondary_school2_city'])) {
                $data['secondary_school2_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $old['_old_input']['secondary_school2_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $juniorSchools = $this->getSchoolByCityName($cityCode, "junior", optional($cityArticle)->code);

                $data['secondary_school2_list'] = $juniorSchools;
            }
            if (!isset($old['_old_input']['secondary_school3_city']) || empty($old['_old_input']['secondary_school3_city'])) {
                $data['secondary_school3_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $old['_old_input']['secondary_school3_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $juniorSchools = $this->getSchoolByCityName($cityCode, "junior", optional($cityArticle)->code);

                $data['secondary_school3_list'] = $juniorSchools;
            }
        } else if (empty($article_data)) {
            $data['pref'] = MstPrefecture::getData();
            $defaultPrefCode = array_get(array_first($data['pref']), 'code');
            if (auth()->user()->company_id === 1) {
                $city = MstCity::getData($defaultPrefCode, null, auth()->user()->company_id);
                /*$num = count($city);
                for ($i = 0; $i < ($num - 1); $i++) {
                    for ($j = $i + 1; $j < $num; $j++) {
                        if (isset($city[4])) {
                            $l1 = $city[4];
                            $city[4] = $city[2];
                            $city[2] = $l1;
                        }
                    }
                }

                $city2 = $city;
                $num = count($city2);
                for ($i = 0; $i < ($num - 1); $i++) {
                    for ($j = $i + 1; $j < $num; $j++) {
                        if (isset($city2[4])) {
                            $l2 = $city2[4];
                            $city2[4] = $city2[3];
                            $city2[3] = $l2;
                        }
                        if (isset($city2[45])) {
                            $l3 = $city2[45];
                            $city2[45] = $city2[5];
                            $city2[5] = $l3;
                        }
                    }
                }*/
                $data['city'] = $city;
            } else {
                $data['city'] = MstCity::getData($defaultPrefCode, null, auth()->user()->company_id);
            }
            $data['town'] = [];
//            $sres = MstCity::selectRaw("name as code, name")->where("company_id", auth()->user()->company_id)->get()->toArray();
            $sres = $data['city'];
            foreach ($sres as $key => $s) {
                $sres[$key]['code'] = $s['name'];
            }
            $data['school_town'] = $sres;
        } else {

            $data['pref'] = MstPrefecture::getData();
            if (auth()->user()->company_id === 1) {
                $city = MstCity::getData($article_data['address1'], null, auth()->user()->company_id);
                $data['city'] = $city;
            } else {
                $data['city'] = MstCity::getData($article_data['address1']??'', null, auth()->user()->company_id);
            }
            $data['town'] = MstTown::getData($article_data['address1']??'', $article_data['address2'] ?? '');
            $sres = $data['city'];
            foreach ($sres as $key => $s) {
                $sres[$key]['code'] = $s['name'];
            }
            $data['school_town'] = $sres;
            if (empty($article_data['primary_school_city'])) {
                $data['primary_school_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $article_data['primary_school_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $primarySchools = $this->getSchoolByCityName($cityCode, "primary", optional($cityArticle)->code);
                $data['primary_school_list'] = $primarySchools;
            }

            if (empty($article_data['primary_school2_city'])) {
                $data['primary_school2_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $article_data['primary_school2_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $primarySchools = $this->getSchoolByCityName($cityCode, "primary", optional($cityArticle)->code);

                $data['primary_school2_list'] = $primarySchools;
            }

            if (empty($article_data['primary_school3_city'])) {
                $data['primary_school3_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $article_data['primary_school3_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $primarySchools = $this->getSchoolByCityName($cityCode, "primary", optional($cityArticle)->code);

                $data['primary_school3_list'] = $primarySchools;
            }

            if (empty($article_data['secondary_school_city'])) {
                $data['secondary_school_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $article_data['secondary_school_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $juniorSchools = $this->getSchoolByCityName($cityCode, "junior", optional($cityArticle)->code);

                $data['secondary_school_list'] = $juniorSchools;
            }

            if (empty($article_data['secondary_school2_city'])) {
                $data['secondary_school2_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $article_data['secondary_school2_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $juniorSchools = $this->getSchoolByCityName($cityCode, "junior", optional($cityArticle)->code);

                $data['secondary_school2_list'] = $juniorSchools;
            }

            if (empty($article_data['secondary_school3_city'])) {
                $data['secondary_school3_list'] = [];
            } else {
                $cityArticle = MstCity::where("name", $article_data['secondary_school3_city'])->where("company_id", auth()->user()->company_id)->first();
                $cityCode = optional($cityArticle)->pref_code . optional($cityArticle)->code;
                $juniorSchools = $this->getSchoolByCityName($cityCode, "junior", optional($cityArticle)->code);

                $data['secondary_school3_list'] = $juniorSchools;
            }

        }

        // 取扱店の取得
        $shops = MstStore::getDataAll($user->company_id);
        $data['shops'] = $shops;

        // 学校のエリア取得
        $schoolTown = RelationCitySchool::getCityList();

        $arr = [];
        foreach ($schoolTown as $town) {
            $arr[] = ['code' => $town->name, 'name' => $town->name];
        }
        $data['school_area'] = $arr;

        // 構造
        $construction = [['code' => 0, 'name' => '未選択']];
        $tmp_construction = MstStructure::getData();
        foreach ($tmp_construction as $row) {
            $construction[] = $row;
        }
        $data['construction'] = $construction;

        $arr_construction = [];
        foreach ($data['construction'] as $row) {
            $arr_construction[$row['code']] = $row['name'];
        }
        $data['arr_construction'] = $arr_construction;

        $data['construction_sub'] = MstStructureSub::getData();
        $arr_construction_sub = [];
        foreach ($data['construction_sub'] as $row) {
            $arr_construction_sub[$row['code']] = $row['name'];
        }
        $data['arr_construction_sub'] = $arr_construction_sub;

        $data['floor'] = [
            ['code' => 0, 'name' => 1],
            ['code' => 1, 'name' => 1],
            ['code' => 2, 'name' => 2],
            ['code' => 3, 'name' => 3],
            ['code' => 4, 'name' => 4],
            ['code' => 5, 'name' => 5],
            ['code' => 6, 'name' => 6],
            ['code' => 7, 'name' => 7],
            ['code' => 8, 'name' => 8],
            ['code' => 9, 'name' => 9],
            ['code' => 10, 'name' => 10],
            ['code' => 11, 'name' => 11],
            ['code' => 12, 'name' => 12],
            ['code' => 13, 'name' => 13],
            ['code' => 14, 'name' => 14],
            ['code' => 15, 'name' => 15],
        ];


        $management_form = MstManagementForm::getData();
        array_push($management_form, ['code' => 0, 'name' => '未選択']);
        $data['management_form'] = $management_form;
        $arr_management_form = [];
        foreach ($data['management_form'] as $row) {
            $arr_management_form[$row['code']] = $row['name'];
        }
        $data['arr_management_form'] = $arr_management_form;

        // 間取り
        $floor_plan = [];
        for ($i = 1; $i < 11; $i++) {
            $floor_plan[] = ['code' => $i, 'name' => $i];

        }
        $data['floor_plan'] = $floor_plan;
        $data['floor_type'] = MstFloorType::getData();

        //　完成時期
        $comp_start = config('const.COMP_YEAR_START');
        $comp_end = date('Y') + config('const.COMP_YEAR');
        $comp_year = [];
        for ($i = $comp_start; $i <= $comp_end; $i++) {
            $comp_year[] = ['code' => $i, 'name' => $i];
        }
        $data['comp_year'] = $comp_year;

        // 引き渡し
        $data['move_in'] = [
            ['code' => 1, 'name' => '即', 'add_text' => '検索', 'add_class' => ''],
            ['code' => 2, 'name' => '相談'],
            ['code' => 3, 'name' => '指定有'],
            ['code' => 4, 'name' => '契約後'],
            ['code' => 0, 'name' => '未選択'],
        ];

        $data['reform'] = [
            ['code' => 1, 'name' => '無'],
            ['code' => 2, 'name' => '済'],
            ['code' => 3, 'name' => '完了予定'],
        ];


        // 現況
        if ($property != 4) {
            $data['genkyou'] = MstGenkyou::getDataByProperty($property);
        } else {
            $data['genkyo'] = [];
        }


        // 駐車場
        if (is_null($type)) {
            $data['parking'] = [];
        } else {
            $parking = MstParking::getDataByType($type);
            array_push($parking, ['code' => 0, 'name' => '未選択']);
            $data['parking'] = $parking;
        }

        $data['pet'] = [
            ['code' => 1, 'name' => '不可'],
            ['code' => 2, 'name' => '可（制限あり）'],
            //['code' => 3, 'name' => '相談'],
            ['code' => 0, 'name' => '未選択']
        ];
        $arr_pet = [];
        foreach ($data['pet'] as $row) {
            $arr_pet[$row['code']] = $row['name'];
        }
        $data['arr_pet'] = $arr_pet;


        $data['pet_num'] = [
            ['code' => 0, 'name' => '未選択'],
            ['code' => 1, 'name' => 1],
            ['code' => 2, 'name' => 2],
            ['code' => 3, 'name' => 3],
            ['code' => 4, 'name' => 4],
            ['code' => 5, 'name' => 5],
        ];


        $data['other_reason'] = MstOtherReason::getData();


        // リフォーム

        $interior = [
            ['code' => '1', 'name' => 'キッチン'],
            ['code' => '2', 'name' => '浴室'],
            ['code' => '3', 'name' => 'トイレ'],
            ['code' => '4', 'name' => '壁'],
            ['code' => '5', 'name' => '床'],
            ['code' => '6', 'name' => '全室'],
            ['code' => '7', 'name' => 'その他'],
        ];

        $exterior = [
            ['code' => '1', 'name' => '外壁'],
            ['code' => '2', 'name' => '屋根'],
            ['code' => '3', 'name' => 'その他'],
        ];

        $spring_kind = [
            ['code' => 1, 'name' => '加温'],
            ['code' => 2, 'name' => '加水'],
            ['code' => 3, 'name' => '運び湯'],
            ['code' => 4, 'name' => '循環装置使用'],
            ['code' => 5, 'name' => '循環ろ過装置使用'],
        ];


        // 制限事項
        $law = MstLawrestriction::getData();
        $other = MstOtherrestriction::getData();
        $shared = MstShared::getData();

        $checked_shared = [];
        $checked_interior = [];
        $checked_exterior = [];
        $checked_spring = [];
        $checked_law = [];
        $checked_other = [];


        if (isset($old['_old_input']['shared'])) {
            $checked_shared = $old['_old_input']['shared'];
        } elseif (isset($article_data->article_id)) {
            $checked_shared = RelationShared::getDataByArticleId($user->company_id, $article_data->building_id);
        }

        if (isset($old['_old_input']['interior_place'])) {
            $checked_interior = $old['_old_input']['interior_place'];
        } elseif (isset($article_data->article_id)) {
            $checked_interior = RelationInterior::getDataByArticleId($user->company_id, $article_data->building_id);
        }

        if (isset($old['_old_input']['exterior_place'])) {
            $checked_exterior = $old['_old_input']['exterior_place'];
        } elseif (isset($article_data->article_id)) {
            $checked_exterior = RelationExterior::getDataByArticleId($user->company_id, $article_data->building_id);
        }

        if (isset($old['_old_input']['spring_kind'])) {
            $checked_spring = $old['_old_input']['spring_kind'];
        } elseif (isset($article_data->article_id)) {
            $checked_spring = RelationSpring::getDataByArticleId($user->company_id, $article_data->building_id);
        }

        if (isset($old['_old_input']['law_restriction'])) {
            $checked_law = $old['_old_input']['law_restriction'];
        } elseif (isset($article_data->article_id)) {
            $buildingId = Article::query()->find($article_data->article_id)->building_id;
            $checked_law = RelationLawrestriction::getDataByArticleId($article_data->building_id ?? $buildingId);
        }

        if (isset($old['_old_input']['other_restriction'])) {
            $checked_other = $old['_old_input']['other_restriction'];
        } elseif (isset($article_data->article_id)) {
            $checked_other = RelationOtherrestriction::getDataByArticleId($article_data->building_id);
        }

        foreach ($shared as &$row) {
            if (in_array($row['code'], $checked_shared)) {
                $row['checked'] = 1;
            }
        }

        foreach ($interior as &$row) {
            if (in_array($row['code'], $checked_interior)) {
                $row['checked'] = 1;
            }
        }

        foreach ($exterior as &$row) {
            if (in_array($row['code'], $checked_exterior)) {
                $row['checked'] = 1;
            }
        }

        foreach ($spring_kind as &$row) {
            if (in_array($row['code'], $checked_spring)) {
                $row['checked'] = 1;
            }
        }

        foreach ($law as &$row) {
            if (in_array($row['code'], $checked_law)) {
                $row['checked'] = 1;
            }
        }

        foreach ($other as &$row) {
            if (in_array($row['code'], $checked_other)) {
                $row['checked'] = 1;
            }
        }


        $data['shared'] = $shared;
        $data['interior'] = $interior;
        $data['exterior'] = $exterior;
        $data['spring_kind'] = $spring_kind;
        $data['law'] = $law;
        $data['other'] = $other;

        $data['land_right'] = [
            ['code' => 1, 'name' => '所有権'],
            ['code' => 2, 'name' => '借地権のみ'],
            ['code' => 3, 'name' => '所有権・借地権混在'],
            ['code' => 0, 'name' => '未選択'],
        ];
        $data['arry_land_right'] = [
            1 => '所有権',
            2 => '借地権のみ',
            3 => '所有権・借地権混在',
            0 => '未選択',
        ];
        $data['arr_leasehold_kind'] = [
            1 => '旧法賃借権',
            2 => '普通賃借権',
            3 => '一般定期賃借権',
            4 => '建物譲渡特約付き定期賃借権',
            5 => '旧法地上権',
            6 => '普通地上権',
            7 => '一般定期地上権',
            8 => '建物譲渡特約付き定期地上権',
        ];
        $data['arr_land_rent'] = [
            1 => '有',
            0 => '無',
        ];
        $data['arr_land_rent_unit'] = [
            1 => '月',
            2 => '年',
            3 => '一括',
        ];
        $data['arr_regular_leased_registration'] = [
            0 => '未選択',
            1 => '可',
            2 => '不可',
            3 => '相談',
        ];
        $data['arr_regular_leased_season'] = [
            0 => '未選択',
            1 => '一定期間毎',
            2 => '事前協議により決定',
        ];
        $data['regular_leased_cost'] = [
            0 => '未選択',
            1 => '公式',
            2 => '事前協議により決定',
        ];
        $data['arr_regular_leased_transfer'] = [
            0 => '未選択',
            1 => '可',
            2 => '不可',
        ];
        $data['arr_regular_leased_transfer_method'] = [
            0 => '未選択',
            1 => '承諾不要',
            2 => '通知要',
            3 => '承諾要',
        ];
        $data['arr_regular_leased_transfer_necessity'] = [
            0 => '未選択',
            1 => '要',
            2 => '不要',
            3 => '未定',
        ];
        $data['arr_regular_leased_transfer_consent'] = [
            0 => '未選択',
            1 => '地主',
            2 => '転貸主',
        ];
        $data['leasehold'] = [
            ['code' => 1, 'name' => '旧法賃借権'],
            ['code' => 2, 'name' => '普通賃借権'],
            ['code' => 3, 'name' => '一般定期賃借権'],
            ['code' => 4, 'name' => '建物譲渡特約付き定期賃借権'],
            ['code' => 5, 'name' => '旧法地上権'],
            ['code' => 6, 'name' => '普通地上権'],
            ['code' => 7, 'name' => '一般定期地上権'],
            ['code' => 8, 'name' => '建物譲渡特約付き定期地上権'],
        ];

        $data['land_rent_unit'] = [
            ['code' => 1, 'name' => '月'],
            ['code' => 2, 'name' => '年'],
            ['code' => 3, 'name' => '一括'],
        ];

        $data['leasehold_period'] = [
            ['code' => 1, 'name' => '残存'],
            ['code' => 2, 'name' => '新規'],
        ];

        $data['right_cost'] = [
            ['code' => 0, 'name' => '無'],
            ['code' => 1, 'name' => '有(価格に含む)'],
        ];

        // 未入居
        $data['occupied'] = [
            ['code' => 1, 'name' => '未入居'],
        ];
        // 収益物件
        $data['revenue'] = [
            ['code' => 1, 'name' => '収益物件'],
        ];

        // 町会費
        $data['council_cost'] = [
            ['code' => 1, 'name' => '町会費'],
            ['code' => 2, 'name' => '町内会費'],
            ['code' => 3, 'name' => '自治会費'],
            ['code' => 0, 'name' => '未選択'],
        ];

        // 温泉
        $data['spring_cost'] = [
            ['code' => 1, 'name' => '温泉使用料'],
            ['code' => 2, 'name' => '温泉権利金'],
            ['code' => 0, 'name' => '未選択'],
        ];

        // 道路(向き)
        $data['land_direction'] = [
            ['code' => 0, 'name' => '未選択'],
            ['code' => 1, 'name' => '北'],
            ['code' => 2, 'name' => '北東'],
            ['code' => 3, 'name' => '東'],
            ['code' => 4, 'name' => '南東'],
            ['code' => 5, 'name' => '南'],
            ['code' => 6, 'name' => '南西'],
            ['code' => 7, 'name' => '西'],
            ['code' => 8, 'name' => '北西'],
        ];

        // 道路(種別)
        $data['land_kind'] = [
            ['code' => 0, 'name' => '未選択'],
            ['code' => 1, 'name' => '公道'],
            ['code' => 2, 'name' => '私道'],
        ];

        // 施設
        // $data['facility'] = Facility::getData();
        $data['facility'] = [];
        $data['facility_property'] = MstFacilityType::getData();
        $data['facility_distance'] = [
            ['code' => 0, 'name' => 0],
            ['code' => 5, 'name' => 5],
            ['code' => 10, 'name' => 10],
            ['code' => 15, 'name' => 15],
            ['code' => 20, 'name' => 20],
            ['code' => 25, 'name' => 25],
            ['code' => 30, 'name' => 30],
            ['code' => 35, 'name' => 35],
            ['code' => 40, 'name' => 40],
            ['code' => 45, 'name' => 45],
            ['code' => 50, 'name' => 50],
            ['code' => 55, 'name' => 55],
            ['code' => 60, 'name' => 60],
            ['code' => 65, 'name' => 65],
        ];

        $data['original1'] = [['code' => 1, 'name' => '　']];
        $data['original2'] = [['code' => 1, 'name' => '　']];
        $data['original3'] = [
            ['code' => 0, 'name' => '0'],
            ['code' => 1, 'name' => '1'],
            ['code' => 2, 'name' => '2'],
            ['code' => 3, 'name' => '3'],
        ];
        $data['original4'] = [['code' => 1, 'name' => '　']];

        // 営業担当者
        // $data['hp_charge'] = User::getDataByCompanyId($user->company_id, 3);
        if (isset($article_data->shop)) {
            $data['hp_charge'] = UserInfo::getCharge($user->company_id, $article_data->shop);
        } else {
            if (isset($shops[0])) {
                $data['hp_charge'] = UserInfo::getCharge($user->company_id, $shops[0]['code']);
            } else {
                $data['hp_charge'] = [];
            }
            // $data['hp_charge'] = [];
        }

        // 物件価格
        $data['tax'] = [
            ['code' => 1, 'name' => '税無'],
            ['code' => 2, 'name' => '税込'],
        ];

        // 用途地域
        $data['use_area'] = MstUseArea::getData();
        $arr_use_area = [];
        foreach ($data['use_area'] as $use_area) {
            $arr_use_area[$use_area['code']] = $use_area['name'];
        }
        $data['arr_use_area'] = $arr_use_area;

        $data['use_area_district'] = MstUseDistrict::getData();
        $arr_use_area_district = [];
        foreach ($data['use_area_district'] as $use_area_district) {
            $arr_use_area_district[$use_area_district['code']] = $use_area_district['name'];
        }
        $data['arr_use_area_district'] = $arr_use_area_district;

        $data['city_plan'] = [
            ['code' => 1, 'name' => '市街化区域'],
            ['code' => 2, 'name' => '調整区域'],
            ['code' => 3, 'name' => '非線引区域'],
            ['code' => 4, 'name' => '区域外'],
            ['code' => 5, 'name' => '準都市区域'],
        ];
        $arr_city_plan = [];
        foreach ($data['city_plan'] as $city_plan) {
            $arr_city_plan[$city_plan['code']] = $city_plan['name'];
        }
        $data['arr_city_plan'] = $arr_city_plan;

        $data['city_plan_reason'] = [
            ['code' => 1, 'name' => '開発許可などによる分譲地内'],
            ['code' => 2, 'name' => '都市開発法施行令36条1項3号口に該当'],
            ['code' => 3, 'name' => '調整区域につき建築許可要'],
            ['code' => 4, 'name' => '調整区域につき建築許可要。建築主の許可要件あり'],
        ];
        $arr_city_plan_reason = [];
        foreach ($data['city_plan_reason'] as $city_plan_reason) {
            $arr_city_plan_reason[$city_plan_reason['code']] = $city_plan_reason['name'];
        }
        $data['arr_city_plan_reason'] = $arr_city_plan_reason;

        // 施設の市区群を取得
        $facility_area = Facility::getFacilityArea($user->company_id);
        $data['facility_area'] = $facility_area;

        return $data;
    }

    private function getSchoolByCityName($cityCode, $typeSchool = "primary", $cityCodeSai = null)
    {
        if (auth()->user()->company_id != 1) {
            $response = [];
            if ($typeSchool === "primary") {
                $schools = MstSchool::getSchoolByCity($cityCodeSai, 1);

            } else {
                $schools = MstSchool::getSchoolByCity($cityCodeSai, 2);

            }
            $response = array_merge($response, $schools);
            $response = collect($response);
            return $response->unique("code")->toArray();
        }

        $response = [];
        if ($typeSchool === "primary") {
            $schools = RelationCitySchool::getDataElementarySchool($cityCode);
        } else {
            $schools = RelationCitySchool::getDataJuniorSchool($cityCode);
        }

        if (!empty($schools)) {
            foreach ($schools as $school) {
                $schoolsData = MstSchool::getSchoolName($school);
                $response = array_merge($response, $schoolsData);
            }
        }

        $response = collect($response);
        return $response->unique("code")->toArray();
    }

    public function setCount()
    {
        $user = Auth::user();
        // 駅に設定されている物件の件数を設定
        if (!empty(request()->get('main_traffic_station_id'))) {
            $count = Article::getCountByStation(request()->get('main_traffic_station_id'));
            $data = ['count' => $count];
            MstStation::where('id', '=', request()->get('main_traffic_station_id'))->update($data);
        }

        if (!empty(request()->get('sub_traffic1_station_id'))) {
            $count = Article::getCountByStation(request()->get('sub_traffic1_station_id'));
            $data = ['count' => $count];
            MstStation::where('id', '=', request()->get('sub_traffic1_station_id'))->update($data);
        }

        if (!empty(request()->get('sub_traffic2_station_id'))) {
            $count = Article::getCountByStation(request()->get('sub_traffic2_station_id'));
            $data = ['count' => $count];
            MstStation::where('id', '=', request()->get('sub_traffic2_station_id'))->update($data);
        }

        if (!empty(request()->get('primary_school_school'))) {
            $count = Article::getCountByPrimarySchool(request()->get('primary_school_school'));
            $data = ['count' => $count];
            MstSchool::where('code', '=', request()->get('primary_school_school'))->update($data);
        }

        if (!empty(request()->get('secondary_school_school'))) {
            $count = Article::getCountBySecondarySchool(request()->get('secondary_school_school'));
            $data = ['count' => $count];
            MstSchool::where('code', '=', request()->get('secondary_school_school'))->update($data);
        }

    }

    public function updateImage($request, $article)
    {
        $all = $request->all();
        $user = Auth::user();
        $image_len = 0;
        $runk = 1;
        if (isset($request->saved_photo_id)) {
            $array_keys = array_keys($all);
            $matched_keys = array_filter(
                $array_keys,
                function ($k) {
                    return preg_match("/article_photo_id[0-9]*/u", $k);
                }
            );
            $tag = [];
            foreach ($matched_keys as $key) {
                $target_key = str_replace('article_photo_id', '', $key);
                if ($target_key != "") {
                    $tag[] = $target_key;
                }

            }

            $list = explode(',', $request->saved_photo_id);
            $image_len = count($list);
            $rls_key = 0;
            foreach ($tag as $val) {
                if (!empty($request->{'article_photo_id' . $val})) {
                    $target_id =  $request->{'article_photo_id' . $val};
                } else {
                    $target_id =  $request->rls_articles_id[$rls_key] ?? "";
                    $rls_key ++;
                }
                $disp = 1;
                if (isset($request->{'photo_disp_change' . $val})) {
                    $disp = $request->{'photo_disp_change' . $val};
                }
                $photo_data = [
                    'file_disp' => $disp,
                    'property' => $request->{'photo_property' . $val},
                    'property_sub' => $request->{'photo_property_sub' . $val},
                    'memo' => $request->{'photo_comment' . $val},
                    'order' => $runk,
                ];
                RelationArticlePhoto::where('id', '=', $target_id)->update($photo_data);
                $runk++;
            }
        } else {
            $array_keys = array_keys($all);
            $matched_keys = array_filter(
                $array_keys,
                function ($k) {
                    return preg_match("/article_photo_id[0-9]*/u", $k);
                }
            );
            $tag = [];

            foreach ($matched_keys as $key) {
                $target_key = str_replace('article_photo_id', '', $key);
                if ($target_key != "") {
                    $tag[] = $target_key;
                }

            }
            $rls_key = 0;
            foreach ($tag as $val) {
                if (!empty($request->{'article_photo_id' . $val})) {
                    $target_id = $request->{'article_photo_id' . $val};
                } else {
                    $target_id =  $request->rls_articles_id[$rls_key] ?? "";
                    $rls_key ++;
                }
                $disp = 1;
                if (isset($request->{'photo_disp_change' . $val})) {
                    $disp = $request->{'photo_disp_change' . $val};
                }
                $photo_data = [
                    'file_disp' => $disp,
                    'property' => $request->{'photo_property' . $val},
                    'property_sub' => $request->{'photo_property_sub' . $val},
                    'memo' => $request->{'photo_comment' . $val},
                    'order' => $runk,
                ];
                RelationArticlePhoto::where('id', '=', $target_id)->update($photo_data);
                $runk++;
            }
        }

        if (isset($request->del_photo_id)) {

            $list = explode(',', $request->del_photo_id);
            foreach ($list as $key => $val) {
                RelationArticlePhoto::where('id', '=', $val)->delete();
                $runk--;
            }
        }

        if (isset($request->photo_images)) {
            $img_list = RelationArticlePhoto::where('article_id', '=', $article->building_id)->get();
            $max = 0;
            foreach ($img_list as $img) {
                $tmp_path = $img->file_path;
                $tmp_path = str_replace('public/photo/photo_image_' . $article->building_id . '_', '', $tmp_path);
                $tmp_path = str_replace('.' . $img->file_type, '', $tmp_path);
                if ($max < $tmp_path) {
                    $max = $tmp_path;
                }
            }
            if ($max != 0) {
                $max++;
            }

            $num = 0;
            $saved = $request->saved_photo_id;
            $saved_info = explode(',', $saved);
            $saved_info = array_filter($saved_info, "strlen");
            $deleted = $request->del_photo_id;
            $deleted_info = explode(',', $deleted);
            $deleted_info = array_filter($deleted_info, "strlen");
            $num += count($saved_info);
            // $num += count($deleted_info);

            $len = $max;

            foreach ($request->photo_images as $key => $photo) {
                $len = $len + 1;
                $extension = $photo->getClientOriginalExtension();

                $image = \Image::make($photo)->exif();
                $org_height = $image['COMPUTED']['Height'];
                $org_width = $image['COMPUTED']['Width'];

                $rate = 0;
                $height = 0;
                $width = 0;
                if ($org_height > $org_width) {
                    $rate = config('const.MAX_LENGTH') / $org_height;
                    $width = $org_width * $rate;
                    $height = config('const.MAX_LENGTH');

                } else {
                    $rate = config('const.MAX_LENGTH') / $org_width;
                    $width = config('const.MAX_LENGTH');
                    $height = $org_height * $rate;

                }
                $image = \Image::make($photo);
                $image->orientate();
                $image->resize($width, $height)->save(storage_path() . '/app/public/company_'.$user->company_id.'/photo/photo_image_' . $article->building_id . '_' . $len . '.' . $extension);

                $image_url = 'public/photo/photo_image_' . $article->building_id . '_' . $len . '.' . $extension;

                $disp = 1;
                if (isset($request->{'photo_disp_change' . $num})) {
                    $disp = $request->{'photo_disp_change' . $num};
                }
                $photo_data = [
                    'article_id' => $article->building_id,
                    'file_path' => $image_url,
                    'file_type' => $extension,
                    'file_disp' => $disp,
                    'property' => $request->{'photo_property' . $num},
                    'property_sub' => $request->{'photo_property_sub' . $num},
                    'memo' => $request->{'photo_comment' . $num},
                    'order' => $runk,
                ];
                RelationArticlePhoto::create($photo_data);
                $runk++;
                $num++;
            }

        }
    }


    public function image(Request $request, User $user)
    {

        // バリデーション省略
        $originalImg = $request->user_image;

        if ($originalImg->isValid()) {
            $filePath = $originalImg->store('public');
            $user->image = str_replace('public/', '', $filePath);
            $user->save();
        }
        return redirect("/user/{$user->id}")->with('user', $user);

    }

    public function getDataById($id)
    {
        $user = Auth::user();

        $article = Article::getDataById($id);

        if ($article == null) {
            print('存在しない物件、または不正なアクセスです。');
            exit;
        }

        if (isset($article->create) && !empty($article->create)) {
            $article->disp_create = date('Y/m/d', strtotime($article->create));
        }
        if (!empty($article->floor_file_path)) {
            $article->file_path = str_replace('public', '/storage', $article->floor_file_path);
        }
        if (!empty($article->sheet_file_path2)) {
            $article->sheet_file_path2 = str_replace('public', '/storage', $article->sheet_file_path2);
        }
        if (!empty($article->sheet_file_path3)) {
            $article->sheet_file_path3 = str_replace('public', '/storage', $article->sheet_file_path3);
        }

        if (!empty($article->event_day)) {
            $article->event_day = explode(',', $article->event_day);
        }

        $images = RelationArticlePhoto::getImgByArticleId($article->building_id);
        $image_id = "";
        foreach ($images as &$img) {
            $img->file_path = str_replace('public', '/storage', $img->file_path);
            if ($image_id != "") {
                $image_id .= ",";
            }
            $image_id .= $img->id;
        }
        $article->images = $images;
        $article->images_id = $image_id;

        return $article;
    }

    function distance($lat1, $lon1, $lat2, $lon2, $mode = true)
    {
        // 緯度経度をラジアンに変換
        $radLat1 = deg2rad($lat1); // 緯度１
        $radLon1 = deg2rad($lon1); // 経度１
        $radLat2 = deg2rad($lat2); // 緯度２
        $radLon2 = deg2rad($lon2); // 経度２

        // 緯度差
        $radLatDiff = $radLat1 - $radLat2;

        // 経度差算
        $radLonDiff = $radLon1 - $radLon2;

        // 平均緯度
        $radLatAve = ($radLat1 + $radLat2) / 2.0;

        // 測地系による値の違い
        $a = $mode ? 6378137.0 : 6377397.155; // 赤道半径
        $b = $mode ? 6356752.314140356 : 6356078.963; // 極半径
        //$e2 = ($a*$a - $b*$b) / ($a*$a);
        $e2 = $mode ? 0.00669438002301188 : 0.00667436061028297; // 第一離心率^2
        //$a1e2 = $a * (1 - $e2);
        $a1e2 = $mode ? 6335439.32708317 : 6334832.10663254; // 赤道上の子午線曲率半径

        $sinLat = sin($radLatAve);
        $W2 = 1.0 - $e2 * ($sinLat * $sinLat);
        $M = $a1e2 / (sqrt($W2) * $W2); // 子午線曲率半径M
        $N = $a / sqrt($W2); // 卯酉線曲率半径

        $t1 = $M * $radLatDiff;
        $t2 = $N * cos($radLatAve) * $radLonDiff;
        $dist = sqrt(($t1 * $t1) + ($t2 * $t2));

        return $dist;
    }
    public static function uploadRemoteMic($file_path)
    {
        $ar_folder = explode('/', $file_path);
        unset($ar_folder[count($ar_folder) - 1]);
        $folder = implode('/', $ar_folder);
        $folder = str_replace('public', 'storage', $folder);


        $url = env("URL_MIC_EXPORT", "");
        $path = storage_path("app".DIRECTORY_SEPARATOR.$file_path);

        try {
            $client = new Client(['verify' => false]);
            $r = $client->request('POST', $url, [
                'multipart' => [
                    [
                        'name'     => 'file_name',
                        'contents' => Psr7\Utils::tryFopen($path, 'r'),
                    ],
                    [
                        'name'     => 'folder',
                        'contents' => "/".$folder."/",
                    ],
                ]
            ]);

            $code = $r->getStatusCode();
            $body = $r->getBody();
            $remainingBytes = $body->getContents();
            //dd($remainingBytes);
        } catch (\Error $error) {
            var_dump($error);
        }
    }

    public static function setPriceCustomContent(Article $article)
    {
        $new_content = '';
        $prices = [];
        foreach($article->histories() as $p){
            $prices[] = $p->price;
        }
        foreach(array_reverse($prices) as $p){
            if($new_content == ''){
                $new_content = number_format($p, 0) . '万円';
            }else{
                $new_content .= ' -> ' . number_format($p, 0) . '万円';
            }
        }

        $priceContent = RelationCustomContent::where(['article_id' => $article->building_id, 'code' => 7])->first();
        if ($priceContent) {
            $priceContent->update(['contents' => $new_content]);
        } else {
            $article->customs()->create([
                'company_id' => \auth()->user()->company_id,
                'type' => 1,
                'code' => 7,
                'contents' => $new_content
            ]);
        }
    }
}
