/* Axtarış / Filter — Inspector-un tam obyekt filtrinin mobil ekvivalenti.
   8 qrup / 40+ sahə, ReportDto ilə eyni struktur. Qruplar açılıb-yığılan
   (accordion) formatındadır ki, mobil ekranda rahat olsun. */
Vue.component('search-view', {
    mixins: [window.ListMixin],
    data: function () {
        var L = window.MOCK.filterLookups;
        return {
            lk: L,
            searched: false,
            open: { dates: true, search: true, status: false, work: false, cons: false, main: false, permit: false, oper: false },
            // yes/no/all selects (dəyər: -1 Hamısı, 1 Bəli, 0 Xeyr)
            yesNo: [{ v: -1, t: 'Hamısı' }, { v: 1, t: 'Bəli' }, { v: 0, t: 'Xeyr' }],
            debtOpts: [{ v: -1, t: 'Hamısı' }, { v: 1, t: 'Var' }, { v: 0, t: 'Yoxdur' }],
            // multiselect qrupları: [key, başlıq, lookupKey]
            consGroups: [
                ['types', 'Daxilolma tipi', 'types'],
                ['registrationTypes', 'Qeydəalınma vəziyyəti', 'registrationTypes'],
                ['destinations', 'Tikintinin təyinatı', 'destinations'],
                ['statuses', 'Tikintinin vəziyyəti', 'statuses'],
                ['conclusions', 'Tikintinin nəticəsi', 'conclusions']
            ],
            mainGroups: [
                ['regions', 'Region', 'regions'],
                ['districts', 'Rayon', 'districts'],
                ['financeSources', 'Maliyyə mənbəyi', 'financeSources'],
                ['customerTypes', 'Sifarişçinin tipi', 'customerTypes']
            ],
            permitGroups: [
                ['ownershipTypes', 'Torpağın mülkiyyət sənədi', 'ownershipTypes'],
                ['results', 'Ekspertiza rəyi', 'results'],
                ['permitIssuers', 'Tikintiyə icazə', 'permitIssuers']
            ],
            operGroups: [
                ['dnjStatuses', 'DNJ', 'dnjStatuses'],
                ['tqrAvailability', 'TQR', 'tqrAvailability'],
                ['ihaAvailability', 'İHA', 'ihaAvailability'],
                ['extractStatuses', 'Çıxarış', 'extractStatuses']
            ],
            workPurposes: [
                ['wp1', 'Əsaslı tikinti'], ['wp2', 'Əsaslı təmir'], ['wp3', 'Bərpa-güclən.'],
                ['wp4', 'Yenidənqurma'], ['wp5', 'Cari təmir'], ['wp6', 'Söküntü işləri']
            ],
            f: this.blankFilter()
        };
    },
    computed: {
        activeCount: function () {
            var f = this.f, c = 0;
            ['customer', 'applicant', 'contractor', 'address', 'name', 'group'].forEach(function (k) { if (f[k]) c++; });
            Object.keys(f.dates).forEach(function (k) { if (f.dates[k].from || f.dates[k].to) c++; });
            ['iao', 'hasExtract', 'hasTbc', 'hasDadasov', 'expertiseDebt', 'measureDebt'].forEach(function (k) { if (f[k] !== -1) c++; });
            for (var i = 1; i <= 6; i++) if (f['wp' + i] !== -1) c++;
            Object.keys(f.ms).forEach(function (k) { if (f.ms[k].length) c += 1; });
            return c;
        }
    },
    methods: {
        fmt: function () { return window.fmt; },
        blankFilter: function () {
            var ms = {};
            ['types', 'registrationTypes', 'destinations', 'statuses', 'conclusions', 'regions', 'districts',
             'financeSources', 'customerTypes', 'ownershipTypes', 'results', 'permitIssuers',
             'dnjStatuses', 'tqrAvailability', 'ihaAvailability', 'extractStatuses'].forEach(function (k) { ms[k] = []; });
            return {
                customer: '', applicant: '', contractor: '', address: '', name: '', group: '',
                dates: { entry: { from: '', to: '' }, start: { from: '', to: '' }, conclusion: { from: '', to: '' }, due: { from: '', to: '' }, finish: { from: '', to: '' } },
                iao: -1, hasExtract: -1, hasTbc: -1, hasDadasov: -1, expertiseDebt: -1, measureDebt: -1,
                wp1: -1, wp2: -1, wp3: -1, wp4: -1, wp5: -1, wp6: -1,
                ms: ms
            };
        },
        toggle: function (g) { this.$set(this.open, g, !this.open[g]); },
        pick: function (key, id) {
            var arr = this.f.ms[key], i = arr.indexOf(id);
            if (i >= 0) arr.splice(i, 1); else arr.push(id);
        },
        selected: function (key, id) { return this.f.ms[key].indexOf(id) >= 0; },
        nameOf: function (lookupKey, id) {
            if (!id) return '';
            var it = this.lk[lookupKey].find(function (x) { return x.id === id; });
            return it ? it.name : '';
        },
        run: function () {
            this.searched = true;
            // mock backend yalnız bir neçə sahəyə görə süzür; UI tam ReportDto sahələrini toplayır
            this.query = {
                search: this.f.name || this.f.customer || this.f.applicant || '',
                district: this.nameOf('districts', this.f.ms.districts[0]),
                status: this.nameOf('statuses', this.f.ms.statuses[0])
            };
            this.fetchList('objects', true);
        },
        reset: function () { this.f = this.blankFilter(); this.searched = false; this.items = []; this.total = 0; }
    },
    template: `
    <div>
        <!-- Tarixlər -->
        <div class="facc">
            <button class="facc__head" @click="toggle('dates')"><i class="fa-light fa-calendar-days"></i><span>Tarixlər</span><i class="fa-light facc__chev" :class="open.dates?'fa-chevron-up':'fa-chevron-down'"></i></button>
            <div v-show="open.dates" class="facc__body">
                <div class="fdate" v-for="d in [['entry','Daxil olma'],['start','Başlama'],['conclusion','Nəticə tarixi'],['due','Son tarix'],['finish','Bitmə tarixi']]" :key="d[0]">
                    <label>{{ d[1] }}</label>
                    <div class="u-row g-6">
                        <input type="date" class="input" v-model="f.dates[d[0]].from">
                        <input type="date" class="input" v-model="f.dates[d[0]].to">
                    </div>
                </div>
            </div>
        </div>

        <!-- Axtarış (mətn) -->
        <div class="facc">
            <button class="facc__head" @click="toggle('search')"><i class="fa-light fa-magnifying-glass"></i><span>Axtarış</span><i class="fa-light facc__chev" :class="open.search?'fa-chevron-up':'fa-chevron-down'"></i></button>
            <div v-show="open.search" class="facc__body">
                <div class="field"><label>Sahib</label><input class="input" v-model="f.customer" placeholder="Sahibin adı"></div>
                <div class="field"><label>Sifarişçi</label><input class="input" v-model="f.applicant" placeholder="Sifarişçinin adı"></div>
                <div class="field"><label>Podratçı</label><input class="input" v-model="f.contractor" placeholder="Podratçı"></div>
                <div class="field"><label>Ünvan</label><input class="input" v-model="f.address" placeholder="Ünvan"></div>
                <div class="field"><label>Obyektin adı</label><input class="input" v-model="f.name" placeholder="Obyektin adı"></div>
            </div>
        </div>

        <!-- Status -->
        <div class="facc">
            <button class="facc__head" @click="toggle('status')"><i class="fa-light fa-toggle-on"></i><span>Status</span><i class="fa-light facc__chev" :class="open.status?'fa-chevron-up':'fa-chevron-down'"></i></button>
            <div v-show="open.status" class="facc__body">
                <div class="fyn" v-for="s in [['iao','İAO'],['hasExtract','Çıxarış'],['hasTbc','TBÇ'],['hasDadasov','Dadaşov']]" :key="s[0]">
                    <label>{{ s[1] }}</label>
                    <div class="segmented segmented--sm"><button v-for="o in yesNo" :key="o.v" :class="{active:f[s[0]]===o.v}" @click="f[s[0]]=o.v">{{ o.t }}</button></div>
                </div>
                <div class="field"><label>Qrup</label><input type="number" class="input" v-model="f.group" placeholder="Qrup №"></div>
                <div class="fyn" v-for="s in [['expertiseDebt','Ekspertiza borcu'],['measureDebt','İnzibati borc']]" :key="s[0]">
                    <label>{{ s[1] }}</label>
                    <div class="segmented segmented--sm"><button v-for="o in debtOpts" :key="o.v" :class="{active:f[s[0]]===o.v}" @click="f[s[0]]=o.v">{{ o.t }}</button></div>
                </div>
            </div>
        </div>

        <!-- İşin təyinatı -->
        <div class="facc">
            <button class="facc__head" @click="toggle('work')"><i class="fa-light fa-briefcase"></i><span>İşin təyinatı</span><i class="fa-light facc__chev" :class="open.work?'fa-chevron-up':'fa-chevron-down'"></i></button>
            <div v-show="open.work" class="facc__body">
                <div class="fyn" v-for="w in workPurposes" :key="w[0]">
                    <label>{{ w[1] }}</label>
                    <div class="segmented segmented--sm"><button v-for="o in yesNo" :key="o.v" :class="{active:f[w[0]]===o.v}" @click="f[w[0]]=o.v">{{ o.t }}</button></div>
                </div>
            </div>
        </div>

        <!-- Tikintinin Axtarışı -->
        <div class="facc">
            <button class="facc__head" @click="toggle('cons')"><i class="fa-light fa-layer-group"></i><span>Tikintinin Axtarışı</span><i class="fa-light facc__chev" :class="open.cons?'fa-chevron-up':'fa-chevron-down'"></i></button>
            <div v-show="open.cons" class="facc__body">
                <div class="fms" v-for="g in consGroups" :key="g[0]">
                    <div class="fms__label">{{ g[1] }}<span v-if="f.ms[g[0]].length" class="badge">{{ f.ms[g[0]].length }}</span></div>
                    <div class="chips chips--wrap">
                        <div v-for="it in lk[g[2]]" :key="it.id" class="chip" :class="{active:selected(g[0],it.id)}" @click="pick(g[0],it.id)">{{ it.name }}</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Əsas Göstəricilər -->
        <div class="facc">
            <button class="facc__head" @click="toggle('main')"><i class="fa-light fa-chart-simple"></i><span>Əsas Göstəricilər</span><i class="fa-light facc__chev" :class="open.main?'fa-chevron-up':'fa-chevron-down'"></i></button>
            <div v-show="open.main" class="facc__body">
                <div class="fms" v-for="g in mainGroups" :key="g[0]">
                    <div class="fms__label">{{ g[1] }}<span v-if="f.ms[g[0]].length" class="badge">{{ f.ms[g[0]].length }}</span></div>
                    <div class="chips chips--wrap">
                        <div v-for="it in lk[g[2]]" :key="it.id" class="chip" :class="{active:selected(g[0],it.id)}" @click="pick(g[0],it.id)">{{ it.name }}</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tikintiyə icazəverici sənədlər -->
        <div class="facc">
            <button class="facc__head" @click="toggle('permit')"><i class="fa-light fa-file-certificate"></i><span>Tikintiyə icazəverici sənədlər</span><i class="fa-light facc__chev" :class="open.permit?'fa-chevron-up':'fa-chevron-down'"></i></button>
            <div v-show="open.permit" class="facc__body">
                <div class="fms" v-for="g in permitGroups" :key="g[0]">
                    <div class="fms__label">{{ g[1] }}<span v-if="f.ms[g[0]].length" class="badge">{{ f.ms[g[0]].length }}</span></div>
                    <div class="chips chips--wrap">
                        <div v-for="it in lk[g[2]]" :key="it.id" class="chip" :class="{active:selected(g[0],it.id)}" @click="pick(g[0],it.id)">{{ it.name }}</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- İstismara icazəverici sənədlər -->
        <div class="facc">
            <button class="facc__head" @click="toggle('oper')"><i class="fa-light fa-file-shield"></i><span>İstismara icazəverici sənədlər</span><i class="fa-light facc__chev" :class="open.oper?'fa-chevron-up':'fa-chevron-down'"></i></button>
            <div v-show="open.oper" class="facc__body">
                <div class="fms" v-for="g in operGroups" :key="g[0]">
                    <div class="fms__label">{{ g[1] }}<span v-if="f.ms[g[0]].length" class="badge">{{ f.ms[g[0]].length }}</span></div>
                    <div class="chips chips--wrap">
                        <div v-for="it in lk[g[2]]" :key="it.id" class="chip" :class="{active:selected(g[0],it.id)}" @click="pick(g[0],it.id)">{{ it.name }}</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Nəticələr -->
        <div v-if="searched" class="u-mt">
            <div class="section-head"><h3>Nəticələr</h3><span class="count">{{ total }} obyekt</span></div>
            <ui-skeleton-list v-if="loading" :rows="4"></ui-skeleton-list>
            <ui-empty v-else-if="!items.length" title="Nəticə yoxdur" hint="Filtri dəyişməyi sınayın"></ui-empty>
            <div v-else class="list list--grid">
                <div v-for="o in items" :key="o.Id" class="list-item" @click="$emit('open-object', o)">
                    <div class="list-item__lead"><i class="fa-light fa-building"></i></div>
                    <div class="list-item__main">
                        <div class="li-head"><span class="pill pill--num">№ {{ o.Id }}</span><status-pill :text="o.StatusName" :tone="o.StatusTone" dot></status-pill></div>
                        <div class="list-item__title mt-6">{{ o.ObjectName }}</div>
                        <div class="list-item__meta"><span><i class="fa-solid fa-user"></i>{{ o.CustomerName }}</span><span><i class="fa-solid fa-location-dot"></i>{{ o.DistrictName }}</span></div>
                    </div>
                </div>
            </div>
            <infinite-loader v-if="!loading" :has-more="hasMore" :loading="loadingMore" :loaded="items.length" :total="total" @load="fetchList('objects')"></infinite-loader>
        </div>

        <!-- Sticky action bar -->
        <div class="filter-actions">
            <button class="btn btn--outline" @click="reset"><i class="fa-light fa-eraser"></i></button>
            <button class="btn btn--brand u-grow" @click="run"><i class="fa-light fa-magnifying-glass"></i>Axtar<span v-if="activeCount"> · {{ activeCount }}</span></button>
        </div>
    </div>`
});
