<?php

namespace App\Http\Controllers\Admin\Ajax;

use App\Console\Commands\Converters\SaiKyotoArticleConverter;
use App\Console\Commands\Converters\SaiKyotoContructConverter;
use App\Http\Controllers\Admin\ArticleController;
use App\Models\CustomContent;
use App\Models\Lease;
use App\Models\MstFacilityType;
use App\Models\MstFloorType;
use App\Models\MstGenkyou;
use App\Models\MstLawrestriction;
use App\Models\MstManagementForm;
use App\Models\MstManner;
use App\Models\MstOtherReason;
use App\Models\MstOtherrestriction;
use App\Models\MstPropertyType;
use App\Models\MstPropertyTypeSub;
use App\Models\MstShared;
use App\Models\MstStatus;
use App\Models\MstStructure;
use App\Models\MstStructureSub;
use App\Models\MstUseArea;
use App\Models\MstUseDistrict;
use App\Models\RelationExterior;
use App\Models\RelationInterior;
use App\Models\RelationLawrestriction;
use App\Models\RelationLeasePhoto;
use App\Models\RelationOtherrestriction;
use App\Models\RelationPortalStatusPublic;
use App\Models\RelationShared;
use App\Models\RelationSpring;
use App\Models\Review;
use App\Models\Sai\Contruct as ContructForSaiKyoto;
use App\Models\Sai\Search as SearchForSaiKyoto;
use App\Models\TempImageLease;
use App\Services\AddressParserService;
use App\Services\CompanyApiService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Log;
use Ramsey\Uuid\Uuid;
use \SplFileObject;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Models\MstPrefecture;
use App\Models\MstCity;
use App\Models\MstTown;
use App\Models\MstLine;
use App\Models\MstStation;
use App\Models\MstSchool;
use App\Models\MstStore;
use App\Models\Article;
use App\Models\Vendor;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\News;
use App\Models\RelationCitySchool;
use App\Models\RelationVendorArticle;
use App\Models\RelationDuplicateVendorArticle;
use App\Models\RainsDuplicateArticle;
use App\Models\RainsDuplicateVendor;
use App\Models\RelationPriceHistory;
use App\Models\Facility;
use App\Models\Reform;
use App\Models\TempImage;
use App\Models\TempImageStore;
use App\Models\TempImageReform;
use App\Models\RelationStorePhoto;
use App\Models\RelationReformPhoto;
use App\Models\RelationArticleFacility;
use App\Models\RelationStoreArea;
use App\Models\MstParking;
use App\Models\RelationArticlePhoto;
use App\Models\RelationPortalPhoto;
use App\Models\RelationPortalFacility;
use App\Models\RelationPortalPublic;
use Artisan;

class AjaxController extends Controller
{
    private $csv_item_num = 196;
    private $option;
    private $parentProperty;
    private $countError;
    /**
     * 住所セレクトボックスの子要素を取得
     */
    public function changeAddress(Request $request)
    {
        $response = array();

        switch ($request->code) {
            case 'pref':
                $response = MstCity::getData($request->prefId);
                break;

            case 'city':
                $response = MstTown::getData($request->prefId, $request->cityId);
                break;
        }

        return response()->json($response);
    }

    /**
     * 都道府県セレクトボックスの子要素を取得
     */
    public function changeAddressPref(Request $request)
    {
        $response = MstCity::getData($request->prefId);
        return response()->json($response);
    }

    /**
     * 市区町村セレクトボックスの子要素を取得
     */
    public function changeAddressCity(Request $request)
    {
        $response = [];
        $response[] = MstTown::getData($request->prefId, $request->cityId);
        $prefInfo = MstPrefecture::getData($request->prefId);
        $cityInfo = MstCity::getData($request->prefId, $request->cityId);
        $response[] = RelationCitySchool::getCityListByCityId($request->prefId . $request->cityId);
        // $response[] = $this->get_gps_from_address($prefInfo[0]['name'].$cityInfo[0]['name']);
        return response()->json($response);
    }

    public function changeAddressCityName(Request $request)
    {
        $response = [];
        $pref_info = MstPrefecture::where('name', $request->prefName)->first();
        $city_info = MstCity::where('name', $request->cityName)->first();
        $town_info = MstTown::where('name', $request->townName)->where('pref_code', '=', optional($pref_info)->code)
            ->where('city_code', '=', optional($city_info)->code)->first();
        /*if ($town_info == null && $city_info != null) {
            $user = Auth::user();
            MstTown::create([
                'pref_code' => optional($pref_info)->code,
                'city_code' => optional($city_info)->code,
                'name' => $request->townName,
                'name2' => $request->townName,
                'current_name' => $request->townName,
                'town_id' => '',
                'company_id' => $user->company_id
            ]);
        }*/
        $response[] = MstTown::getData(optional($pref_info)->code, optional($city_info)->code);
        $response[] = RelationCitySchool::getCityListByCityId($request->code);
        $response[] = optional($city_info)->code;
        $response[] = optional($pref_info)->code;

        if (isset($pref_info)){
            $response[] = MstCity::getData($pref_info->code);
        }
        // $response[] = $this->get_gps_from_address($prefInfo[0]['name'].$cityInfo[0]['name']);
        return response()->json($response);
    }

    /**
     * 市区町村セレクトボックスの子要素を取得
     */
    public function changeAddressCityToSearch(Request $request)
    {
        $response = [];
        $arrResult = [];
        $towns = MstTown::where('city_code', '=', $request->cityId)
            ->where('pref_code', $request->prefId)
            //->orderby('name2')
            ->orderby('code')
            ->get();
        foreach ($towns as $town) {
            $arrResult[] = ['code' => $town->code, 'name' => $town->name.$town->chome_name.$town->koaza_name];
        }

        $response[] = $arrResult;

        if($request->prefId == '-1'){
            $request->prefId = @MstTown::where('city_code', '=', $request->cityId)->orderby('code')->first()->pref_code ?? '';
        }
        //$response[] = MstTown::getData('', $request->cityId);
        $response[] = MstSchool::getPrimarySchoolByAddress($request->prefId, $request->cityId);
        $response[] = MstSchool::getSecondarySchoolByAddress($request->prefId, $request->cityId);

        return response()->json($response);
    }

    /**
     * 市区郡、路線・駅名を取得
     */
    public function changeAddressPrefStation(Request $request)
    {
        $response = [];
        if (isset($request->prefId)) {
            // 市区郡を取得
            $response[] = MstCity::getData($request->prefId);
            // 路線・駅名を取得
            $response[] = MstStation::getDataByCode($request->prefId);
        }
        return response()->json($response);
    }

    public function changeAddressCityStation(Request $request)
    {
        $response = [];
        if (isset($request->prefId)) {
            $code = $request->prefId;
            if ($request->cityId != 0) {
                $code .= $request->cityId;
            }
            // 路線・駅名を取得
            $name = $request->get('name');
            $response[] = MstStation::getDataByCode($code, $name);
        }
        return response()->json($response);
    }

    /**
     * 路線を取得
     */
    public function getLine(Request $request)
    {
        $response = [];
        if (isset($request->prefId)) {
            $code = $request->prefId;
            if ($request->cityId != 0) {
                $code .= $request->cityId;
            }
            // 路線・駅名を取得
            $response = MstStation::getDataDistinctByCode($code, $request->key);
        }
        return response()->json($response);
    }

    /**
     * 駅を取得
     */
    public function getStation(Request $request)
    {
        $response = [];
        if (isset($request->line)) {
            // 路線・駅名を取得
            $response = MstStation::getDataStation($request->line, $request->key);
        }
        return response()->json($response);
    }

    public function changeAddressCityStationSub(Request $request)
    {
        $response = [];
        if (isset($request->prefId) && isset($request->cityId)) {
            $code = $request->prefId;
            if ($request->cityId != 0) {
                $code .= $request->cityId;
            }
            // 路線・駅名を取得
            $response[] = MstStation::getDataDistinctByCode($code, $request->key);
        }
        return response()->json($response);
    }

    public function changeAddressCityESchool(Request $request)
    {
        $cityQuery = MstCity::where("name", $request->get("city"));
        if (isset($request->pref_code)){
            $cityQuery->where('pref_code', $request->pref_code);
        }
        $city = $cityQuery->first();

        if (auth()->user()->company_id != 1) {
            $response = [];
            $schools = MstSchool::getPrimarySchoolByAddress(optional($city)->pref_code, optional($city)->code);
            $response = array_merge($response, $schools);
            $response = collect($response);
            $response = $response->unique("code");

            return response()->json($response);
        }
        $response = [];
        $schools = RelationCitySchool::getDataElementarySchool(optional($city)->pref_code . optional($city)->code);
        if (!empty($schools)) {
            foreach ($schools as $school) {
                $schoolsData = MstSchool::getSchoolName($school);
                $response = array_merge($response, $schoolsData);
            }
        }
        $response = collect($response);
        $response = $response->unique("code");

        return response()->json($response);
    }

    public function changeAddressCityJSchool(Request $request)
    {
        $cityQuery = MstCity::where("name", $request->get("city"));
        if (isset($request->pref_code)){
            $cityQuery->where('pref_code', $request->pref_code);
        }
        $city = $cityQuery->first();
        if (auth()->user()->company_id != 1) {
            $response = [];
            $schools = MstSchool::getSecondarySchoolByAddress(optional($city)->pref_code, optional($city)->code);
            $response = array_merge($response, $schools);
            $response = collect($response);
            $response = $response->unique("code");

            return response()->json($response);
        }
        $response = [];
        $schools = RelationCitySchool::getDataJuniorSchool(optional($city)->pref_code . optional($city)->code);
        if (!empty($schools)) {
            foreach ($schools as $school) {
                $schoolsData = MstSchool::getSchoolName($school);
                $response = array_merge($response, $schoolsData);
            }
        }
        $response = collect($response);
        $response = $response->unique("code");

        return response()->json($response);
    }

    /**
     * 指定ユーザーを削除
     */
    public function deleteUser(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user($request);

        $response = [];
        $id = $request->id;
        if ($user->id != $id) {
            $user_info = UserInfo::where('employee_number', $id)->where('company_id', $user->company_id)->first();
            User::where('id', $user_info->id)->delete();
            UserInfo::where('employee_number', $id)->where('company_id', $user->company_id)->delete();

            $apiService->delStaff($id);
        }
        return response()->json($response);
    }

    /**
     * 指定お知らせを削除
     */
    public function deleteNews(Request $request)
    {
        $response = [];
        News::where('id', $request->id)->delete();
        return response()->json($response);
    }

    public function deleteLot(Request $request, CompanyApiService $apiService)
    {
        if ($request->ajax()) {
            $result = Article::where('building_id', $request->id)->first();
            $resultChild = Article::where('sale_no', $result->building_id)->get();
            if($resultChild) {
                foreach ($resultChild as $item) {
                    $item->update(['sale_no' => null]);
                }
            }
            $result->delete();
            $apiService->delLot($request->id);
//            Article::where('building_id', $request->id)->delete();
        }
    }

    /**
     * 指定施設を削除
     */
    public function deleteFacility(Request $request)
    {
        $response = [];
        Facility::where('id', $request->id)->delete();
        RelationArticleFacility::where('facility_id', '=', $request->id)->delete();
        return response()->json($response);
    }

    /**
     * 指定施設を削除
     */
    public function deleteStore(Request $request)
    {
        $response = [];
        $store = MstStore::where('id', $request->id)->first();
        MstStore::where('id', $request->id)->delete();
        //Remove store image
        RelationStorePhoto::where('store_id', $store->code)->delete();
        return response()->json($response);
    }

    /**
     * 指定おすすめ登録
     */
    public function saveRecommend(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();

        // 既に登録されているオススメを取得
        $old = Article::select('building_id')->where('recommend', '=', 1)->orderby('recommend_num')->get();

        $id_list = explode(',', $request->id);
        $response = [];
        $num = 1;
        foreach ($id_list as $id) {
            $data = ['recommend' => 1, 'recommend_num' => $num];
            Article::where('building_id', '=', $id)->update($data);
            $num++;
        }

        foreach ($old as $row) {
            $data = ['recommend' => 1, 'recommend_num' => $num];
            Article::where('building_id', '=', $row->id)->update($data);
            $num++;
        }
        $data_send = [];
        $data_send['ids'] = $id_list;
        $apiService->saveRecommend($data_send);

        return response()->json($response);
    }


    /**
     * 指定おすすめ削除
     */
    public function deleteRecommend(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $response = [];
        $data = ['recommend' => 0, 'recommend_num' => null];
        Article::where('building_id', '=', $request->id)->update($data);

        $article = Article::where('recommend', '=', 1)->orderBy('recommend_num')->get();
        $num = 1;
        foreach ($article as $row) {
            $data = ['recommend_num' => $num];
            Article::where('building_id', '=', $row->id)->update($data);
            $num++;
        }
        $data_send = [];
        $data_send['id'] = $request->id;

        $apiService->delRecommend($data_send);

        return response()->json($response);
    }

    /**
     * おすすめソート
     */
    public function setRecommendRank(Request $request, CompanyApiService $apiService)
    {
        $response = [];
        $data = ['recommend_num' => $request->num];
        Article::where('building_id', '=', $request->id)->update($data);
        $apiService->setRecommendRank($request->all());
        return response()->json($response);
    }

    /**
     * 指定リフォーム削除
     */
    public function deleteReform(Request $request)
    {
        $user = Auth::user();
        $response = [];

        Reform::where('code', $request->id)->delete();

        $reform = Reform::orderBy('reform_num')->get();
        $num = 1;
        foreach ($reform as $row) {
            $data = ['reform_num' => $num];
            Reform::where('code', $row->code)->update($data);
            $num++;
        }

        return response()->json($response);
    }

    /**
     * リフォームソート
     */
    public function setReformRank(Request $request, CompanyApiService $apiService)
    {
        $response = [];
        $data = ['reform_num' => $request->num];
        Reform::where('code', '=', $request->id)->first()->update($data);

        $data_send = Reform::where('code', '=', $request->id)->first();
        $data_send['photo_data'] = RelationReformPhoto::where('reform_id', '=', $request->id)->get();
        $apiService->editReform($request->id, $data_send);
        return response()->json($response);
    }

    public function searchShopCharge(Request $request)
    {
        $user = Auth::user();
        $response = UserInfo::getCharge($user->company_id, $request->id);

        return response()->json($response);
    }

    public function setImage(Request $request)
    {
        $file = $request->file('photo');
        $content = $this->convertImageSource(file_get_contents($file->getRealPath()));
        $data = ['num' => $request['num'], 'id' => '', 'flag' => $request['flag'] ?? '', 'content' => $content ?? ''];
        return view('admin.objects.components.add-photo-image', $data);
    }

    /*
    * レインズCSVのアップロード
    */
    public function uploadCsv(Request $request)
    {
        try {
            $res = "success";

            // CSVファイルのアップロードと読み込み
            $aryDataList = $this->readCsv();
            $j = 0;
            $ar_row = [];
            foreach ($aryDataList as $i => $row) {
                if (mb_detect_encoding(implode($row)) != 'UTF-8') {
                    mb_convert_variables("UTF-8", "SJIS", $row);
                }

                // 物件情報の登録
                try {
                    if(count($row) <= 8){
                        if($i>9){
                            if(count($ar_row) == 5){
                                if(isset($ar_row[0][1]) && $ar_row[0][1] != ''){
                                    //$check = RainsDuplicateArticle::where('rains_no', intval($ar_row[0][1]));
                                    //if($check->count() == 0 && $ar_row[0][1] != ''){
                                        if(!empty($ar_row) && count($ar_row)>0){
                                            $this->saveRainsData_v2($ar_row);
                                        }
                                    //}
                                }
                                $ar_row = [];
                                $ar_row[] = $row;

                            }else{
                                $ar_row[] = $row;
                            }
                        }
                    }else{
                        $this->saveRainsData($row);
                    }

                } catch (\Exception $exception) {
                    Log::debug($exception->getMessage());
                } catch (\Error $error) {
                }
            }

            return $res;
        } catch (Exception $e) {
            Log::debug( "例外キャッチ：", $e->getMessage());
        }
    }

