<template>
    <view class="insurance-payback c-gap-inner-top-large c-gap-inner-bottom-large c-gap-top">
        <view class="insurance-payback-title c-font-medium c-font-wb">{{ moduleTitle }}</view>
        <!-- 省市和类型选择 -->
        <view class="insurance-payback-picker">
            <view class="picker-line c-line-clamp1 c-gap-top">
                <text class="left c-color-gray">{{ chooseRegion }}</text>
                <picker
                    mode="multiSelector"
                    :title="regionPicker.title"
                    :range="[provinceList, cityList]"
                    :value="[0, 0]"
                    @change="handleRegionSelectorChange"
                    @columnchange="handleRegionSelectorColumnChange"
                >
                    <view v-if="pickerAddress" class="right">
                        <text>{{ pickerAddress }}</text>
                        <c-icon
                            :font-size="iconSize"
                            name="right"
                            class="c-gap-left-small"
                        />
                    </view>
                </picker>
            </view>
            <view class="picker-line c-line-clamp1 c-gap-top">
                <text class="left c-color-gray">{{ chooseInsuranceType }}</text>
                <picker
                    mode="selector"
                    range-key="name"
                    :title="typePicker.title"
                    :range="typePicker.selector"
                    :value="typePicker.arrIndex"
                    @change="handleTypeSelectorChange"
                >
                    <view v-if="insuranceType" class="right">
                        <text>{{ insuranceType }}</text>
                        <c-icon
                            :font-size="iconSize"
                            name="right"
                            class="c-gap-left-small"
                        />
                    </view>
                </picker>
            </view>
        </view>
        <!-- tab区域 -->
        <view class="insurance-payback-tabs c-gap-top-ll">
            <view class="tab-portion">
                <view
                    v-for="(tab, index) in tabHeader.iterableList"
                    :key="'tab_' + index"
                    :class="['tab-item', currentSelectedTab === tab.type ? 'active' : '']"
                    @tap="handleTabItemTap(tab)"
                >
                    {{ tab.text }}
                </view>
            </view>
            <view class="content-portion c-gap-top">
                <view class="content-caption-line c-row c-color-gray">
                    <text v-if="captionGroup[0]" class="c-span4 c-line-clamp1">{{ captionGroup[0] }}</text>
                    <text v-if="captionGroup[1]" class="c-span5 c-line-clamp1 c-tac">{{ captionGroup[1] }}</text>
                    <text v-if="captionGroup[2]" class="c-span3 c-line-clamp1 c-tar">{{ captionGroup[2] }}</text>
                </view>
                <block v-if="contentCollection && contentCollection.length">
                    <view
                        v-for="(content, index) in contentCollection"
                        :key="'content_' + index"
                        class="content-detail-line c-row"
                    >
                        <text v-if="content.level" class="c-span4 c-line-clamp1">{{ content.level }}</text>
                        <text v-if="content.payback" class="c-span5 c-line-clamp1 c-tac">{{ content.payback }}</text>
                        <text
                            v-if="content.subIds && content.subIds.length > 0"
                            class="c-span3 c-line-clamp1 c-tar c-color-main"
                            @tap="handleTabDetailTap(content)"
                        >
                            {{ tabDetail }}
                        </text>
                        <text v-else-if="content.percentage" class="c-span3 c-line-clamp1 c-tar">
                            {{ content.percentage }}
                        </text>
                    </view>
                </block>
                <block v-else>
                    <view class="content-detail-line c-row c-tac">
                        <text class="c-span12 c-line-clamp1">{{ errorMessage }}</text>
                    </view>
                </block>
            </view>
        </view>
        <!-- popup浮层 -->
        <c-popup
            :show="popupOpts.show"
            :title="popupOpts.title"
            :height="popupOpts.height"
            :show-title-line="popupOpts.showTitleLine"
            :show-close-handler="popupOpts.showCloseHandler"
            :btns="popupOpts.btnGroup"
            show-close
            close-icon="close-circle"
            @close="handlePopupClose"
            @btntap="handlePopupBtnTap"
        >
            <view class="c-row c-color-gray c-gap-top-mini">
                <text v-if="captionGroup[0]" class="c-span4 c-line-clamp1">{{ captionGroup[0] }}</text>
                <text v-if="captionGroup[1]" class="c-span5 c-line-clamp1 c-tac">{{ captionGroup[1] }}</text>
                <text v-if="captionGroup[2]" class="c-span3 c-line-clamp1 c-tar">{{ captionGroup[2] }}</text>
            </view>
            <view
                v-for="(content, index) in popupContentCollection"
                :key="'detail_' + index"
                class="c-row"
            >
                <text v-if="content.level" class="c-span4 c-line-clamp1">{{ content.level }}</text>
                <text v-if="content.payback" class="c-span5 c-line-clamp1 c-tac">{{ content.payback }}</text>
                <text v-if="content.percentage" class="c-span3 c-line-clamp1 c-tar">{{ content.percentage }}</text>
            </view>
        </c-popup>
    </view>