    function saveRainsData_v2($data)
    {
        $user = Auth::user();
        // CSVの物件情報を登録予定物件として登録
        $article = new RainsDuplicateArticle;
        $article->company_id = $user->company_id;
        $article->rains_no = intval($data[0][1]);

        if($data[0][2] == '売地'){
            $article->property = 1;
        }
        if($data[0][2] == '新築マンション'){
            $article->property = 6;
            $article->property_sub = 1;
        }
        if($data[0][2] == '中古マンション'){
            $article->property = 6;
            $article->property_sub = 2;
        }
        if($data[0][2] == '新築タウン'){
            $article->property = 7;
            $article->property_sub = 1;
        }
        if($data[0][2] == '中古タウン'){
            $article->property = 7;
            $article->property_sub = 2;
        }
        if($data[0][2] == '新築リゾート' || $data[0][2] == '中古リゾート' || $data[0][2] == 'その他'){
            $article->property = null;
        }
        if($data[0][2]  == '新築戸建'){
            $article->property = 4;
            $article->property_sub = 1;
        }
        if($data[0][2]  == '中古戸建'){
            $article->property = 4;
            $article->property_sub = 2;
        }
        if($data[0][2]  == '新築テラス'){
            $article->property = 5;
            $article->property_sub = 1;
        }
        if($data[0][2]  == '中古テラス'){
            $article->property = 5;
            $article->property_sub = 2;
        }

        if($data[0][2]  == '底地権'){
            $article->property = 3;
        }

        if($data[0][2]  == '借地権'){
            $article->property = 2;
        }

        $address = $data[0][5];
        $building = $data[1][5];

        $address2 = '';
        $address3 = '';
        if (isset($address) && $address != ''){
            $addressGoogle = AddressParserService::strToAddress($address, $building);
            $article->address1 = $addressGoogle['pref']['code'] ?? '';
            $article->address2 = $addressGoogle['city']['code'] ?? '';
            $article->address3 = $addressGoogle['town']['code'] ?? '';

            $address2 = $addressGoogle['city']['name'] ?? '';
            if (isset( $addressGoogle['town'])){
                $address3 = $addressGoogle['town']['name'] . $addressGoogle['town']['chome_name']. $addressGoogle['town']['koaza_name'];
            }
            $article->zip = $addressGoogle['postcode'] ?? '';
            if (isset($addressGoogle['town'])){
                $address4Arr = explode($addressGoogle['town']['name'], $address);
                $article->address4 = (count($address4Arr) > 1) ? end($address4Arr) : '';
//                if (!str_contains($addressGoogle['town']['name'], '丁目' ) && !str_contains($addressGoogle['town']['name'], '字')){
//                    $article->address4 = $addressGoogle['sublocality_level_3'];
//                }
            }
        }
//        $add1 = explode('県', $address);
//        $address1 = $add1[0].'県';
//        //$add2 = explode('市', $add1[1]);
//        //$address2 = $add2[0].'市';
//        $add2 = explode('区', $add1[1]);
//        $address2 = $add2[0].'区';
//        $add2 = explode('区', $add1[1]);
//        if(count($add2)>1){
//            $address2 = $add2[0].'区';
//            $address3 = $add2[1];
//        }else{
//            $add2 = explode('市', $add1[1]);
//            if(count($add2)>1){
//                $address2 = $add2[0].'市';
//                $address3 = $add2[1];
//            }else{
//                $add2 = explode('町', $add1[1]);
//                if(count($add2)>1){
//                    $address2 = $add2[0].'町';
//                    $address3 = $add2[1];
//                }else{
//                    $add2 = explode('村', $add1[1]);
//                    if(count($add2)>1){
//                        $address2 = $add2[0].'村';
//                        $address3 = $add2[1];
//                    }
//                }
//            }
//        }

        // FB LWS-226
        if($article->property == 2 || $article->property == 3){
            $article->name = $address2.$address3;
            $article->land_area = 0;
            $article->land_area_val = str_replace(['㎡',','], '', $data[0][4]);
        }

        if($article->property == 1) {
            $article->building_rate = str_replace('%', '', $data[2][3]);
            $article->volume_rate = str_replace('%', '', $data[3][3]);
            $land_dir = $data[4][4];
            $land_info = [
                '北'     =>  1,
                '北東'   =>  2,
                '東'     =>  3,
                '南東'   =>  4,
                '南'     =>  5,
                '南西'   =>  6,
                '西'     =>  7,
                '北西'   =>  8
            ];
            $check_land = mb_substr($land_dir,0,2);

            if(!isset($land_info[$check_land])){
                $check_land = mb_substr($land_dir,0,1);
            }
            if(isset($land_info[$check_land])){
                $article->land_direction1 = $land_info[$check_land];
                $article->road_width1 = str_replace([$check_land, 'm'], '', $land_dir);
            }else{
                $article->road_width1 = str_replace('m', '', $land_dir);
            }

            $article->name = $address2.$address3;

            $article->land_area = 0;
            $article->land_area_val = str_replace(['㎡',','], '', $data[0][4]);
        }
//        if($user->company_id == 3 || $user->company_id == 4){
//            $address3_name = $address3;
//            $address1_name = $address1;
//            $address2_name = $address2;
//        }
        if($article->property == 6 || $article->property == 7) {
            if($data[1][5] == '' || $data[1][5] == '-'){
                $article->name = '空欄';
            }else{
                $article->name = $data[1][5];
            }
            $article->name = !empty($data[1][5]) ? $data[1][5] : '空欄';
            $article->total_area_val = str_replace(['㎡','.00'], '', $data[0][4]);
            $article->floor = str_replace('階', '', $data[1][6]);
            $article->whereabouts = $article->floor;
            $floor_plan = $data[1][7];
            if($floor_plan == 'ワンルーム'){
                $article->floor_plan = 1;
                $article->floor_plan_type = 3;
            }else {
                $article->floor_plan = substr($floor_plan, 0, 1);
                $floor_plan_type = substr($floor_plan, 1);
                $ar_floor_type = [
                    'ＤＫ' => 1,
                    'ＬＤＫ' => 2,
                    'Ｒ' => 3,
                    'Ｋ' => 4,
                    'ＳＫ' => 5,
                    'ＳＤＫ' => 6,
                    'ＬＫ' => 7,
                    'ＳＬＫ' => 8,
                    'ＳＬＤＫ' => 9
                ];
                $article->floor_plan_type = $ar_floor_type[$floor_plan_type];
            }
            //management
            if($data[2][2]!=''){
                $article->management = 1;
                $article->management_cost = str_replace([',','円'], '', $data[2][2]);
            }

            if($data[4][2] != ''){
                $this->calculateDate($data[4][2], $article);
            }
        }
        if($article->property == 4 || $article->property == 5){
            $article->total_area_val = str_replace(['㎡', '?'], '', $data[1][4]);
            $article->land_area_val = str_replace(['㎡','?',','], '', $data[0][4]);

            if($data[4][2] != ''){
                $this->calculateDate($data[4][2], $article);
            }

            $article->name = $address2.$address3;
            $land_dir = $data[3][4];
            $land_info = [
                '北'     =>  1,
                '北東'   =>  2,
                '東'     =>  3,
                '南東'   =>  4,
                '南'     =>  5,
                '南西'   =>  6,
                '西'     =>  7,
                '北西'   =>  8
            ];
            $check_land = mb_substr($land_dir,0,2);
            if(!isset($land_info[$check_land])){
                $check_land = mb_substr($land_dir,0,1);
            }
            if($check_land!='-' && !is_numeric($check_land)){
                $article->land_direction1 = $land_info[$check_land];
            }
            if(!is_numeric($check_land)){
                $article->road_width1 = str_replace([$check_land, 'm'], '', $land_dir);
            }else{
                $article->road_width1 = str_replace('m', '', $check_land);
            }
            $floor_plan = $data[1][7];
            if($floor_plan == 'ワンルーム'){
                $article->floor_plan = 1;
                $article->floor_plan_type = 3;
            }else{
                $article->floor_plan = substr($floor_plan, 0,1);
                $floor_plan_type = substr($floor_plan, 1);
                $ar_floor_type = [
                    'ＤＫ'    =>  1,
                    'ＬＤＫ'   =>  2,
                    'Ｒ'     =>  3,
                    'Ｋ'     =>  4,
                    'ＳＫ'    =>  5,
                    'ＳＤＫ'   =>  6,
                    'ＬＫ'    =>  7,
                    'ＳＬＫ'    =>  8,
                    'ＳＬＤＫ'  =>  9
                ];
                $article->floor_plan_type = $ar_floor_type[$floor_plan_type];
            }
        }
        // 取引態様
        if($data[1][1]!=''){
            //$article->manner = MstManner::where('name', 'like', '%'.$data[1][1].'%')->first()->code;
            $data[1][1] = str_replace(' オーナーチェンジ', '', $data[1][1]);

            $qr = MstManner::where('name', 'like', '%'.$data[1][1].'%');
            if($qr->count() > 0){
                $article->company_manner = $qr->first()->code;
            }
        }
        $price = str_replace(["万円",","], '', $data[1][2]);
        $article->price = $price;

//        $address_info = MstTown::getDataByAddress($address3);
//        $zip = $this->getZipCode($address);
//        $article->zip = $zip;
//        $address1 = 0;
//        $address2 = 0;
//        $address3 = 0;
//        if (isset($address_info[0]['pref_code'])) {
//            $address1 = intval($address_info[0]['pref_code']);
//        }
//        if (isset($address_info[0]['pref_code'])) {
//            $address2 = intval($address_info[0]['city_code']);
//        }
//        if (isset($address_info[0]['pref_code'])) {
//            $address3 = intval($address_info[0]['code']);
//        }
//        $article->address1 = $address1;
//        $article->address2 = $address2;
//        $article->address3 = $address3;

       // $article->address4 = '';
        $article->revenue = 0;
        // 対象店舗の取得
//        if($user->company_id == 3 || $user->company_id == 4){
//            $address1 = MstPrefecture::where('name', '=', $address1_name)->first()->code;
//            $address2 = MstCity::where('name', '=', $address2_name)->first()->code;
//
//            $shop = RelationStoreArea::getShopIdCompany3($address1, $address2);
//            $article->address1 = $address1;
//            $article->address2 = $address2;
//            $check_towns = MstTown::getData($address1, $address2);
//
//            if(!empty($check_towns)){
//                foreach ($check_towns as $tw){
//                    if(strpos($address3_name, $tw['name']) !== false){
//                        $article->address3 = $tw['code'];
//                        $article->address4 = str_replace($tw['name'], '', $address3_name);
//                        break;
//                    }
//                }
//            }
//        }else{
//            $shop = RelationStoreArea::getShopId($address1, $address2, $address3);
//        }

        $shop = RelationStoreArea::getShopId($article->address1 , $article->address2, $article->address3);

        $other_shop = MstStore::getIdByName('その他');
        if($other_shop == null){
            $other_shop_code = '';
        }else{
            $other_shop_code = $other_shop->code;
        }
        $article->shop = $shop->store_id ?? $other_shop_code;

        if($data[2][5] != '') {
            $main_trafic_line = explode('　', $data[2][5]);
            if ($main_trafic_line[0] == '京浜急行線') {
                $main_trafic_line[0] = '京急本線';
            }
            if ($main_trafic_line[0] == '横浜ブルー') {
                $main_trafic_line[0] = '横浜市営ブルーライン';
            }
            if ($main_trafic_line[0] == '田園都市線') {
                $main_trafic_line[0] = '東急田園都市線';
            }
            if ($main_trafic_line[0] == 'こどもの国') {
                $main_trafic_line[0] = '東急こどもの国線';
            }
            if ($main_trafic_line[0] == '横浜グリー') {
                $main_trafic_line[0] = '横浜市営グリーンライン';
            }
            if ($main_trafic_line[0] == '東横線') {
                $main_trafic_line[0] = '東急東横線';
            }
            if ($main_trafic_line[0] == '相鉄線') {
                $main_trafic_line[0] = '相鉄本線';
            }
            if ($main_trafic_line[0] == 'いずみ野線') {
                $main_trafic_line[0] = '相鉄いずみ野線';
            }
            if ($main_trafic_line[0] == 'みなとM線') {
                $main_trafic_line[0] = '横浜高速鉄道みなとみらい線';
            }
            if ($main_trafic_line[0] == '京急逗子線') {
                $main_trafic_line[0] = '京急逗子線';
            }
            if ($main_trafic_line[0] == 'シーサイド') {
                $main_trafic_line[0] = '横浜シーサイドライン';
            }
            if ($main_trafic_line[0] == '湘南モノレ') {
                $main_trafic_line[0] = '湘南モノレール';
            }
            if ($main_trafic_line[0] == '江ノ電') {
                $main_trafic_line[0] = '江ノ島電鉄';
            }

            if ($main_trafic_line[0] == '根岸線' || $main_trafic_line[0] == '根岸線' || $main_trafic_line[0] == '京浜東北線' || $main_trafic_line[0] == '鶴見線' || $main_trafic_line[0] == '東海道本線' || $main_trafic_line[0] == '横須賀線') {
                $main_trafic_line[0] = 'JR' . $main_trafic_line[0];
            }

            $main_trafic_line[0] = MstLine::convertLineName($main_trafic_line[0]);

            $article->main_traffic_line = $main_trafic_line[0];
            $line_data = MstLine::getDataByName($main_trafic_line[0]);

            if (!empty($line_data)) {
                $article->main_traffic_line_id = $line_data->id;
            }

            $station_data = null;
            if (count($main_trafic_line) > 1) {
                $station_data = MstStation::getDataByName($main_trafic_line[0], $main_trafic_line[1]);
            }

            $article->main_traffic_station = $main_trafic_line[1] ?? "";
            if (!empty($station_data)) {
                $article->main_traffic_station_id = $station_data->id;
            }
        }
        if(isset($data[2][6]) && $data[2][6] != '') {
            $main_trafic = explode('　', $data[2][6]);

            if ($main_trafic[0] == '徒歩') {
                $article->main_traffic = 1;
                $article->main_traffic_time = str_replace('分', '', $main_trafic[1]);
            } else {
                $article->main_traffic = 2;
                $article->main_traffic_bus = null;
                if (count($main_trafic) == 3) {
                    $article->main_traffic_bus_walk = str_replace('分/バス', '', $main_trafic[1]);
                    $article->main_traffic_bus_time = str_replace('分', '', $main_trafic[2]);
                } else {
                    $article->main_traffic_bus_time = str_replace('分', '', $main_trafic[1]);
                }
            }
        }
        $use_area = $data[1][3];
        $property = $data[0][3];

        if($data[2][1] == '-' || $data[2][1] == '公開中'){
            $article->status = 1;
        }

        $article->sales_company = $data[3][5];

        $ar_use_area = [
            '一低'    =>  '1種低層',
            '二低'    =>  '2種低層',
            '一中'	 => '1種中高',
            '二中'	 => '2種中高',
            '一住'   =>   '1種住居',
            '二住'	 =>  '2種住居',
            '準住'    =>  '準住居',
            '近商'	 =>  '近隣商業',
            '無指定'   =>	'無',
            '準工'    =>  '準工業',
            '工業'    =>  '工業',
            '工専'    =>  '工専',
            '田園'    =>  '田園住居',
            '-'       =>    '未選択'
        ];

        $article->use_area = null;
        if(isset($ar_use_area[$use_area])){
            $new_use_area = $ar_use_area[$use_area];
            $use_area = MstUseArea::where('name',  $new_use_area);
            if($use_area->count()>0){
                $article->use_area = $use_area->first()->code;
            }
        }

        $article->construction_company = null;
        $article->management_company = null;
        $article->management_form = null;
        $article->land_not = null;
        //dd($article);
        $article->save();

        // 業者登録
        $vendor_data = [];
        $vendor_data['name'] = $article->sales_company;
        $vendor_data['company_id'] = $user->company_id;
        $vendor_data['vendor_charge'] = '';
        $vendor_data['vendor_tel1'] = $data[4][5];
        $vendor_data['vendor_tel2'] = null;
        $vendor_data['vendor_mail'] = null;
        $vendor_data['manner'] = $article->company_manner;

        // 重複する業者がなければ登録
        RelationDuplicateVendorArticle::where(['article_id' => $article->id])->delete();
        if($data[4][5] != ''){
            $vendor = Vendor::where(['name' => $article->sales_company])->where(['vendor_tel1' => $data[4][5]])->where(['company_id' => $user->company_id])->first();
            if(is_null($vendor)){
                $vendor = Vendor::where(['name' => $article->sales_company])->where(['company_id' => $user->company_id])->first();
            }
        }else{
            $vendor = Vendor::where(['name' => $article->sales_company])->where(['company_id' => $user->company_id])->first();
        }

        if (is_null($vendor)) {
            $vendor = new Vendor;
            $vendor->fill($vendor_data)->save();
        }

        $relation = new RelationDuplicateVendorArticle;
        $relation->article_id = $article->id;
        $relation->vendor_id = $vendor->id;
        $relation->charge = null;
        $relation->company_id = $user->company_id;
        //$relation -> manner = $data[42];
        $relation->save();
        return $article->id;
    }

    function saveRainsData($data)
    {
        $user = Auth::user();
        // CSVの物件情報を登録予定物件として登録
        $article = new RainsDuplicateArticle;
        $article->company_id = $user->company_id;
        $article->rains_no = intval($data[0]);
        $article->status = intval($data[1]);

        if ($data[2] == "1") {
            if($data[3] == "1"){
                $article->property = 1;
                $article->property_sub = "";
            }
            if($data[3] == "2"){
                $article->property = 2;
                $article->property_sub = "";
            }
            if($data[3] == "3"){
                $article->property = 3;
                $article->property_sub = "";
            }
        } else if ($data[2] == "2") {
            if($data[3] == "1"){
                $article->property = 4;
                $article->property_sub = 1;
            }
            if($data[3] == "2"){
                $article->property = 4;
                $article->property_sub = 2;
            }
            if($data[3] == "3"){
                $article->property = 5;
                $article->property_sub = 1;
            }
            if($data[3] == "4"){
                $article->property = 5;
                $article->property_sub = 2;
            }
        } else if ($data[2] == "3") {
            if($data[3] == "1"){
                $article->property = 6;
                $article->property_sub = 1;
            }
            if($data[3] == "2"){
                $article->property = 6;
                $article->property_sub = 2;
            }
            if($data[3] == "3"){
                $article->property = 7;
                $article->property_sub = 1;
            }
            if($data[3] == "4"){
                $article->property = 7;
                $article->property_sub = 2;
            }
        }

        $address_info = MstTown::getDataByAddress($data[16]);
        $address = $data[14] . $data[15] . $data[16];
        $zip = $this->getZipCode($address);
        $article->zip = $zip;
        $address1 = 0;
        $address2 = 0;
        $address3 = 0;
        if (isset($address_info[0]['pref_code'])) {
            $address1 = intval($address_info[0]['pref_code']);
        }
        if (isset($address_info[0]['pref_code'])) {
            $address2 = intval($address_info[0]['city_code']);
        }
        if (isset($address_info[0]['pref_code'])) {
            $address3 = intval($address_info[0]['code']);
        }
        $article->address1 = $address1;
        $article->address2 = $address2;
        $article->address3 = $address3;

        $article->address4 = $data[17];
        $article->name = empty($data[18]) ? $data[15] . $data[16] : $data[18];
        $article->name_portal = empty($data[18]) ? $data[15] . $data[16] : $data[18];
        if ($data[2] == 3) {
            $article->name_apartment = $data[18];
        }
        if (empty($data[19])) {
            $room_num = null;
        } else {
            $room_num = intval($data[19]);
        }
        $article->room_num = $room_num;

        $article->revenue = 0;

        // 対象店舗の取得
        $shop = RelationStoreArea::getShopId($address1, $address2, $address3);
        $other_shop = MstStore::getIdByName( 'その他');
        $article->shop = $shop->store_id ?? $other_shop->code;

        // 主要交通
        if (!empty($data[22])) {

            $article->main_traffic = 1;
            if ($data[22] == '横浜ブルー') {
                $line_name = '横浜市営ブルーライン';
            } elseif ($data[22] == 'いずみ野線') {
                $line_name = '相鉄いずみ野線';
            } elseif ($data[22] == '京急逗子線') {
                $line_name = '京急逗子線';
            } elseif ($data[22] == '京浜急行線') {
                $line_name = '京急本線';
            } elseif ($data[22] == '京浜東北線') {
                $line_name = 'JR京浜東北線';
            } elseif ($data[22] == 'こどもの国') {
                $line_name = '東急こどもの国線';
            } elseif ($data[22] == 'シーサイド') {
                $line_name = '横浜シーサイドライン';
            } elseif ($data[22] == '相鉄線') {
                $line_name = '相鉄本線';
            } elseif ($data[22] == '鶴見線') {
                $line_name = 'JR鶴見線';
            } elseif ($data[22] == '田園都市線') {
                $line_name = '東急田園都市線';
            } elseif ($data[22] == '東横線') {
                $line_name = '東急東横線';
            } elseif ($data[22] == '根岸線') {
                $line_name = 'JR根岸線';
            } elseif ($data[22] == 'みなとM線') {
                $line_name = '横浜高速鉄道みなとみらい線';
            } elseif ($data[22] == '横須賀線') {
                $line_name = 'JR横須賀線';
            } elseif ($data[22] == '横浜グリー') {
                $line_name = '横浜市営グリーンライン';
            } elseif ($data[22] == '横浜線') {
                $line_name = 'JR横浜線';
            } elseif ($data[22] == '横浜ブルー') {
                $line_name = '横浜市営ブルーライン';
            } else {
                $line_name = $data[22];
            }

            $line_name = MstLine::convertLineName($line_name);

            $article->main_traffic_line = $line_name;
            $line_data = MstLine::getDataByName($line_name);
            if (!empty($line_data)) {
                $article->main_traffic_line_id = $line_data->id;
            }

            $station_data = null;
            if (!empty($data[23])) {
                $station_data = MstStation::getDataByName($line_name, $data[23]);
            }
            $article->main_traffic_station = $data[23];
            if (!empty($station_data)) {
                $article->main_traffic_station_id = $station_data->id;
            }
            $article->main_traffic_time = empty($data[24]) ? null : intval($data[24]);

            if ($data[26] != null && $data[28] != null && $data[29] != null) {
                $article->main_traffic = 2;
                $article->main_traffic_bus_time = empty($data[26]) ? null : intval($data[26]);
                $article->main_traffic_bus = empty($data[28]) ? null : $data[28];
                $article->main_traffic_bus_walk = empty($data[29]) ? null : intval($data[29]);
            }
        }

        // 補助交通１
        if (!empty($data[27])) {


            $article->sub_traffic1 = 2;
            if ($data[27] == '横浜ブルー') {
                $line_name = '横浜市営ブルーライン';
            } elseif ($data[27] == 'いずみ野線') {
                $line_name = '相鉄いずみ野線';
            } elseif ($data[27] == '京急逗子線') {
                $line_name = '京急逗子線';
            } elseif ($data[27] == '京浜急行線') {
                $line_name = '京急本線';
            } elseif ($data[27] == '京浜東北線') {
                $line_name = 'JR京浜東北線';
            } elseif ($data[27] == 'こどもの国') {
                $line_name = '東急こどもの国線';
            } elseif ($data[27] == 'シーサイド') {
                $line_name = '横浜シーサイドライン';
            } elseif ($data[27] == '相鉄線') {
                $line_name = '相鉄本線';
            } elseif ($data[27] == '鶴見線') {
                $line_name = 'JR鶴見線';
            } elseif ($data[27] == '田園都市線') {
                $line_name = '東急田園都市線';
            } elseif ($data[27] == '東横線') {
                $line_name = '東急東横線';
            } elseif ($data[27] == '根岸線') {
                $line_name = 'JR根岸線';
            } elseif ($data[27] == 'みなとM線') {
                $line_name = '横浜高速鉄道みなとみらい線';
            } elseif ($data[27] == '横須賀線') {
                $line_name = 'JR横須賀線';
            } elseif ($data[27] == '横浜グリー') {
                $line_name = '横浜市営グリーンライン';
            } elseif ($data[27] == '横浜線') {
                $line_name = 'JR横浜線';
            } elseif ($data[27] == '横浜ブルー') {
                $line_name = '横浜市営ブルーライン';
            } else {
                $line_name = $data[27];
            }

            $line_name = MstLine::convertLineName($line_name);

            $line_data = MstLine::getDataByName($line_name);
            $station_data = null;
            if (!empty($data[28])) {
                $station_data = MstStation::getDataByName($line_name, $data[28]);
            }
            $article->sub_traffic1_line = $line_name;
            if (!empty($line_data)) {
                $article->sub_traffic1_line_id = $line_data->id;
            }
            $article->sub_traffic1_station = $data[28];
            if (!empty($station_data)) {
                $article->sub_traffic1_station_id = $station_data->id;
            }
            $article->sub_traffic1_time = empty($data[29]) ? null : intval($data[29]);
        }

        $article->memo1 = empty($data[193]) ? null : $data[193];
        $article->memo2 = empty($data[194]) ? null : $data[194];


        $article->price = empty($data[46]) ? null : intval($data[46]) / 10000;
        $article->tax = empty($data[47]) ? 1 : 2;

        $article->building_rate = empty($data[85]) ? null : intval($data[85]);
        $article->volume_rate = empty($data[86]) ? null : intval($data[86]);

        //$article->road_burden = empty($data[58]) ? null : intval($data[58]);
        if(empty($data[58]) || $data[58] == '' || $data[58] == 0){
            $article->road_burden = null;
        }else{
            if(intval($data[58]) == 2){
                $article->road_burden = 0;
            }else{
                $article->road_burden = intval($data[58]);
            }
        }
        $article->road_burden_area = empty($data[59]) ? null : intval($data[59]);

        if (!empty($data[60])) {
            $article->balcony_area = 1;
            $article->balcony_area_val = floatval($data[60]);
        }

        if (!empty($data[61])) {
            $article->balcony_area = 1;
            $article->balcony_area_val = floatval($data[61]);
        }

        $article->ground = empty($data[80]) ? null : intval($data[80]);

        $article->set = empty($data[62]) ? null : intval($data[62]);
        $article->set_area = empty($data[64]) ? null : intval($data[64]);


        $article->total_unit = empty($data[179]) ? null : $data[179];
        preg_match("@([0-9]{4})([0-9]{1,2})@", $data[178], $age);
        $article->age_year = empty($age[1]) ? null : $age[1];
        $article->age_month = empty($age[2]) ? null : $age[2];
        $article->construction = empty($data[172]) ? null : $data[172];
        $article->floor = empty($data[175]) ? null : $data[175];
        $article->whereabouts = empty($data[177]) ? null : $data[177];
        $article->underground = empty($data[176]) ? null : $data[176];

        $article->land_area = empty($data[51]) ? null : $data[51];
        $article->total_area = $article->land_area;
        $article->land_area_val = empty($data[52]) ? null : $data[52];

        if ($data[2] == "1") {
            $article->total_area_val = empty($data[70]) ? null : $data[70];
        } else if ($data[2] == "2") {
            $article->total_area_val = empty($data[56]) ? null : $data[56];
        } else if ($data[2] == "3") {
            $article->total_area_val = empty($data[57]) ? null : $data[57];
        }

        if (!empty($data[37]) && $data[37] == 4) {
            $article->land_delivery = 3;
        } else {
            $article->land_delivery = empty($data[37]) ? null : $data[37];
        }

        preg_match("@([0-9]{4})([0-9]{1,2})@", $data[38], $age);
        $article->delivery_year = empty($age[1]) ? null : $age[1];
        $article->delivery_month = empty($age[2]) ? null : $age[2];

        $article->land_kind1 = empty($data[111]) ? null : $data[111];
        $article->land_direction1 = empty($data[114]) ? null : $data[114];
        $article->road_width1 = empty($data[115]) ? null : $data[115];
        $article->frontage1 = empty($data[112]) ? null : $data[112];

        $article->land_kind2 = empty($data[116]) ? null : $data[116];
        $article->land_direction2 = empty($data[119]) ? null : $data[119];
        $article->road_width2 = empty($data[120]) ? null : $data[120];
        $article->frontage2 = empty($data[117]) ? null : $data[117];

        $article->land_kind3 = empty($data[121]) ? null : $data[121];
        $article->land_direction3 = empty($data[124]) ? null : $data[124];
        $article->road_width3 = empty($data[125]) ? null : $data[125];
        $article->frontage3 = empty($data[122]) ? null : $data[122];

        $article->city_plan = empty($data[81]) ? null : $data[81];

        $article->use_area = empty($data[82]) ? null : $data[82];
        $article->land_use = empty($data[83]) ? null : $data[83];

        $article->section = empty($data[67]) ? null : $data[67];

        if (!empty($data[42])) {
            $new_manner = [
                1 => 1,
                2 => 6,
                3 => 5,
                4 => 4,
                5 => 3
            ];
            $data[42] = $new_manner[$data[42]];
        }
        $article->company_manner = $data[42];


        if (!empty($data[101])) {
            $article->management = 1;
            $article->management_cost = intval($data[101]);
        }

        if (!empty($data[103])) {
            $article->repair = 1;
            $article->repair_cost = intval($data[103]);
        }


        $article->sales_company = empty($data[108]) ? null : $data[108];
        $article->construction_company = empty($data[107]) ? null : $data[107];
        $article->management_company = empty($data[99]) ? null : $data[99];
        $article->management_form = empty($data[70]) ? null : $data[70];


        $article->land_condition = empty($data[95]) ? null : $data[95];
        $dataStatus = null;
        if ($data[2] != null) {
            // house
            if ($article->property == 4 || $article->property == 5) {
                if (!empty($data[35])) {
                    if ($data[35] == 1) {
                        $dataStatus = 4;
                    } elseif ($data[35] == 2) {
                        $dataStatus = 5;
                    } elseif ($data[35] == 3) {
                        $dataStatus = 6;
                    } elseif ($data[35] == 4) {
                        $dataStatus = 7;
                    } else {
                        $dataStatus = $data[35];
                    }
                }
            }

            //mansion
            if ($article->property == 6 || $article->property == 7) {
                if (!empty($data[35])) {
                    if ($data[35] == 1) {
                        $dataStatus = 10;
                    } elseif ($data[35] == 2) {
                        $dataStatus = 11;
                    } elseif ($data[35] == 3) {
                        $dataStatus = 12;
                    } elseif ($data[35] == 4) {
                        $dataStatus = 13;
                    } else {
                        $dataStatus = $data[35];
                    }
                }
            }

            // land
            if ($article->property == 1 || $article->property == 2 || $article->property == 3) {
                if (!empty($data[35])) {
                    if ($data[35] == 1) {
                        $dataStatus = 1;
                    } elseif ($data[35] == 2) {
                        $dataStatus = 2;
                    } else {
                        $dataStatus = $data[35];
                    }
                }
            }
        }

        $article->current_status = $dataStatus;
//        $article -> current_status = empty($data[35])? null: $data[35];


        preg_match("@([0-9]{4})([0-9]{1,2})@", $data[36], $age);
        $article->current_status_year = empty($age[1]) ? null : $age[1];
        $article->current_status_month = empty($age[2]) ? null : $age[2];

        $floor_plan = null;
        if ($data[132] == 1) {
            $floor_plan = 3;
        } elseif ($data[132] == 2) {
            $floor_plan = 4;
        } elseif ($data[132] == 3) {
            $floor_plan = 1;
        } elseif ($data[132] == 4) {
            $floor_plan = 7;
        } elseif ($data[132] == 5) {
            $floor_plan = 2;
        } elseif ($data[132] == 6) {
            $floor_plan = 5;
        } elseif ($data[132] == 7) {
            $floor_plan = 6;
        } elseif ($data[132] == 8) {
            $floor_plan = 8;
        } elseif ($data[132] == 9) {
            $floor_plan = 9;
        }
        $article->floor_plan = empty($data[133]) ? null : $data[133];
        $article->floor_plan_type = $floor_plan;

        $article->sales_company = $data[108];
        $article->construction_company = $data[107];
        $article->management_company = $data[99];
        $article->management_form = empty($data[98]) ? null : $data[98];

        $article->land_not = empty($data[196]) ? null : $data[196];
        $article->save();

        // 業者登録
        $vendor_data = [];
        $vendor_data['name'] = $data[4];
        $vendor_data['company_id'] = $user->company_id;
        $vendor_data['vendor_charge'] = $data[6];
        $vendor_data['vendor_tel1'] = $data[5];
        $vendor_data['vendor_tel2'] = $data[7];
        $vendor_data['vendor_mail'] = $data[8];
        $vendor_data['manner'] = $data[42];

        // 重複する業者がなければ登録
        $vendor = Vendor::where(['name' => $data[4]])->where(['company_id' => $user->company_id])->first();
        if (is_null($vendor)) {
            $vendor = new Vendor;
            $vendor->fill($vendor_data)->save();
        }


        $relation = new RelationDuplicateVendorArticle;
        $relation->article_id = $article->id;
        $relation->vendor_id = $vendor->id;
        $relation->charge = $data[6];
        $relation->company_id = $user->company_id;
        //$relation -> manner = $data[42];
        $relation->save();


        return $article->id;
    }