</template>

<script>
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import CPopup from '@baidu/med-ui/components/Popup/Popup';
import {request} from '@utils/request';
import {ubcSend} from '@utils/log';
import * as core from '@utils/core';
import * as Conf from '@utils/conf';

/**
 * @file 医保信息页/医保报销比例
 * @author chenyang28
 * @categories 商业化
 * @tags [component]
 */
export default {
    config: {
        component: true
    },
    props: {
        /**
         * url查询参数
         */
        query: {
            type: Object,
            default: () => {}
        },
        /**
         * 省市picker
         */
        regionPicker: {
            type: Object,
            default: () => {}
        },
        /**
         * 参保类型picker
         */
        typePicker: {
            type: Object,
            default: () => {}
        },
        /**
         * 医保报销比例tab header
         */
        tabHeader: {
            type: Object,
            default: () => {}
        },
        /**
         * 医保报销比例tab content
         */
        tabContentCollection: {
            type: Array,
            default: () => []
        }
    },
    data() {
        const asyncApi = Conf.apiHost + '/bus/ins';
        return {
            asyncApi: asyncApi,
            isAsync: false,
            iconSize: '16px',
            defaultTab: 'zhuyuan',
            currentSelectedTab: '',
            moduleTitle: '医保报销比例',
            chooseRegion: '选择省市',
            chooseInsuranceType: '选择医保类型',
            tabDetail: '查看详情',
            errorMessage: '暂无医保数据',
            popupOpts: {
                title: '报销详情',
                height: '48%',
                btnGroup: [
                    {
                        text: '我知道了',
                        color: '#ffffff',
                        background: '#00c8c8'
                    }
                ],
                show: false,
                showTitleLine: true,
                showCloseHandler: false
            },
            captionGroup: [
                '医疗机构等级',
                '起付线/报销限额',
                '报销比例'
            ],
            queryParams: {
                province: '',
                city: '',
                type: '',
                brandname: ''
            },
            pickerAddress: '',
            insuranceType: '',
            provinceList: [],
            cityList: [],
            contentCollection: [],
            asyncTabContentCollection: [],
            popupContentCollection: []
        };
    },
    components: {
        CPopup,
        CIcon
    },
    created() {
        this.queryParams = core.extend(this.queryParams, {...this.query});
        this.currentSelectedTab = this.defaultTab;
        this.contentCollection = this.tabContentCollection.filter(this.filterByDefaultCategory);
        this.initRegionPickerData();
        this.initTypePickerData();
    },
    watch: {
        query(newQuery) {
            if (newQuery && newQuery.brandname) {
                this.queryParams = core.extend(this.queryParams, {...newQuery});
            }
        },
        tabContentCollection(newCollection) {
            if (newCollection && newCollection.length) {
                this.contentCollection = '';
                this.contentCollection = newCollection.filter(this.filterByDefaultCategory);
            }
        },
        typePicker(newPicker) {
            if (newPicker && newPicker.title && newPicker.selector && newPicker.selector.length) {
                this.typePicker.selector = newPicker.selector;
                this.typePicker.title = newPicker.title;
                this.typePicker.arrIndex = newPicker.arrIndex || 0;
                this.initTypePickerData();
            }
        },
        regionPicker(newPicker) {
            if (newPicker && newPicker.title && newPicker.selector && newPicker.selector.length) {
                this.regionPicker.selector = newPicker.selector;
                this.regionPicker.title = newPicker.title;
                this.regionPicker.arrIndex = newPicker.selector || [0, 0];
                this.initRegionPickerData();
            }
        }
    },
    methods: {
        initRegionPickerData() {
            if (this.regionPicker && this.regionPicker.selector && this.regionPicker.selector.length) {
                this.regionPicker.selector.forEach((region, index) => {
                    if (index === 0) {
                        this.cityList = region.cityList || [];
                    }
                    if (region.province) {
                        this.provinceList.push(region.province);
                    }
                });

                const province = this.provinceList[0] || '';
                const city = this.cityList[0] || '';

                this.queryParams = core.extend(
                    this.queryParams,
                    {province: province, city: city}
                );
                this.pickerAddress = `${province}${city}`;
            }
        },
        initTypePickerData() {
            if (this.typePicker && this.typePicker.selector && this.typePicker.selector.length) {
                const arrIndex = this.typePicker.arrIndex || 0;
                const name = this.typePicker.selector[arrIndex] ? this.typePicker.selector[arrIndex].name : '';

                if (name) {
                    this.queryParams = core.extend(this.queryParams, {type: name});
                    this.insuranceType = name;
                }
            }
        },
        fetchDataByParams(params) {
            ubcSend({
                type: 'clk',
                value: 'query_insurance',
                ext: {
                    pd: 'yd',
                    module: 'business',
                    params: core.extend(params, {brandname: this.queryParams.brandname})
                }
            });

            request({
                url: this.asyncApi,
                method: 'GET',
                data: {
                    province: params.province,
                    city: params.city,
                    type: params.type,
                    brandname: params.brandname
                },
                isNeedLogin: false,
                isFirstScreen: false
            })
                .then(res => {
                    const {tabContentCollection} = res.data || {};
                    this.asyncTabContentCollection = tabContentCollection || [];
                    this.isAsync = true;
                    this.currentSelectedTab = this.defaultTab;
                    this.contentCollection = '';
                    this.contentCollection = this.asyncTabContentCollection.filter(this.filterByDefaultCategory);
                    res.update.call(this);
                })
                .catch(err => { console.log(err); });
        },
        filterByDefaultCategory(content) {
            return this.defaultTab === content.category && content.displayLevel === 1;
        },
        handleTabItemTap(tab) {
            ubcSend({
                type: 'clk',
                value: 'insurance_tab_click',
                ext: {
                    pd: 'yd',
                    module: 'business',
                    tab: tab.type,
                    brandname: this.queryParams.brandname
                }
            });

            const contentCollection = this.isAsync ? this.asyncTabContentCollection : this.tabContentCollection;
            this.currentSelectedTab = tab.type;
            this.contentCollection = '';
            this.contentCollection = contentCollection.filter(content => {
                return tab.type === content.category && content.displayLevel === 1;
            });
        },
        handlePopupBtnTap() {
            this.popupOpts.show = false;
        },
        handlePopupClose() {
            this.popupOpts.show = false;
        },
        handleTabDetailTap(subContent) {
            ubcSend({
                type: 'clk',
                value: 'check_insurance_detail',
                ext: {
                    pd: 'yd',
                    module: 'business',
                    category: subContent.category,
                    cid: subContent.cid,
                    brandname: this.queryParams.brandname
                }
            });

            const contentCollection = this.isAsync ? this.asyncTabContentCollection : this.tabContentCollection;
            this.popupContentCollection = '';
            this.popupContentCollection = contentCollection.filter(content => {
                return subContent.subIds.includes(content.cid) && content.displayLevel === 2;
            });
            this.popupOpts.show = true;
        },
        handleTypeSelectorChange(e) {
            const pickerValue = e && e.detail && e.detail.value;
            const insurance = this.typePicker.selector && this.typePicker.selector[pickerValue];

            if (!insurance || !insurance.name) {
                return;
            }

            this.insuranceType = insurance.name;
            this.queryParams = core.extend(
                this.queryParams,
                {type: insurance.name}
            );
            this.fetchDataByParams(this.queryParams);
        },
        handleRegionSelectorChange(e) {
            const pickerValue = e && e.detail && e.detail.value;
            const pIndex = pickerValue[0] || 0;
            const cIndex = pickerValue[1] || 0;
            const province = this.provinceList[pIndex] || '';
            const city = this.cityList[cIndex] || '';

            if (!province || !city) {
                return;
            }

            this.pickerAddress = `${province}${city}`;
            this.queryParams = core.extend(
                this.queryParams,
                {province: province, city: city}
            );
            this.fetchDataByParams(this.queryParams);
        },
        handleRegionSelectorColumnChange(e) {
            const pickerColumn = e && e.detail && e.detail.column;
            const pickerValue = e && e.detail && e.detail.value;

            if (pickerColumn !== 0) {
                return;
            }

            const province = this.provinceList[pickerValue || 0];
            this.regionPicker.selector.forEach(region => {
                if (region.province === province) {
                    this.cityList = region.cityList;
                }
            });
        }
    }
};
</script>

<style lang="less" scoped>
.insurance-payback {
    background: #ffffff;
    padding-left: 17px;
    padding-right: 17px;

    &-picker {
        .picker-line {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            line-height: 23px;
        }
    }

    &-tabs {
        .tab-portion {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            text-align: center;
            border-radius: 9px;
            height: 36px;
            background: #f5f5f5;
            padding: 2px 3px;
            box-sizing: border-box;
            .tab-item {
                flex: 1 1 auto;
                height: 32px;
                line-height: 32px;
                font-weight: 400;
                &.active {
                    color: #00C8C8;
                    background: #ffffff;
                    border-radius: 7px;
                    box-shadow: 0 0 4px 0 rgba(0,0,0,0.1);
                }
            }
        }
    }

    .c-row {
        line-height: 32px;
    }
}
</style>