    public function getZipCode($address)
    {
        $res = "";
        $baseurl = "https://zipcoda.net/api/";

        $ch = curl_init(); //1.初期化
        curl_setopt($ch, CURLOPT_URL, $baseurl . '?address=' . $address); //2.URLをセット
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); //3.HTTP リクエストをセット（GET,POST等)
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //文字列で返す
        //curl_setopt($ch, CURLOPT_HEADER, true);   // ヘッダーも出力する

        //..4.その他必要オプション
        $result = curl_exec($ch); //5.実行して、レスポンスを取得
        // var_dump($result); // 出力
        print("-------------------------------");
        $resultarr = json_decode($result, true); //jsonを配列に
        // var_dump($resultarr); //配列で出力

        curl_close($ch); // 6.終了

        if ($resultarr['status'] == 'success') {
            if (isset($resultarr['items'][0]['zipcode'])) {
                $tmp = $resultarr['items'][0]['zipcode'];
                $res = substr($tmp, 0, 3) . '-' . substr($tmp, 3);
            }
        }

        return $res;

    }

    public function readCsv()
    {
        $targetFolder = storage_path('/app/import'); //アップロード先フォルダを指定します。
        $aryDataList = [];

        //POSTでアップロードされたファイルの保存場所、読み込み指定をします。
        if (is_uploaded_file($_FILES["file"]["tmp_name"])) {
            $tempFile = $_FILES['file']['tmp_name'];
            $targetPath = $targetFolder;
            $targetFile = rtrim($targetPath, '/') . '/' . $_FILES['file']['name'];

            // Validate the file type
            $fileTypes = array('csv', 'txt');// File extensions
            $fileParts = pathinfo($_FILES['file']['name']);
            $name_csv = explode('_', $fileParts['filename']);

            if (in_array($fileParts['extension'], $fileTypes)) {
                move_uploaded_file($tempFile, $targetFile);

                $aryDataList = [];

                $data = file_get_contents($targetFile);
                $data = preg_replace('/(\r\n|\r|\n)/s', "\r\n", $data);
                $utf8 = $data;
                if($name_csv[0] != 'v2'){
                    $utf8 = mb_convert_encoding($data, 'UTF-8', 'SJIS-win');
                }
                $targetFile_utf = rtrim($targetPath, '/') . '/rains.csv';
                file_put_contents($targetFile_utf, $utf8);
                $data = file_get_contents($targetFile_utf
                );

                // 一時ファイルの作成
                $temp = tmpfile();
                // メタデータからファイルパスを取得して読み込み
                $meta = stream_get_meta_data($temp);

                // 一時ファイル書き込み
                fwrite($temp, $data);

                // ファイルポインタの位置を先頭に
                rewind($temp);

                $objFile = new SplFileObject($meta['uri'], 'rb');
                $objFile->setFlags(SplFileObject::READ_CSV);

                $num = 0;

                foreach ($objFile as $line) {
                    // mb_convert_variables('UTF-8', 'sjis-win', $line);
                    if ($num == 0) {
                        $num++;
                        continue;
                    }
                    $aryDataList[] = $line;
                }

                fclose($temp);

            } else {
                // csvではない
                echo 'Invalid file type.';
            }
        }

        return $aryDataList;
    }

    public function readCsvMap($targetFile_utf)
    {
        $aryDataList = [];

        //POSTでアップロードされたファイルの保存場所、読み込み指定をします。

        $data = file_get_contents($targetFile_utf);

        // 一時ファイルの作成
        $temp = tmpfile();
        // メタデータからファイルパスを取得して読み込み
        $meta = stream_get_meta_data($temp);

        // 一時ファイル書き込み
        fwrite($temp, $data);

        // ファイルポインタの位置を先頭に
        rewind($temp);

        $objFile = new SplFileObject($meta['uri'], 'rb');
        $objFile->setFlags(SplFileObject::READ_CSV);

        $num = 0;

        foreach ($objFile as $line) {
            if ($num == 0) {
                $num++;
                continue;
            }
            $aryDataList[] = $line;
        }

        fclose($temp);

        return $aryDataList;
    }

    public function getCsvMap(Request $request)
    {
        $targetFolder = storage_path('/app/import'); //アップロード先フォルダを指定します。
        $targetPath = $targetFolder;
        if ($request->address1 == '京都府') {
            $targetFile_utf = rtrim($targetPath, '/') . '/25SHIGA.CSV';
        }
        if ($request->address1 == '京都府') {
            $targetFile_utf = rtrim($targetPath, '/') . '/26KYOUTO.CSV';
        }
        try {
            $res = "";

            // CSVファイルのアップロードと読み込み
            $aryDataList = $this->readCsvMap($targetFile_utf);

            foreach ($aryDataList as $row) {
                if (mb_detect_encoding(implode($row)) != 'UTF-8') {
                    mb_convert_variables("UTF-8", "SJIS", $row);
                }

                // 物件情報の登録
                try {
                    if ($request->address1 == $row[6] && $request->address2 == $row[7] && $request->address3 == $row[8]) {
                        $res1 = substr($row[2], 0, 3);
                        $res2 = substr($row[2], 3);
                        $res = $res1 . '-' . $res2;
                        break;
                    }

                } catch (\Exception $exception) {
                } catch (\Error $error) {
                }
            }

            return $res;
        } catch (Exception $e) {
            echo "例外キャッチ：", $e->getMessage(), "\n";
        }
    }

    function checkDuplicate($data)
    {
        $res = 0;
        $address_info = MstTown::getDataByAddress($data[16]);
        if (isset($address_info[0]['city_code'])) {
            $city = intval($address_info[0]['city_code']);
        }

        // 市・土地面積
        $q = Article::query();
        $q->where('address2', '=', $city);
        $q->where('land_area_val', '=', $data[52]);
        $res1 = $q->get()->count();
        if ($res1 != 0) {
            $res += $res1;
        }

        // 市・建物面積
        $q = Article::query();
        $q->where('address2', '=', $city);
        $q->where('total_area_val', '=', $data[56]);
        $res2 = $q->get()->count();
        if ($res2 != 0) {
            $res += $res2;
        }

        // 市・丁目・物件種別
        $q = Article::query();
        $q->where('address2', '=', $city);
        $q->where('address4', '=', $data[17]);
        $property = "";
        if ($data[2] == "1") {
            $property = 1;
        } else if ($data[2] == "2") {
            $property = 4;
        } else if ($data[2] == "3") {
            $property = 6;
        }
        $q->where('property', '=', intval($property));
        $res3 = $q->get()->count();
        if ($res3 != 0) {
            $res += $res3;
        }

        // マンション名
        $res4 = 0;
        if (!empty($data[18])) {
            $q = Article::query();
            $q->where('name_apartment', '=', $data[18]);
            $res4 = $q->get()->count();
            if ($res4 != 0) {
                $res += $res4;
            }
        }

        return $res;
    }

    public function changeAccess1(Request $request)
    {
        $response = [];
        if (isset($request->line)) {
            // 路線・駅名を取得
            $response = MstStation::getDataStationByLine($request->line);
        }
        return response()->json($response);
    }

    public function searchFacility(Request $request)
    {
        $res = 0;
        $all = $request->all();
        $res = Facility::getDataByCondition($all);

        return response()->json($res);
    }

    public function searchFacilityShop(Request $request)
    {
        $user = Auth::user();
        $res = [];
        $property = $request->property;
        if ($property == "") {
        } else {
            $facility = Facility::where('kind', '=', $property)->where('company_id', '=', $user->company_id)->get();
            foreach ($facility as &$row) {
                $row->disp_file_path = str_replace('public', '/storage', $row->file_path);
                $tmp = [
                    'id' => $row->id,
                    'name' => $row->name
                ];
                $res[] = $tmp;
            }
        }


        return response()->json($res);
    }

    public function searchFacilityProperty(Request $request)
    {
        $user = Auth::user();
        $res = [];

        $all = $request->all();
        if (isset($all['area'])) {
            $res = Facility::getFacilityProperty($user->company_id, $all['area']);
        }


        return response()->json($res);
    }

    public function saveVendorInfo(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();

        $all = $request->all();

        $vendor_id = $all['vendor_id'];
        $article_id = $all['article_id'];

        // 物件ー業者情報の更新
        $article_vendor_data = [];
        $article_vendor_data['ad_conf_day'] = $all['ad_conf_day'];
        $article_vendor_data['flyer'] = $all['flyer'];
        $article_vendor_data['freepaper'] = $all['freepaper'];
        $article_vendor_data['house_hp'] = $all['house_hp'];
        $article_vendor_data['portal'] = $all['portal'];
        $article_vendor_data['signboard'] = $all['signboard'];
        $article_vendor_data['ad_conf'] = $all['ad_conf'];
        $article_vendor_data['article_conf_day'] = $all['article_conf_day'];
        $article_vendor_data['charge'] = $all['charge'];
        $article_vendor_data['manner'] = $all['manner'];
        $article_vendor_data['home_note'] = $all['home_note'];
        RelationVendorArticle::where('company_id', '=', $user->company_id)->
        where('article_id', '=', $article_id)->where('vendor_id', '=', $vendor_id)->update($article_vendor_data);

        // 物件データの更新
        $article_data = [];
        $article_data['price_closing'] = $all['price_closing'];
        $article_data['close_date'] = $all['close_date'];
        $article_data['status'] = $all['status'];
        $article_data['conf_day'] = $all['article_conf_day'];

        Article::where('company_id', '=', $user->company_id)->
        where('building_id', '=', $article_id)->update($article_data);

        $history_id = null;
        // 物件価格履歴の更新
        if (isset($all['change_flag']) && $all['change_flag'] == 1 && $all['change_price'] != '') {
            $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article_id)->first();
            if ($article->price != $all['change_price']) {
                $history_data = [];
                $history_data['company_id'] = $user->company_id;
                $history_data['article_id'] = $article_id;
                if($all['change_price_date'] == null) {
                    $history_data['regist_date'] = Carbon::now()->format('Y/m/d');
                } else {
                    $history_data['regist_date'] = $all['change_price_date'];
                }
                $history_data['price'] = $all['change_price'];
                $history = new RelationPriceHistory;
                $history->fill($history_data)->save();
                $history_id = $history->id;
                $article_data = [];
                $article_data['price'] = $all['change_price'];
                Article::where('company_id', '=', $user->company_id)->
                where('building_id', '=', $article_id)->update($article_data);
            }
        }

        if ($user->isOwnerOfSaiKyoto()) {
            $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article_id)->first();
            ArticleController::setPriceCustomContent($article);
            if ($article->mansion_id != null) {
                $mansion = $article->getMansion();
                    $mansion->close_date = $article->close_date;
                // $this->insertArticleIntoSai($article, false, $mansion);
            } else {
                // $this->insertArticleIntoSai($article, false);
            }
        }

        $all['company_id'] = $user->company_id;

        if($history_id != null){
            $all['history_data'] = RelationPriceHistory::where('article_id', $article_id)->orderBy('id', 'DESC')->first();
        }

        $apiService->saveVendorInfo($all);

        return response()->json($all);
    }

    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();
            $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 = MstCity::selectRaw("name as code, name")->where("company_id", auth()->user()->company_id)->get()->toArray();
            $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');
            $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();
            $data['school_town'] = $sres;
        } else {
            $data['pref'] = MstPrefecture::getData();
            $data['city'] = MstCity::getData($article_data['address1'], null, auth()->user()->company_id);
            $data['town'] = MstTown::getData($article_data['address1'], $article_data['address2']);

            $sres = MstCity::selectRaw("name as code, name")->where("company_id", auth()->user()->company_id)->get()->toArray();
            $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' => 0, 'name' => '未設定'],
            ['code' => 1, 'name' => '不可'],
            ['code' => 2, '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)) {
            $checked_law = RelationLawrestriction::getDataByArticleId($article_data->building_id);
        }

        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['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 insertArticleIntoSai($article, $new = true, $mansion = null)
    {
        $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);

            unset($article->original_add);
            if ($new) {
                $articleForSaiKyoto = new ContructForSaiKyoto();
                $dataForSaiKyoto["c_id"] = $this->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;
        }
        unset($article->original_add);
        $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 ($article->conf_day != null) {
            $updateTime = $this->convertDateTime($article->conf_day);
        } else {
            $updateTime = $this->convertDateTime($article->updated_at);
        }


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

            $articleForSaiKyoto->update(["OB" => $createTime, "OA" => $updateTime]);
            return;
        }
        unset($article->original_add);
        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}";
    }


    public function saveVendorBusiness(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();

        $all = $request->all();

        $vendor_id_list = isset($all['id']) ? $all['id'] : "";
        $article_id = $all['article_id'];

        $num = 0;
        if (!empty($vendor_id_list)) {
            foreach ($vendor_id_list as $vendor_id) {
                // 物件ー業者情報の更新
                $article_vendor_data = [];
                $article_vendor_data['ad_conf_day'] = $all['ad_conf_day'][$num];
                $article_vendor_data['flyer'] = $all['flyer'][$num];
                $article_vendor_data['freepaper'] = $all['freepaper'][$num];
                $article_vendor_data['house_hp'] = $all['house_hp'][$num];
                $article_vendor_data['portal'] = $all['portal'][$num];
                $article_vendor_data['signboard'] = $all['signboard'][$num];
                $article_vendor_data['ad_conf'] = $all['ad_conf'][$num];
                //$article_vendor_data['article_conf_day'] = $all['article_conf_day'][$num];
                $article_vendor_data['charge'] = $all['charge'][$num];
                $article_vendor_data['manner'] = $all['manner'][$num];
                $article_vendor_data['home_note'] = $all['home_note'][$num] ?? null;
                RelationVendorArticle::where('company_id', '=', $user->company_id)->
                where('article_id', '=', $article_id)->where('vendor_id', '=', $vendor_id)->update($article_vendor_data);

                $vendor = [];
                $vendor['vendor_tel1'] = $all['vender_tel'][$num];
                $vendor['vendor_fax'] = $all['vender_fax'][$num];

                Vendor::where('id', '=', $vendor_id)->update($vendor);
                $num++;
            }
        }

        if (isset($all['conf_day'])) {
            $all['conf_day'] = Carbon::parse($all['conf_day'])->format('Y-m-d');
        }
        // 物件データの更新
        $article_data = [];
        $article_data['price_closing'] = $all['price_closing'];
        $article_data['close_date'] = $all['close_date'];
        $article_data['status'] = $all['status'];
        $article_data['bk'] = $all['bk'];
        $article_data['key_text'] = $all['key_text'];
        if (isset($all['memo1'])) {
            $article_data['memo1'] = $all['memo1'];
        } else {
            $article_data['memo1'] = $all['memo'] ?? "";
        }
        if (isset($all['article_conf_day'])) {
            $article_data['conf_day'] = $all['article_conf_day'][0];
        } else {
            $article_data['conf_day'] = $all['conf_day'] ?? null;
        }
        if (!isset($all['change_flag'])){
            unset($article_data['price']);
        }

        $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article_id)->first();
        $article_data['updated_at'] = Carbon::now()->format('Y-m-d H:i:s');
        if (isset($all['own_company'])) {
            $article_data['own_company'] = $all['own_company'];
        }
        $article->update($article_data);
        $history_id = null;
        // 物件価格履歴の更新
        if (isset($all['change_flag']) && $all['change_flag'] == 1 && $all['change_price'] != '') {
            $article = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article_id)->first();
            if ($article->price != $all['change_price']) {
                $history_data = [];
                $history_data['company_id'] = $user->company_id;
                $history_data['article_id'] = $article_id;
                $history_data['price'] = $all['change_price'];
                if($all['change_price_date'] == null) {
                    $history_data['regist_date'] = Carbon::now()->format('Y/m/d');
                } else {
                    $history_data['regist_date'] = $all['change_price_date'];
                }
                $history = new RelationPriceHistory;
                $history->fill($history_data)->save();
                $history_id = $history->id;
                $article_data = [];
                $article_data['price'] = $all['change_price'];
                $check = RelationPriceHistory::where('article_id', $article_id)->orderBy('regist_date', 'DESC')->first();
                $regist_date = str_replace('/', '-', $history_data['regist_date']);
                if($regist_date >= $check->regist_date) {
                    Article::where('company_id', '=', $user->company_id)->where('building_id', '=',
                        $article_id)->update($article_data);
                }
            }
        }

        if ($user->isOwnerOfSaiKyoto()) {
            $original = $article->customs()->get();

            $article->original_add = $original[0]->contents;
            if (isset($all['change_price']) && $all['change_price'] != '' && isset($all['change_flag'])) {
                $check = RelationPriceHistory::where('article_id', $article_id)->orderBy('regist_date', 'DESC')->first();
                $regist_date = str_replace('/', '-', $history_data['regist_date']);
                if($regist_date >= $check->regist_date) {
                    $article->price = $all['change_price'];
                }
                ArticleController::setPriceCustomContent($article);
            }
            if ($article->mansion_id != null) {
                $mansion = $article->getMansion();
                $mansion->original_add = $original[0]->contents;
                $mansion->close_date = $article->close_date;
                // $this->insertArticleIntoSai($article, false, $mansion);
            } else {
                // $this->insertArticleIntoSai($article, false);
            }
        }

        $all['history_id'] = $history_id;
        $data = Article::where('company_id', '=', $user->company_id)->where('building_id', '=', $article_id)->first();
        if($history_id != null){
            $data['history_data'] = RelationPriceHistory::where('article_id', $article_id)->orderBy('id', 'DESC')->first();
        }
        if (!empty($vendor_id_list)) {
            $data['vendor_list'] = RelationVendorArticle::where('company_id', '=', $user->company_id)->where('article_id', '=', $article_id)->get();
            $data['vendors'] = Vendor::whereIn('id', $vendor_id_list)->get();
        }

        $apiService->saveVendorBusiness($data);

        return response()->json($all);
        //return $history_id;
    }

    public function changeDispUser(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $response = [];
        $data = ['disp' => $request->check];
        UserInfo::where('company_id', '=', $user->company_id)->where('employee_number', '=', $request->id)->update($data);
        $apiService->changeStatusStaff($request->id, $data);
        return response()->json($response);
    }

    public function changeDispReform(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $response = [];
        $data = ['disp' => $request->check];
        Reform::where('code', '=', $request->id)->where('company_id', $user->company_id)->update($data);
        $apiService->changeStatusReform($request->id, $data);
        return response()->json($response);
    }

    public function changeDispNews(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $response = [];
        $data = ['disp' => $request->check];
        News::where('news_id', '=', $request->id)->update($data);
        $apiService->changeStatusNews($request->id, $data);
        return response()->json($response);
    }
    public function changeDisplayLease(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $response = [];
        $data = ['display' => $request->check];
        Lease::where('id', '=', $request->id)->update($data);
        $apiService->changeStatusLease($request->id, $data);
        return response()->json($response);
    }


    public function changeDispStore(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $response = [];
        $data = ['disp' => $request->check];
        MstStore::where('id', '=', $request->id)->update($data);
        $apiService->changeStatusStore($request->id, $data);
        return response()->json($response);
    }

    public function changeDispFacility(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user();
        $response = [];
        $data = ['kokai' => $request->check];
        Facility::where('id', '=', $request->id)->update($data);
        $apiService->changeStatusFacility($request->id, $data);
        return response()->json($response);
    }

    public function searchFacilityData(Request $request)
    {
        $res = 0;
        $all = $request->all();

        if ($request->id == "") {
            $res = [
                'img' => '../../img/noimage2.jpg',
                'id' => '',
                'distance' => 0,
                'time' => 0
            ];
        } else {
            $result = Facility::getDataByCondition($all);
            $result->disp_file_path = str_replace('public', '/storage', $result->file_path);
            $distance = 0;
            if (isset($all['lat']) && isset($all['lng']) && isset($result->lat) && isset($result->lng)) {
                $distance = $this->calDistance($all['lat'], $all['lng'], $result->lat, $result->lng);
                $distance = $distance + (5 - $distance % 5) % 5;
            }

            $time = ceil($distance / 80);
            $res = [
                'img' => $result->disp_file_path,
                'id' => $result->id,
                'distance' => $distance,
                'time' => $time
            ];
        }

        return response()->json($res);
    }

    function calDistance($start_lat, $start_lng, $end_lat, $end_lng)
    {
        if ($start_lat == null || $start_lng == null || $end_lat == null || $end_lng == null) {
            return 0;
        }
        //緯度、経度の移動量を計算
        $lat_dist = ($start_lat - $end_lat);
        if ($lat_dist < 0) $lat_dist = $lat_dist * -1;
        $lng_dist = ($start_lng - $end_lng);
        if ($lng_dist < 0) $lng_dist = $lng_dist * -1;


        //緯度位置における経度量を計算　地球は丸い
        $m_lng = 30.9221438 * cos($start_lat / 180 * pi());
        if ($m_lng < 0) $m_lng = $m_lng * -1;

        //移動量を計算
        $distance = (int)(sqrt(pow(abs($lat_dist / 0.00027778 * 30.9221438), 2) + pow(abs($lng_dist / 0.00027778 * $m_lng), 2)));

        return $distance;
    }

    function convertImageSource($imgData)
    {
        $base64 = base64_encode($imgData);
        $mime = 'image/jpg';
        return 'data:' . $mime . ';base64,' . $base64;
    }

    function get_gps_from_address(Request $request)
    {
        $res = array();
        if ($request->address != "") {
            $req = 'http://www.geocoding.jp/api/?q=';
            $req .= urlencode($request->address);
            $xml = simplexml_load_file($req) or die('XML parsing error');
            $location = $xml->coordinate;
            $res['lat'] = (string)$location->lat;
            $res['lng'] = (string)$location->lng;
        }

        return response()->json($res);
    }

    function getParking(Request $request)
    {
        $res = [];

        if ($request->get("property") == 41 || $request->get("property") == 42 || $request->get("property") == 5) {
            $parking = MstParking::whereNull('type')->orWhere('type', '=', 2)->where("code", "!=", 13)->get();
        } elseif ($request->get("property") == 1) {

            $parking = MstParking::where("code", "=", 8)->get();
        } elseif ($request->get("property") == 61 || $request->get("property") == 7) {
            $parking = MstParking::whereNull('type')->orWhere('type', '=', 1)->where("code", "!=", 13)->get();
        } elseif (empty($request->get("property"))) {
            $parking = MstParking::where("code", "!=", 13)->get();
        } else {
            $parking = MstParking::where("code", "!=", 13)->get();
        }


        $res = MstParking::getParking($parking);
        return $res;
    }

    function saveVendor(Request $request)
    {

        if (empty($request->id)) {
            $vendor = new Vendor;
            $vendor->name = $request->name;
            $vendor->manner = $request->manner;
            $vendor->vendor_tel1 = $request->vendor_tel1;
            $vendor->vendor_fax = $request->vendor_fax;
            $vendor->vendor_charge = $request->vendor_charge;
            $vendor->flyer = $request->flyer;
            $vendor->freepaper = $request->freepaper;
            $vendor->house_hp = $request->house_hp;
            $vendor->portal = $request->portal;
            $vendor->signboard = $request->signboard;
            $vendor->ad_conf_day = $request->ad_conf_day;
            $vendor->save();
        } else {
            $vendor = Vendor::where('id', $request->id)->first();
            $vendor->name = $request->name;
            $vendor->manner = $request->manner;
            $vendor->vendor_tel1 = $request->vendor_tel1;
            $vendor->vendor_fax = $request->vendor_fax;
            $vendor->vendor_charge = $request->vendor_charge;
            $vendor->flyer = $request->flyer;
            $vendor->freepaper = $request->freepaper;
            $vendor->house_hp = $request->house_hp;
            $vendor->portal = $request->portal;
            $vendor->signboard = $request->signboard;
            $vendor->ad_conf_day = $request->ad_conf_day;
            $vendor->save();
        }


        echo $vendor->id;


    }

    function convertEOL($string, $to = "\r\n")
    {
        return preg_replace("/\r\n|\r|\n/", $to, $string);
    }

    public function searchVendor(Request $request)
    {
        $user = Auth::user($request);
        $response = array();
        $vendor = Vendor::query();
        $vendor->where('company_id', $user->company_id);
        if (isset($request->name)) {
            $vendor->where('name', 'LIKE', '%' . $request->name . '%');
        }
        if (isset($request->shop)) {
            $vendor->where('store', '=', $request->shop);
        }
        if (isset($request->tel)) {
            $vendor->where('vendor_tel1', '=', $request->tel);
        }
        if (isset($request->fax)) {
            $vendor->where('vendor_fax', '=', $request->fax);
        }
        if (isset($request->id)) {
            $vendor->where('id', '=', $request->id);
        }
        if (isset($request->dup)) {
            $id_list = explode(',', $request->dup);
            $vendor->whereNotIn('id', $id_list);
        }

        $response = $vendor->get();

        return response()->json($response);
    }

    public function saveChangeVendor(Request $request)
    {
        $response = $request->change;
        // dump($request->vendor);

        return response()->json($response);
    }

    public function delProvisional(Request $request)
    {
        $user = Auth::user($request);
        $response = [];
        $id = $request->del;
        $save = ['del' => 1];
        Article::where('building_id', '=', $id)->where('company_id', '=', $user->company_id)->update($save);

        return response()->json($response);
    }

    public function searchLot(Request $request)
    {
        $user = Auth::user($request);
        $response = array();

        $article = Article::query();
        $article->where('property', '=', 99);
        $article->where('company_id', '=', $user->company_id);
        $article->whereNotNull('address2');
        if (isset($request->name)) {
            $article->where('search_lot_name', 'LIKE', '%' . $request->name . '%');
        }
        if (isset($request->num)) {
            $article->where('building_id', '=', $request->num);
        }
        if (isset($request->address1)) {
            $article->where('address1', '=', $request->address1);
        }
        if (isset($request->address2)) {
            $article->where('address2', '=', $request->address2);
        }
        if (isset($request->address3)) {
            $article->where('address3', '=', $request->address3);
        }

        $response = $article->get();

        return response()->json($response);
    }

    public function searchRoom(Request $request)
    {
        $user = Auth::user($request);
        $response = array();

        $article = Article::query();
        $article->select(["building_id", "name"])->where('company_id', '=', $user->company_id);
        $article->room();

        if (isset($request->name)) {
            $article->where('name', 'LIKE', '%' . $request->name . '%');
        }
        if (isset($request->num)) {
            $article->where('building_id', '=', $request->num);
        }
        if (isset($request->address1)) {
            $article->where('address1', '=', $request->address1);
        }
        if (isset($request->address2)) {
            $article->where('address2', '=', $request->address2);
        }
        if (isset($request->address3)) {
            $article->where('address3', '=', $request->address3);
        }
        $response = $article->get();

        return response()->json($response);
    }

    public function searchLotBuild(Request $request)
    {
        $user = Auth::user($request);
        $response = array();

        $article = Article::query();
        $article->where('property', '=', 99);
        $article->where('company_id', '=', $user->company_id);

        if (isset($request->address1)) {
            $article->where('address1', '=', $request->address1);
        }
        if (isset($request->address2)) {
            $article->where('address2', '=', $request->address2);
        }
        if (isset($request->address3)) {
            $article->where('address3', '=', $request->address3);
        }
        if (isset($request->address4)) {
            $article->where('address3', '=', $request->address3);
        }

        $response = $article->get();

        return response()->json($response);
    }

    public function saveTmpImageStore(Request $request)
    {
        $response = [];
        if (isset($request->tmp_image)) {

            $num = $request->num;
            $extension = $request->tmp_image->getClientOriginalExtension();
            $photo_data = [
                'file_type' => $extension,
            ];
            $photo = TempImageStore::create($photo_data);

            $image_url = $request->tmp_image->storeAs('public/tmp', 'photo_image_xxx_' . $photo->id . '.' . $extension);
            $photo_data = [
                'file_path' => $image_url,
            ];
            TempImageStore::where('id', '=', $photo->id)->update($photo_data);

            $response = $photo->id;
        }

        return response()->json($response);
    }

    public function saveTmpImageReform(Request $request)
    {
        $response = [];
        if (isset($request->tmp_image)) {

            $num = $request->num;
            $extension = $request->tmp_image->getClientOriginalExtension();
            $photo_data = [
                'file_type' => $extension,
            ];
            $photo = TempImageReform::create($photo_data);

            $image_url = $request->tmp_image->storeAs('public/tmp', 'photo_image_xxx_' . $photo->id . '.' . $extension);
            $photo_data = [
                'file_path' => $image_url,
            ];
            TempImageReform::where('id', '=', $photo->id)->update($photo_data);

            $response = $photo->id;
        }

        return response()->json($response);
    }
    public function delTmpImage(Request $request)
    {
        $response = [];
        $tmp = TempImage::where('id', $request->id)->first();
        Storage::delete($tmp->file_path);

        TempImage::where('id', $request->id)->delete();
        return response()->json($response);
    }

    public function delReformTmpImage(Request $request)
    {
        $response = [];
        $tmp = TempImageReform::where('id', $request->id)->first();
        Storage::delete($tmp->file_path);

        TempImageReform::where('id', $request->id)->delete();
        return response()->json($response);
    }

    public function delStoreTmpImage(Request $request)
    {
        $response = [];
        $tmp = TempImageStore::where('id', $request->id)->first();
        Storage::delete($tmp->file_path);

        TempImageStore::where('id', $request->id)->delete();
        return response()->json($response);
    }

    public function delReformImage(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user($request);
        $response = [];
        $tmp = RelationReformPhoto::where('id', $request->id)->first();
        Storage::delete($tmp->file_path);

        RelationReformPhoto::where('id', $request->id)->delete();
        $apiService->delReformImage($request->id);
        return response()->json($response);
    }

    public function delStoreImage(Request $request, CompanyApiService $apiService)
    {
        $user = Auth::user($request);
        $response = [];
        $tmp = RelationStorePhoto::where('id', $request->id)->first();
        Storage::delete($tmp->file_path);

        RelationStorePhoto::where('id', $request->id)->delete();
        $apiService->delStoreImage($request->id);
        return response()->json($response);
    }

    public function getSearchCount(Request $request)
    {
        $recommend = $request->get("recommend");
        $article_list = [];
        $article_list = collect($article_list);
        if (empty($recommend)) {
            if (is_array($request->address1)) {
                for ($i = 0; $i < count($request->address1); $i++) {
                    $newRequest = new \stdClass();
                    foreach ($request->all() as $key => $value) {
                        if ($key == 'land_condition') {
                            if (is_array($value)) {
                                $newRequest->{$key} = [$value[$i * 2] ?? null, $value[$i * 2 + 1] ?? null];
                            }
                        } else {
                            if (is_array($value)) {
                                $newRequest->{$key} = [$value[$i] ?? null];
                            }
                        }
                    }
                    $art_list = Article::getSearchDataByCondition($newRequest, null, null, 2);
                    $article_list = $article_list->merge($art_list)->unique();
                }
            }
        } else {
            $article_list = Article::getSearchDataByCondition($request, null, 2, 2);
        }
        $count = count($article_list);

        return $count;
    }

    public function getSearchCountClose(Request $request)
    {
        $article_list = [];
        $article_list = collect($article_list);
        if (is_array($request->address1)) {
            for ($i = 0; $i < count($request->address1); $i++) {
                $newRequest = new \stdClass();
                foreach ($request->all() as $key => $value) {
                    if ($key == 'land_condition') {
                        if (is_array($value)) {
                            $newRequest->{$key} = [$value[$i * 2] ?? null, $value[$i * 2 + 1] ?? null];
                        }
                    } else {
                        if (is_array($value)) {
                            $newRequest->{$key} = [$value[$i] ?? null];
                        }
                    }
                }
                $art_list = Article::getSearchDataByCondition($newRequest, null, null, 1);
                $article_list = $article_list->merge($art_list)->unique();
            }
        }
        $count = count($article_list);
        return $count;
    }

    public function getSearchCountMansion(Request $request)
    {

        $article_list = [];
        $article_list = collect($article_list);
        if (is_array($request->address1)) {
            for ($i = 0; $i < count($request->address1); $i++) {
                $newRequest = new \stdClass();
                foreach ($request->all() as $key => $value) {
                    if ($key == 'shared') {
                        if (is_array($value)) {
                            $newRequest->{$key} = [$value[$i * 8] ?? null, $value[$i * 8 + 1] ?? null, $value[$i * 8 + 2] ?? null, $value[$i * 8 + 3] ?? null, $value[$i * 8 + 4] ?? null,
                                $value[$i * 8 + 5] ?? null, $value[$i * 8 + 6] ?? null, $value[$i * 8 + 7] ?? null];
                        }
                    } else {
                        if (is_array($value)) {
                            $newRequest->{$key} = [$value[$i] ?? null];
                        }
                    }
                }
                $art_list = Article::getMansionDataByCondition($newRequest, null, null, null);
                $article_list = $article_list->merge($art_list)->unique();
            }
        }
        $count = count($article_list);
        return $count;
    }

    public function getSearchCountLot(Request $request)
    {
        $article_list = [];
        $article_list = collect($article_list);
        if (is_array($request->address1)) {
            for ($i = 0; $i < count($request->address1); $i++) {
                $newRequest = new \stdClass();
                foreach ($request->all() as $key => $value) {
                    if (is_array($value)) {
                        $newRequest->{$key} = [$value[$i] ?? null];
                    }
                }
                $art_list = Article::getSearchDataByCondition($newRequest, null, null, null, null, 1);
                $article_list = $article_list->merge($art_list)->unique();
            }
        }
        $count = count($article_list);
        return $count;
    }

    public function delArticle(Request $request, CompanyApiService $apiService)
    {
        $response = [];
        $user = Auth::user();
        $data = ['del' => 1];
        $id = $request->id;
        Article::where('building_id', '=', $id)->where('company_id', '=', $user->company_id)->update($data);
        $apiService->delArticle($id);
        return response()->json($response);
    }

    public function saveSearchVendor(Request $request)
    {
        $user = Auth::user();
        $article_id = $request->target_article;
        $vendor_id = $request->vendor_id;

        $all = $request->all();
        $article_vendor_data = [];
        $article_vendor_data['ad_conf_day'] = $all['ad_conf_day'];
        $article_vendor_data['flyer'] = $all['flyer'];
        $article_vendor_data['freepaper'] = $all['freepaper'];
        $article_vendor_data['house_hp'] = $all['house_hp'];
        $article_vendor_data['portal'] = $all['portal'];
        $article_vendor_data['signboard'] = $all['signboard'];
        $article_vendor_data['ad_conf'] = $all['ad_conf'];
        $article_vendor_data['article_conf_day'] = $all['article_conf_day'];
        $article_vendor_data['charge'] = $all['charge'];
        $article_vendor_data['manner'] = $all['manner'];
        RelationVendorArticle::where('company_id', '=', $user->company_id)->
        where('article_id', '=', $article_id)->where('vendor_id', '=', $vendor_id)->update($article_vendor_data);

        // 物件データの更新
        $article_data = [];
        $article_data['price_closing'] = $all['price_closing'];
        $article_data['close_date'] = $all['close_date'];
        $article_data['status'] = $all['status'];

        $article_data['bk'] = $all['bk'];
        $article_data['key_text'] = $all['key_text'];
        $article_data['memo1'] = $all['memo1'];

        Article::where('company_id', '=', $user->company_id)->
        where('building_id', '=', $article_id)->update($article_data);

        // 物件価格履歴の更新
        if (isset($all['change_flag']) && $all['change_flag'] == 1) {
            $history_data = [];
            $history_data['company_id'] = $user->company_id;
            $history_data['article_id'] = $article_id;
            $history_data['price'] = $all['change_price'];
            $history_data['regist_date'] = $all['change_price_date'];
            $history = new RelationPriceHistory;
            $history->fill($history_data)->save();

            $article_data = [];
            $article_data['price'] = $all['change_price'];

            Article::where('company_id', '=', $user->company_id)->
            where('building_id', '=', $article_id)->update($article_data);

        }


    }

    public function uploadArticleImage(Request $request)
    {
        $user = Auth::user();
        $photo = $request->image;
        $id = $request->article_id;
        $img_list = RelationArticlePhoto::where('article_id', '=', $id)->get();
        $max = 0;
        $uuid = Uuid::uuid4()->toString();
        foreach ($img_list as $img) {
            $tmp_path = $img->file_path;

            $tmp_path = str_replace('public/company_'.$user->company_id.'/photo/photo_image_' . $uuid . '_' . $id . '_', '', $tmp_path);
            $tmp_path = str_replace('.' . $img->file_type, '', $tmp_path);
            if ($max < $tmp_path) {
                $max = $tmp_path;
            }
        }

        $len = $max + 1;

        $extension = $photo->getClientOriginalExtension();

        $image = \Image::make($photo->getPathName());
        $org_height = $image->height();
        $org_width = $image->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_url = 'public/company_'.$user->company_id.'/photo/photo_image_' . $uuid . '_' . $id . '_' . $len . '.' . $extension;
        $image->resize($width, null, function ($constraint) {
            return $constraint->aspectRatio();
        });
        $streamedImage = $image->stream();
        Storage::put($image_url, $streamedImage->__toString());

        $photo_data = [
            'article_id' => $id,
            'file_path' => $image_url,
            'file_type' => $extension,
            'file_disp' => 0,
            'property_sub' => 1,
            'company_id' => \auth()->user()->company_id,
            'relation_article_photo_id' => (isset($request->relation_article_photo_id) && is_numeric($request->relation_article_photo_id)) ? $request->relation_article_photo_id : null ,
            // 'property' => $request->{'photo_property'.$num},
            // 'property_sub' => $request->{'photo_property_sub'.$num},
            // 'memo' => $request->{'photo_comment'.$num},
            // 'order' => $runk,
        ];
        if (isset($request->image_id) && is_numeric($request->image_id)) {
            $obj = TempImage::where('id', $request->image_id)->first();
            if (!empty($obj)){
                $obj->update($photo_data);
            }
        } else {
            $obj = TempImage::create($photo_data);
        }

        return response()->json($obj->id);
    }

    public function uploadLeaseImage(Request $request)
    {
        $user = Auth::user();
        $photo = $request->image;
        $id = $request->lease_id;
        $img_list = RelationLeasePhoto::where('lease_id', '=', $id)->get();
        $max = 0;
        $uuid = Uuid::uuid4()->toString();
        $folder = 'company_'.$user->company_id.'/lease';

        if(!Storage::disk('public')->exists($folder)){
            Storage::disk('public')->makeDirectory($folder);
        }

        foreach ($img_list as $img) {
            $tmp_path = $img->file_path;
            $tmp_path = str_replace('public/company_'.$user->company_id.'/lease/lease_image_' . $uuid . '_' . $id . '_', '', $tmp_path);
            $tmp_path = str_replace('.' . $img->file_type, '', $tmp_path);
            if ($max < $tmp_path) {
                $max = $tmp_path;
            }
        }

        $len = $max + 1;

        $extension = $photo->getClientOriginalExtension();

        $image = \Image::make($photo->getPathName());
        $org_height = $image->height();
        $org_width = $image->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_url = 'public/company_'.$user->company_id.'/lease/lease_image_' . $uuid . '_' . $id . '_' . $len . '.' . $extension;
        $image->resize($width, null, function ($constraint) {
            return $constraint->aspectRatio();
        });
        $streamedImage = $image->stream();
        Storage::put($image_url, $streamedImage->__toString());

        $photo_data = [
            'lease_id' => $id,
            'file_path' => $image_url,
            'file_type' => $extension
        ];
        if (isset($request->image_id) && is_numeric($request->image_id)) {
            $obj = TempImageLease::where('id', $request->image_id)->first();
            if (!empty($obj)){
                $obj->update($photo_data);
            }
        } else {
            $obj = TempImageLease::create($photo_data);
        }

        return response()->json($obj->id);
    }

    public function uploadPortalImage(Request $request)
    {
        $user = Auth::user();
        //ID Relation_article_photo
        $id = $request->id;
        //$img_list = RelationArticlePhoto::where('article_id', '=', $id)->get();
        $portal = $request->portal;
        if($portal == 'suumo'){
            $type = config('const.SUUMO');
        }
        if($portal == 'homes'){
            $type = config('const.HOMES');
        }
        if($portal == 'athome'){
            $type = config('const.ATHOME');
        }
        if($request->all != ''){
            RelationPortalPhoto::where('article_id', '=', $id)->where('type', '=', $type)->where('del', '=', 1)->delete();

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

            $list = RelationArticlePhoto::where('article_id', '=', $id)->where('company_id', '=', $user->company_id)->orderBy('order', 'asc')->get();
            $check_room = Article::where('company_id', '=', $user->company_id)->where('building_id', $id)->first();
            if($check_room->mansion_id != null){
                $list_mansion = RelationArticlePhoto::where('article_id', '=', $check_room->mansion_id)->where('company_id', '=', $user->company_id)->orderBy('order', 'asc')->get();
            }
            $last_order = RelationPortalPhoto::where('article_id', $id)->where('type', '=', $type)->where('company_id', '=', $user->company_id)->orderBy('order', 'desc')->first();
            $this->uploadPortalFirstImage($id, $type);
        }
        $num_order = 1;
        if(!empty($last_order)){
            $num_order = $last_order->order;
        }
        foreach ($list as $img) {
            $article_id = $img->article_id;
            $property_sub = $img->property_sub;
            $mansion = null;
            if($request->pid != ''){
                $article_id = $request->pid;
                $mansion = 1;
            }

            $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'   =>  $mansion,
                'property_sub' =>  $property_sub,
                'facility' =>  config('const.TYPE_IMAGE_PORTAL'),
                'type_upload' =>  config('const.TYPE_UPLOAD_BUKKEN'),
            ];
            $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'),
                ];

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

        if($type == config('const.HOMES')) {
            $this->uploadPortalFacility($request);
        }
    }

    public function uploadPortalFacility(Request $request)
    {
        $user = Auth::user();

        $id = $request->id;

        if(isset($request->room_id)){
            $room_id = $request->room_id;
        }
        $portal = $request->portal;
        if($portal == 'suumo'){
            $type = config('const.SUUMO');
        }
        if($portal == 'homes'){
            $type = config('const.HOMES');
        }
        if($portal == 'athome'){
            $type = config('const.ATHOME');
        }

        if($request->all != ''){
            if($portal != 'homes'){
                RelationPortalFacility::where('article_id', '=', $id)->where('type', '=', $type)->where('del', '=', 1)->delete();
                RelationPortalFacility::where('article_id', '=', $id)->where('type', '=', $type)->where('company_id', '=', $user->company_id)->update(['del' => 1]);

                RelationPortalPhoto::where('article_id', '=', $id)->where('facility', '=', config('const.TYPE_FACILITY_PORTAL'))->where('type', '=', $type)->where('del', '=', 1)->delete();
                RelationPortalPhoto::where('article_id', '=', $id)->where('company_id', '=', $user->company_id)->where('type', '=', $type)->where('facility', '=', config('const.TYPE_FACILITY_PORTAL'))->update(['del' => 1]);
            }

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

            }
        }else{
            $list = RelationArticleFacility::where('id', '=', $id)->where('company_id', '=', $user->company_id)->get();
            if(count($list) > 0){
                $last_order = RelationPortalFacility::where('article_id', $list[0]->article_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_home = RelationPortalPhoto::where('article_id', $id)->where('type', '=', $type)->where('company_id', '=', $user->company_id)->orderBy('order', 'desc')->first();
        $num_order_home = 0;
        if(!empty($last_order_home)){
            $num_order_home = $last_order_home->order;
        }
        foreach ($list as $img) {
            $num_order++;
            $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' => isset($room_id) ? $room_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,
                'facility_area' => $img->facility_area,
                'facility_property' =>  $img->facility_property,
                'facility'  =>  $img->facility,
                'type_upload'  =>  config('const.TYPE_UPLOAD_BUKKEN')
            ];
            if($type == config('const.HOMES')){
                $num_order_home++;
                $photo_data = [
                    'article_id' => isset($room_id) ? $room_id : $img->article_id,
                    'file_type'  => $img->file_type,
                    'file_path' =>  $fac->file_path,
                    'company_id' => $img->company_id,
                    'portal_id' =>  $img->id,
                    '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'),
                    'order' => $num_order_home
                ];
                $relationPortalPhoto = RelationPortalPhoto::ofImage($img->id, $img->article_id, config('const.HOMES'), config('const.TYPE_FACILITY_PORTAL'))->first();
                if (!empty($relationPortalPhoto)){
                    $photo_data['del'] = 0;
                    $relationPortalPhoto->update($photo_data);
                }else{
                    $relationPortalPhoto = RelationPortalPhoto::create($photo_data);
                }
            }

            if($type == config('const.SUUMO')) {
                $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)) {
                    $facility_data_suumo['del'] = 0;
                    $obj_suumo->update($facility_data_suumo);
                } else {
                    $obj_suumo = RelationPortalFacility::create($facility_data_suumo);
                }
            }
            if($type == config('const.ATHOME')) {
                $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)) {
                    $facility_data_athome['del'] = 0;
                    $obj_athome->update($facility_data_athome);
                } else {
                    $obj_athome = RelationPortalFacility::create($facility_data_athome);
                }
            }
        }
        if(isset($obj_suumo) && isset($obj_athome)){
            return 1;
        }
    }

    public function uploadPortalFirstImage($id, $type) {
        $article = Article::getDataById($id);
        $verticalFile = RelationArticlePhoto::where('article_id', $article->building_id)->where('vertical', 1)->first();
        $floorFilePath = $article->floor_file_path;
        if (isset($verticalFile) && isset($verticalFile->file_path2)){
            $floorFilePath = $verticalFile->file_path2;
        }

        if ($article->floor_file_path) {
            $photo_data = [
                'article_id' => $article->building_id,
                'file_type'  => null,
                'file_path' =>  $floorFilePath,
                'file_disp' =>  null,
                'order'     =>  0,
                'memo'      =>  $article->floor_file_comment,
                'company_id' => \auth()->user()->company_id,
                'portal_id' =>  $article->building_id,
                'mansion'   =>  null,
                'property_sub' =>  $article->floor_file_type,
                'facility' =>  config('const.TYPE_FLOOR_PLAN'),
                'type_upload' =>  config('const.TYPE_UPLOAD_BUKKEN'),
            ];

            $photo_data['type'] = $type;
            $obj = RelationPortalPhoto::ofImage($article->building_id, $article->building_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);
            }
        }
    }

    public function updateReview(Request $request, CompanyApiService $apiService) {
        $user = Auth::user();

        $photo_data = [
            'facility_id'   => $request->facility_id,
            'r_name'        => $request->r_name,
            'r_title'       => $request->r_title,
            'r_date'        => $request->r_date,
            'r_comment'     => $request->r_comment
        ];

        $obj = Review::where('id', $request->id)->first();
        $obj->update($photo_data);

        if (isset($request->r_photo)) {
            $extension = $request->r_photo->getClientOriginalExtension();
            $image_url = $request->r_photo->storeAs('public/company_' . $user->company_id . '/review', 'review_image_' . $request->facility_id . '_' . $request->id . '.' . $extension);
            Review::where('id', $request->id)->update(['r_photo' => $image_url]);
        }
        if(isset($request->del_photo) && $request->del_photo == 1){
            Storage::delete($obj->r_photo);
            Review::where('id', $request->id)->update(['r_photo' => null]);
        }

        $data_review = Review::where('id', $request->id)->first();
        $data_review['del_photo'] = $request->del_photo;
        $apiService->editReview($request->id, $data_review);
    }

    public function delReview(Request $request, CompanyApiService $apiService) {

        $obj = Review::where('id', $request->id)->first();
        $facility_id = $obj->facility_id;

        if (isset($obj->r_photo) && !empty($obj->r_photo)){
            Storage::delete($obj->r_photo);
        }

        $obj->delete();

        $apiService->delReview($request->id);

        return redirect()->route("review-edit", ['id' => $facility_id]);
    }

    public function searchProperty(Request $request)
    {
        $property = $request->property;

        if ($property != null) {
            if ($property == 1) {
                $result = MstGenkyou::select('code', 'name')->where('property', 1)->get()->toArray();
            } elseif ($property == 61) {
                $result = MstGenkyou::select('code', 'name')->where('property', 3)->get()->toArray();
            } else {
                $result = MstGenkyou::select('code', 'name')->where('property', 2)->get()->toArray();
            }
            return $result;
        } else {
            return 1;
        }
    }

    public function clearSession(Request $request)
    {
        $request->session()->forget('news_data_created');
        return '0k';
    }

    public function deleteHistory(Request $request)
    {
        $user = auth::user();
        if ($request->ajax()) {
            $item = RelationPriceHistory::where([
                'id' => $request->id,
                'company_id' => $user->company_id
            ]);
            $article_id = $item->first()->article_id;
            $item->delete();
            $last = RelationPriceHistory::where('article_id', $article_id)->orderBy('regist_date', 'DESC')->first();
            if ($last->id != $request->id) {
                Article::where('building_id', $article_id)->where('company_id', $user->company_id)->update(['price' => $last->price]);
            }
            return response()->json([
                'success' => 'Record deleted successfully!'
            ]);
        }
    }

    public function changeLibrary(Request $request): JsonResponse
    {
        if (!$request->ajax()) {
            return response()->json([
                'status' => false,
            ]);
        }

        $library = $request->get('library');
        $buildingId = $request->get('building_id');
        $companyId = auth()->user()->company_id;
        $article = Article::where('building_id', $buildingId)
            ->where('company_id', $companyId)
            ->first();

        try {
            if (empty($article)) {
                throw new \Exception("Article does not exists (building_id = $buildingId, company_id = $companyId).");
            }

            $article->update([
                'library' => $library,
            ]);

            /* @var CompanyApiService $apiService */
            $apiService = app()->make(CompanyApiService::class);
            $response = $apiService->editMansion($buildingId, $article->toArray());
            if (empty($response)) {
                throw new \Exception("Call api edit mansion failed (building_id = $buildingId, company_id = $companyId).");
            }

            return response()->json([
                'status' => true,
            ]);
        } catch (\Exception $e) {
            Log::error($e);

            $article->update([
                'library' => $library == 1 ? 0 : 1,
            ]);
        }

        return response()->json([
            'status' => false,
            'message' => 'Change failed!',
        ]);
    }

    public function uploadPortalFirstImageId(Request $request) {
        if ($request->ajax()) {
            $id = $request->get('id');
            $article = Article::findOrFail($id);
            if ($article->floor_file_path) {
                $photo_data = [
                    'article_id' => $article->building_id,
                    'file_type'  => null,
                    'file_path' =>  $article->floor_file_path,
                    'file_disp' =>  null,
                    'order'     =>  0,
                    'memo'      =>  $article->floor_file_comment,
                    'company_id' => \auth()->user()->company_id,
                    'portal_id' =>  $article->building_id,
                    'mansion'   =>  null,
                    'property_sub' =>  $article->floor_file_type,
                    'facility' =>  config('const.TYPE_FLOOR_PLAN'),
                    '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($article->building_id, $article->building_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);
                    }
                }
                return $obj;
            }
        }
    }
    public function getPublicPortal(Request $request) {
        set_time_limit(0);
        $user = Auth::user();
        $shop = MstStore::getStoreCode($user->store_id);
        if ($request->ajax()) {
            $articles = Article::query();
            $articles->join('portal_status_articles', 'portal_status_articles.article_id', '=', 'articles.building_id');
            $type = $request->get('type');
            if($type == 'suumo'){
                $articles->where('portal_status_articles.portal_type', '=', 1);
                $articles->where('portal_status_articles.portal_user', '=', $shop->suumo_id);
                $this->getStatusPortalSuumo();
            }
            if($type == 'athome'){
                $articles->where('portal_status_articles.portal_type', '=', 3);
                $articles->where('portal_status_articles.portal_user', '=', $shop->athome_id);
                $this->getStatusPortalAthome();
            }
            if($type == 'homes'){
                $articles->where('portal_status_articles.portal_type', '=', 2);
                $articles->where('portal_status_articles.portal_user', '=', $shop->homes_id);
                $this->getStatusPortalHomes();
            }
            $articles->whereNotNull('portal_status_articles.article_id');


            $articles->where(function ($query) {
                $query->whereNull('del')
                    ->orWhere('del', '0');
            });
            $articles->where('status', '!=', 4);
            $articles->where('status', '!=', 5);
            $articles->groupBy('building_id');

            //Get count status portal suumo

            if($articles->count() > 0){
                if($type == 'suumo'){
                    $this->getInfoPortalSuumo($articles->get());
                }
                if($type == 'homes'){
                    $this->getInfoPortalHomes($articles->get());
                }
                if ($type == 'athome') {
                    if (!$this->checkLogged()) {
                        Log::info('start curl login athome');
                        $this->loginAthome();
                        Log::info('end login athome, start curl login athome ATTB');
                        $this->loginATTB();
                        Log::info('end curl login athome ATTB');
                    }
                    $this->getInfoPortalAthome($articles->get());
                }
            }
            return response()->json([
                'success' => 'Successfully!'
            ]);
        }
    }

    public function getStatusPortalSuumo() {
        $user = auth::user();

        $this->loginSuumo();

        $data = array(
            'TB' => 11,
            'BKTB' => 10,
            'hanKubun' => '1K'
        );

        $url = "https://manager.suumo.jp/chukai/tn02Xx0104.do";
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // POST変数をセット
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt_array($curl, $this->option); // 共通オプションの設定
        $response = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行
        file_put_contents("./suumo_response.html", $response);

        $pattern = '/<tr class="pCell4">(.*?)<\/tr>/s';
        preg_match_all($pattern, $response, $match);
        if(count($match)>1){
            $pattern1 = '/<input type="hidden" name="allCnt" value="(.*?)"/s';
            preg_match($pattern1, $response, $match1);
            $ar_match = [];
            foreach ($match[0] as $mt){
                $pattern1 = '/<td class="bdCell fgRed b tac"> (?<value1>.*?)<span class="fgBlack ml5">指示<\/span><span class="iS isRestArrow dibz ml5">残り(?<value2>.*?)枠<\/span><\/td>/';
                preg_match_all($pattern1, $mt, $matches);
                $ar_match[] = array($matches['value1'][0], $matches['value2'][0]);
            }
            RelationPortalStatusPublic::where('store_id', $user->store_id)->where('type', 1)->delete();
            $status_public = new RelationPortalStatusPublic();
            $data = array(
                'store_id' => $user->store_id,
                'net_frame_from' => $ar_match[0][0],
                'net_frame_to' => $ar_match[0][1],
                'net_report_from' => $ar_match[1][0],
                'net_report_to' => $ar_match[1][1],
                'total_portal'  => $match1[1],
                'type' => 1
            );
            $status_public->insert($data);
        }

    }

    public function getInfoPortalSuumo($articles) {
        //Log::info('local.INFO: start login Suumo');
        $this->loginSuumo();
        //Log::info('local.INFO: end login Suumo');
        $url = "https://manager.suumo.jp/chukai/tn01Xx0104.do";
        //Log::info('local.INFO: start curl suumo');
        foreach ($articles as $i => $article){
            RelationPortalPublic::where('article_id', $article->building_id)->where('type', 1)->delete();
            $data[$i] = array(
                'TB' => 11,
                'BKTB' => 10,
                'hanKubun' => '1K',
                'bukkenCd'  =>  $article->portal_id
            );
            $ch[$i] = curl_init();
            curl_setopt($ch[$i], CURLOPT_URL, $url); // 取得するURLを指定
            curl_setopt($ch[$i], CURLOPT_POST, TRUE);
            curl_setopt($ch[$i], CURLOPT_POSTFIELDS, http_build_query($data[$i])); // POST変数をセット
            curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
            curl_setopt_array($ch[$i], $this->option); // 共通オプションの設定
        }
        $mh = curl_multi_init();

        foreach ($articles as $i => $article){
            curl_multi_add_handle($mh, $ch[$i]);
        }

        $active = null;
        //execute the handles
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active && $mrc == CURLM_OK) {
            if (curl_multi_select($mh) != -1) {
                do {
                    $mrc = curl_multi_exec($mh, $active);
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }

        //close the handles
        foreach ($articles as $i => $article){
            curl_multi_remove_handle($mh, $ch[$i]);
        }
        curl_multi_close($mh);
        $responses = [];
        foreach ($articles as $i => $article){
            $responses[] =  curl_multi_getcontent($ch[$i]);
        }

        foreach ($responses as $i => $response){
            $formPattern = '/<font size = \'4\'>(.*?)<\/font>/';
            preg_match_all($formPattern, $response, $formMatches);
            if(isset($formMatches[1][0]) && $formMatches[1][0] == '閲覧権限がないため、画面を表示できません'){

            }else{
                $formPattern1 = '/<form.*?id="mainForm".*?>(.*?)<\/form>/s';
                preg_match($formPattern1, $response, $formMatches1);

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

                $pattern2 = '/<input.*?type="checkbox".*?name="(?<name>.*?)".*?value="(?<value>.*?)".*?checked="checked".*?>/';
                preg_match_all($pattern2, $formMatches1[0], $matches, PREG_SET_ORDER);
                $data_form = collect($matches)->pluck('value', 'name')->toArray();
                $status = 0;

                foreach ($data_form as $name => $value){
                    if($name == 'netKomaKeisaiShijiFlg'){
                        $status = 1;
                    }
                    if($name == 'netRptKeisaiShijiFlg'){
                        $status = 2;
                    }
                }
                if($articles[$i]['portal_id'] != null){
                    $relationportalpublic = new RelationPortalPublic();
                    $data = array(
                        'article_id' => $articles[$i]['building_id'],
                        'portal_id' => $articles[$i]['portal_id'],
                        'type' => 1,
                        'status' => $status
                    );
                    $relationportalpublic->insert($data);
                }
            }
        }
    }

    function loginSuumo() {
        $cookie_path = './suumo_cookie.txt';
        touch($cookie_path);

        $user = Auth::user();
        $shop = MstStore::getDataByCode($user->company_id, $user->store_id);
        $id = $shop->suumo_id;
        $pass = $shop->suumo_pw;

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

        // ログイン処理
        $url = "https://manager.suumo.jp/chukai/login/login";
        $POST_DATA = array(
            'j_username' => $id,
            'j_password' => $pass,
            'path' => "",
            'old_id' => '',
            'id' => $id,
            'pass' => $pass,
        );
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($POST_DATA)); // POST変数をセット
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt_array($curl, $this->option); // 共通オプションの設定
        $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行
    }

    public function getInfoPortalHomes($articles) {
        Log::info('CURL: Homes' . now()->toDateTimeLocalString());
        $url = [];
        foreach ($articles as $article){
            RelationPortalPublic::where('article_id', $article->building_id)->where('type', 2)->delete();
            $url[] = "https://manager.homes.co.jp/index.php?action=sale_reg_form&b=".$article->portal_id;
        }

        $responses = $this->requestWithDatas($url, [], false);

        foreach ($responses as $i => $response){
            $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");
            $formPattern = '/<form.*?id="form_reg".*?>(.*?)<\/form>/s';
            preg_match($formPattern, $response, $formMatches);

            if(count($formMatches) >= 2){
                $pattern = '/<input.*?name="flg_open".*?value="(?<value>.*?)".*?checked="checked".*?>/';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);
                $status = 0;
                if($matches[0][1] == 1){
                    $status = 1;
                }

                $pattern = '/<input.*?name="status".*?value="(?<value>.*?)".*?checked="checked".*?>/';
                preg_match_all($pattern, $formMatches[0], $matches, PREG_SET_ORDER);

                $del = 0;
                if($matches[0][1] == 9){
                    $del = 1;
                }
                if($del == 0){
                    $relationportalpublic = new RelationPortalPublic();
                    $data = array(
                        'article_id'    => $articles[$i]['building_id'],
                        'portal_id'     => $articles[$i]['portal_id'],
                        'type'          => 2,
                        'status'        => $status
                    );

                    $relationportalpublic->insert($data);
                }
            }
        }
    }

    public function getStatusPortalHomes() {
        $user = auth::user();
        Log::info('start Login Homes');
        $this->loginHome();
        Log::info('end Login Homes');

        $url = "https://manager.homes.co.jp/index.php?action=sale_list_view&tk=1";
        $response = $this->requestWithData($url, [], false);
        $response = mb_convert_encoding($response, "UTF-8", "EUC-JP");

        $pattern = '/<span class=\"dataTtl\">(.*?)<\/span>/s';
        preg_match_all($pattern, $response, $match);
        if(!empty($match[1])){
            $count_one = str_replace(["件", "\n"], '', $match[1][0]);
            $ar_count = explode('／', $count_one);
            RelationPortalStatusPublic::where('store_id', $user->store_id)->where('type', 2)->delete();

            $total_count = str_replace(["件", "\n"], '', $match[1][1]);

            $status_public = new RelationPortalStatusPublic();
            $data = array(
                'store_id' => $user->store_id,
                'net_frame_from' => trim($ar_count[0]),
                'net_frame_to' => trim($ar_count[1]),
                'net_report_from' => 0,
                'net_report_to' => 0,
                'total_portal'  =>  $total_count,
                'type' => 2
            );
            $status_public->insert($data);
        }
    }

    function loginHome() {
        // Homesにアクセス
        if ($this->countError >= 5) {
            $this->canRecursive = false;
            return;
        }
        $cookie_path = './homes_cookie.txt';
        touch($cookie_path);

        $user = Auth::user();
        $shop = MstStore::getDataByCode($user->company_id, $user->store_id);
        $id = $shop->homes_id;
        $pass = $shop->homes_pw;

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

        // ログイン画面へアクセス
        $url = "https://homes.force.com/pro/UserLogin";
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行
        curl_close($curl);

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

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

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

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

        // ログイン処理
        $url = $match1[3];
        $POST_DATA = [
            $match1[1] => $match1[1],
            'j_id0:j_id13:j_id23' => $id,
            'j_id0:j_id13:j_id25' => $pass,
            'j_id0:j_id13:j_id32' => 'ログイン',
            'com.salesforce.visualforce.ViewState' => $match2[1],
            'com.salesforce.visualforce.ViewStateVersion' => $match3[1],
            'com.salesforce.visualforce.ViewStateMAC' => $match4[1],
        ];
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($POST_DATA)); // POST変数をセット
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
        $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行

        $pattern = '/window\.location\.href =\'(.*?)\';/';
        preg_match($pattern, $res, $match5);
        if($match5) {
            $url = $match5[1];
        }
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
        curl_setopt_array($curl, $this->option); // 共通オプションの設定
        $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行
        curl_close($curl);

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

        // cURLセッション実行結果の解析
        $pattern = '/<p class="thumbnail"><a href="(.*?)" target="_blank"><img src="\/pro\/resource\/(.*?)\/homes_manager_/';
        preg_match($pattern, $res, $match6);

        // LIFULL HOME'S Managerにログイン情報を連携
        if (count($match6) < 2) {
            $res = mb_convert_encoding($res, "UTF-8", "EUC-JP");

            Log::error("Error insert article into Home match6");
            $this->countError++;
            return $this->loginHome();
        }
        $url = $match6[1];
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_POST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
        curl_setopt_array($curl, $this->option); // 共通オプションの設定
        $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行
        curl_close($curl);

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

        if (count($match7) < 2) {
            $res = mb_convert_encoding($res, "UTF-8", "EUC-JP");

            Log::error("Error insert article into Home match7");
            $this->countError++;
            return $this->loginHome();
        }
        $url = $match7[1];
        $curl = curl_init(); // cURLセッションの初期化
        curl_setopt($curl, CURLOPT_URL, $url); // 取得するURLを指定
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // 実行結果を文字列で返す。
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // Locationヘッダを追跡
        curl_setopt_array($curl, $this->option); // 共通オプションの設定
        $res = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行
        curl_close($curl);
    }

    function requestWithData($url, $data, $isPost = false, $headers = [], $followLocation = false)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        if ($isPost) {
            curl_setopt($curl, CURLOPT_POST, $isPost);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($curl, CURLINFO_HEADER_OUT, TRUE);
        }

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

        if($followLocation) {
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
        }

        $response = curl_exec($curl) or die('error ' . curl_error($curl));

        return $response;
    }
    function requestWithDatas($urls, $data, $isPost = false, $headers = [], $followLocation = false)
    {
        foreach ($urls as $i => $url){
            $ch[$i] = curl_init();
            curl_setopt($ch[$i], CURLOPT_URL, $url);
            curl_setopt($ch[$i], CURLOPT_HEADER, 0);
            curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, TRUE);
            if ($isPost) {
                curl_setopt($ch[$i], CURLOPT_POST, $isPost);
                curl_setopt($ch[$i], CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch[$i], CURLOPT_FOLLOWLOCATION, TRUE);
                curl_setopt($ch[$i], CURLINFO_HEADER_OUT, TRUE);
            }
            curl_setopt_array($ch[$i], $this->option);
            curl_setopt($ch[$i], CURLOPT_HTTPHEADER, $headers);
            if($followLocation) {
                curl_setopt($ch[$i], CURLOPT_FOLLOWLOCATION, TRUE);
            }
        }
        $mh = curl_multi_init();
        foreach ($urls as $i => $url){
            curl_multi_add_handle($mh, $ch[$i]);
        }

        $active = null;
        Log::info('start curl');
        //execute the handles
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active && $mrc == CURLM_OK) {
            if (curl_multi_select($mh) != -1) {
                do {
                    $mrc = curl_multi_exec($mh, $active);
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }

        //close the handles
        foreach ($urls as $i => $url){
            curl_multi_remove_handle($mh, $ch[$i]);
        }
        curl_multi_close($mh);
        $response = [];
        foreach ($urls as $i => $url){
           $response[] =  curl_multi_getcontent($ch[$i]);
        }
        Log::info('end curl');
        return $response;
    }

    public function getInfoPortalAthome($articles) {
        Log::info('CURL: Athome' .now()->toDateTimeLocalString());
        $datas = [];
        foreach ($articles as $i => $article){
            $datas[] = [
                'bukkenId' => $article->portal_id,
                'bukkenVersionNumber' => 5
            ];
        }

        $url = 'https://atbb.athome.co.jp/front-web/mainservlet/bfbk030s031';

        $responses = $this->submitAthome($url, $datas);

        foreach ($responses as $i => $response){
            $response = str_replace('onclick="checkedGlobalKokai();"', '', $response);

            $pattern = '/<input\b(?=[^>]*name="globalKokai")[^>]*\bvalue="(?<value>.*?)"[^>]*\bchecked/';

            preg_match_all($pattern, $response, $matches, PREG_SET_ORDER);

            if(!empty($matches[0])){
                $status = 0;
                if(!empty($matches[0][1])){
                    $status = $matches[0][1];
                }
                $checkPortal = RelationPortalPublic::where('article_id', $articles[$i]['building_id'])->where('portal_id', $articles[$i]['portal_id'])->where('type', 3);

                if($checkPortal->count() == 0){
                    $relationportalpublic = new RelationPortalPublic();
                    $data = array(
                        'article_id' => $articles[$i]['building_id'],
                        'portal_id' => $articles[$i]['portal_id'],
                        'type' => 3,
                        'status' => $status
                    );
                    $relationportalpublic->insert($data);
                }else{
                    $checkPortal->update(['status' => $status, 'updated_at' => date('Y-m-d H:i:s')]);
                }

            }
        }

    }

    public function getStatusPortalAthome() {
        $user = auth::user();

        RelationPortalStatusPublic::where('store_id', $user->store_id)->where('type', 3)->delete();

        if (!$this->checkLogged()) {
            Log::info('local.INFO: start login Athome');
            $this->loginAthome();
            Log::info('local.INFO: end login Athome and login ATTB');
            $this->loginATTB();
            Log::info('local.INFO: end login Athome ATTB');
        }
        //Get Total House
        $total_count = 0;

        $data_one = "itteiKensakuYoBukkenTorokuKubun=02&itteiKensakuYoBukkenTorokuKubun=06&itteiKensakuYoBukkenTorokuKubun=07&itteiKensakuYoBukkenTorokuKubun=08&itteiKensakuYoKokaiKubun=&itteiKensakuYoBukkenJotaiCode=&itteiKensakuYoMotozukeTensaiKakuninKubun=&itteiKensakuYoBukkenKubun=1&itteiKensakuYoBukkenKubun=2&itteiKensakuYoTorokuBaitai=&itteiKensakuYoIchiranKubun=01";

        $url_one = "https://atbb.athome.co.jp/front-web/mainservlet/bfbk030s003";

        $curl_one = $this->initDefaultCurl();

        curl_setopt($curl_one, CURLOPT_URL, $url_one);
        curl_setopt($curl_one, CURLOPT_POST, true);
        curl_setopt($curl_one, CURLOPT_POSTFIELDS, $data_one);

        $response_one = curl_exec($curl_one) or die('error ' . curl_error($curl_one));
        $pattern_one = '/ページ目を表示（合計：.*?<span class="bold red">(.*?)<\/span>/s';

        preg_match_all($pattern_one, $response_one, $matches);
        if(count($matches) > 1){
            $total_count = $matches[1][0];
        }

        //Get Total House nonpublic
        $nopublic_count = 0;
        $data_two = "itteiKensakuYoBukkenTorokuKubun=02&itteiKensakuYoBukkenTorokuKubun=06&itteiKensakuYoBukkenTorokuKubun=07&itteiKensakuYoBukkenTorokuKubun=08&itteiKensakuYoKokaiKubun=01&itteiKensakuYoBukkenJotaiCode=&itteiKensakuYoMotozukeTensaiKakuninKubun=&itteiKensakuYoBukkenKubun=1&itteiKensakuYoBukkenKubun=2&itteiKensakuYoTorokuBaitai=&itteiKensakuYoIchiranKubun=26";
        $url_one = "https://atbb.athome.co.jp/front-web/mainservlet/bfbk030s003";

        $curl_one = $this->initDefaultCurl();

        curl_setopt($curl_one, CURLOPT_URL, $url_one);
        curl_setopt($curl_one, CURLOPT_POST, true);
        curl_setopt($curl_one, CURLOPT_POSTFIELDS, $data_two);

        $response_one = curl_exec($curl_one) or die('error ' . curl_error($curl_one));

        $pattern_one = '/ページ目を表示（合計：.*?<span class="bold red">(.*?)<\/span>/s';

        preg_match_all($pattern_one, $response_one, $matches);

        if(count($matches) > 1){
            $nopublic_count = $matches[1][0];
        }
        /////////////////////////////////
        $data = [
            'bukkenKubunCheckFlag' => false,
            'torokuBaitaiCheckFlag' => true,
            'bukkenShumokuCheckFlag' => false,
            'bukkenShumoku' => 01,
            'bukkenShumoku' => 03,
            'bukkenShumoku' => 02,
            'bukkenShumoku' => 04,
            'bukkenKubun' => 1,
            'torokuBaitai'  =>  2,
            'jisyaKensakuFlag' => 2
        ];

        $url = "https://atbb.athome.co.jp/front-web/mainservlet/bfbk112s002";

        $curl = $this->initDefaultCurl();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));

        $response = curl_exec($curl) or die('error ' . curl_error($curl)); // cURLセッションの実行

        $pattern = '/<td width="80" align="right" class="common-data">(.*?)<\/td>/s';

        preg_match_all($pattern, $response, $matches);
        if(!empty($matches[1])){
            $status_1 = 0;
            $status_2 = 0;
            $status_3 = 0;
            unset($matches[1][0]);
            foreach ($matches[1] as $i => $item){
                preg_match("/<a.*?>(.*?)<\/a>/s", $item, $ar_item);

                if(count($ar_item)>1){
                    if($i == 0){
                        $nopublic_count = $nopublic_count - $ar_item[1];
                    }
                    if($i == 1){
                        $status_1 = $ar_item[1];
                    }
                    if($i == 2){
                        $status_2 = $ar_item[1];
                    }
                    if($i == 3){
                        $status_3 = $ar_item[1];
                    }
                }
            }

            $status_public = new RelationPortalStatusPublic();
            $data = array(
                'store_id'          => $user->store_id,
                'net_frame_from'    => $status_1,
                'net_frame_to'      => $status_2,
                'net_report_from'   => $status_3,
                'net_report_to'     => $nopublic_count,
                'total_portal'      =>  $total_count,
                'type' => 3
            );
            $status_public->insert($data);
        }
    }
    private function submitAthome($url, array $datas)
    {
        $user = auth()->user();
        $userAgent = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0';
        $cookiePath = Storage::path("import/athome/cookie-{$user->id}-{$user->company_id}-{$user->store_id}.txt");

        touch($cookiePath);
        foreach ($datas as $i => $data){
            $ch[$i] = curl_init();
            curl_setopt($ch[$i], CURLOPT_USERAGENT, $userAgent);
            curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch[$i], CURLOPT_COOKIEJAR, $cookiePath);
            curl_setopt($ch[$i], CURLOPT_COOKIEFILE, $cookiePath);
            curl_setopt($ch[$i], CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true);

            curl_setopt($ch[$i], CURLOPT_HEADER, true);
            curl_setopt($ch[$i], CURLOPT_VERBOSE, true);

            curl_setopt($ch[$i], CURLOPT_URL, $url);
            curl_setopt($ch[$i], CURLOPT_POST, true);
            curl_setopt($ch[$i], CURLOPT_POSTFIELDS, $this->httpBuildQuery($data));
            curl_setopt($ch[$i], CURLOPT_REFERER, $url);
            curl_setopt($ch[$i], CURLOPT_MAXREDIRS, 10);
            curl_setopt($ch[$i], CURLOPT_AUTOREFERER, true);
        }
        $mh = curl_multi_init();
        foreach ($datas as $i => $dt){
            curl_multi_add_handle($mh, $ch[$i]);
        }
        $active = null;
        Log::info('start curl athome');
        //execute the handles
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active && $mrc == CURLM_OK) {
            if (curl_multi_select($mh) != -1) {
                do {
                    $mrc = curl_multi_exec($mh, $active);
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }

        //close the handles
        foreach ($datas as $i => $dt){
            curl_multi_remove_handle($mh, $ch[$i]);
        }
        curl_multi_close($mh);
        $response = [];
        foreach ($datas as $i => $dt){
            $response[] =  curl_multi_getcontent($ch[$i]);
        }
        Log::info('end curl athome');

        return $response;
    }
    private function httpBuildQuery(array $queries)
    {
        $data = [];
        foreach($queries as $key => $value) {
            if(is_array($value)) {
                foreach($value as $subValue) {
                    $data[] = urlencode($key).'='.urlencode($subValue);
                }
            } else {
                if ($key == 'yotoChikiCode2') {
                    $key = 'yotoChikiCode';
                }
                $data[] = urlencode($key).'='.urlencode($value);
            }
        }
        return implode('&', $data);
    }
    public function checkLogged()
    {
        $url = 'https://atbb.athome.co.jp/front-web/mainservlet/bfcm003s201';

        $response = $this->goToPage($url);

        $position = strpos($response, 'HTTP/1.1 302 Found');

        return $position === false;
    }
    private function goToPage($url, array $data = null)
    {
        $curl = $this->initDefaultCurl();

        curl_setopt($curl, CURLOPT_URL, $url);

        if($data != null) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }

        return curl_exec($curl);
    }
    private function initDefaultCurl()
    {
        $curl = curl_init();
        $user = auth()->user();
        $userAgent = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0';
        $cookiePath = Storage::path("import/athome/cookie-{$user->id}-{$user->company_id}-{$user->store_id}.txt");

        touch($cookiePath);

        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiePath);
        curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiePath);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_VERBOSE, true);

        return $curl;
    }
    private function loginAthome()
    {
        $user = Auth::user();
        $shop = MstStore::getDataByCode($user->company_id, $user->store_id);
        $account = $shop->athome_id;
        $password = $shop->athome_pw;

        $url = 'https://members.athome.jp/login';

        $data = [
            'loginId' => $account,
            'password' => $password,
        ];

        $curl = $this->initDefaultCurl();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        return curl_exec($curl);
    }

    private function loginATTB()
    {
        $bukkenTorokuUrl = 'https://members.athome.jp/atbb/bukkenToroku?from=global_menu_bukkenTorokuKokai';
        $response = $this->goToPage($bukkenTorokuUrl, []);

        $refreshPattern = '/<meta http-equiv="Refresh" content="0;URL=(.*?)">/';
        preg_match($refreshPattern, $response, $refreshMatches);
        if(isset($refreshMatches[1])){
            $response = $this->goToPage($refreshMatches[1]);

            if(strpos($response, '強制終了させてATBBを利用する')) {
                $forceLoginUrl = 'https://atbb.athome.co.jp/front-web/login/force';

                $response = $this->goToPage($forceLoginUrl);
            }
        }

        return $response;
    }
    public function checkLoginPortal(){
        $user = Auth::user();
        $shop = MstStore::getDataByCode($user->company_id, $user->store_id);
//        if(empty($shop->suumo_id) || empty($shop->suumo_pw) || empty($shop->homes_id) || empty($shop->homes_pw) || empty($shop->athome_id) || empty($shop->athome_pw)){
        $msg = '';

        if($shop->suumo_linked == 2 && $shop->homes_linked == 2 && $shop->athome_linked == 2){
            $msg = "契約しているポータルサイトはありません。";

            return response()->json(
                [
                    'status'    =>  false,
                    'msg'       =>  $msg,
                    'suumo_linked' => $shop->suumo_linked,
                    'homes_linked' => $shop->homes_linked,
                    'athome_linked' => $shop->athome_linked
                ]
            );
        }

        if($shop->suumo_linked == 1 && (empty($shop->suumo_id) || empty($shop->suumo_pw))){
            $msg .= 'SUUMO ';
        }

        if($shop->homes_linked == 1 && (empty($shop->homes_id) || empty($shop->homes_pw))){
            $msg .= 'HOMES ';
        }

        if($shop->athome_linked == 1 && (empty($shop->athome_id) || empty($shop->athome_pw))){
            $msg .= 'at home ';
        }

        if($msg != ''){
            $msg.= "のログイン情報が不正です。<br/>店舗情報画面で「ID」「Password」を更新してください。";

            return response()->json(
                [
                    'status'    =>  false,
                    'msg'       =>  $msg,
                    'suumo_linked' => $shop->suumo_linked,
                    'homes_linked' => $shop->homes_linked,
                    'athome_linked' => $shop->athome_linked
                ]
            );
        }
        /*if(
            (empty($shop->suumo_linked) && empty($shop->homes_linked) && empty($shop->athome_linked)) ||
            ($shop->suumo_linked === 2 && $shop->homes_linked === 2 && $shop->athome_linked === 2))
        {
            $msg = '';
            if(empty($shop->suumo_id) || empty($shop->suumo_pw)){
                $msg .= 'SUUMO ';
            }
            if(empty($shop->homes_id) || empty($shop->homes_pw)){
                $msg .= 'HOMES ';
            }
            if(empty($shop->athome_id) || empty($shop->athome_pw)){
                $msg .= 'at home ';
            }
            $msg .= 'のログイン情報が不正です。<br> 店舗情報画面で「ID」「Password」を更新してください。';
            return response()->json(
                [
                    'status'    =>  false,
                    'msg'       =>  $msg,
                    'suumo_linked' => $shop->suumo_linked,
                    'homes_linked' => $shop->homes_linked,
                    'athome_linked' => $shop->athome_linked
                ]
            );
        }*/else{
            return response()->json(
                [
                    'status'    =>  true,
                    'msg'       =>  '',
                    'suumo_linked' => $shop->suumo_linked,
                    'homes_linked' => $shop->homes_linked,
                    'athome_linked' => $shop->athome_linked
                ]
            );
        }
    }
    public function changeStaff(Request $request){
        $user = Auth::user();
        $html = '';
        if(isset($request->store_id)){
            $user = User::getDataByStoreId($user->company_id, $request->store_id);
            foreach($user as $key => $item){
                $html .= '<option value="'.$item['code'].'"';
                if(isset($request->selected) && $request->selected == $item['code']){
                    $html .= ' selected';
                }
                $html .= '>'.$item['name'].'</option>';
            }
        }
        return $html;
    }
    public function setLeaseRank(Request $request, CompanyApiService $apiService)
    {
        $response = [];
        $data = ['order' => $request->num];
        Lease::where('id', '=', $request->id)->first()->update($data);

        $apiService->setLeaseRank($request->id, $data);

        return response()->json($response);
    }

    /**
     * @param $date
     * @param $article
     * @return void
     */
    private function calculateDate($date, $article)
    {
        if ($date === '大正以前' || $date == '築年不詳') {
        } else if (str_contains($date, '不詳')) {
            $age_year_month = explode('年', $date);
            $article->age_year = $age_year_month[0];
        } else {
            $age_year_month = explode('年', $date);
            $article->age_year = $age_year_month[0];
            $age_year_month = explode('）', $date);
            $article->age_month = str_replace(['月', '?'], '', $age_year_month[1]);
            if (!is_numeric($article->age_month)) {
                $article->age_month = mb_substr($article->age_month, 1);
            }
        }
    }
}
