<template>
    <view v-if="forms" class="form">
        <view class="form-wrapper">
            <view
                v-for="(form, formIndex) in forms"
                :key="formIndex"
                class="form-item c-row"
                :class="[formIndex === forms.length - 1 ? '' : 'form-item-border']"
            >
                <view class="form-wrapper__title c-span2">
                    {{ form.title }}
                </view>
                <view class="form-wrapper__input c-span8">
                    <!-- idcard -->
                    <view v-if="form.inputName === 'idcard'" class="pr">
                        <input
                            type="text"
                            :value="form.value"
                            :focus="form.focus"
                            :name="form.inputName"
                            :placeholder="form.placeholder"
                            :maxlength="form.maxlength"
                            placeholder-class="form-input-placeholder"
                            autocomplete="off"
                            class="form-input c-font-15"
                            @input="formInput($event, formIndex)"
                            @blur="formBlur($event, formIndex)"
                        >
                    </view>
                    <!-- 姓名 -->
                    <view v-else-if="form.inputName === 'name'" class="pr">
                        <input
                            type="text"
                            :value="form.value"
                            :focus="form.focus"
                            :name="form.inputName"
                            :placeholder="form.placeholder"
                            :maxlength="form.maxlength"
                            autocomplete="off"
                            cursor-spacing="20"
                            placeholder-class="form-input-placeholder"
                            class="form-input c-font-15"
                            @focus="formFocus($event, formIndex)"
                            @input="formInput($event, formIndex)"
                            @blur="formBlur($event, formIndex)"
                        >
                        <view
                            v-if="(form.value && (curInputName === form.inputName))"
                            class="form-select-close"
                            @tap.stop="delTap(formIndex)"
                        >
                            <c-icon
                                name="close-circle"
                                font-size="18px"
                                class="c-color-gray"
                                @tap.stop="delTap(formIndex)"
                            />
                        </view>
                    </view>
                    <!-- tel 输入框 h5Number类型input无法显示*** 需要模拟下-->
                    <view v-else-if="form.type === 'tel'" class="pr">
                        <input
                            type="number"
                            :value="form.value"
                            :focus="form.focus"
                            :name="form.inputName"
                            :placeholder="form.placeholder"
                            :maxlength="form.maxlength"
                            autocomplete="off"
                            placeholder-class="form-input-placeholder"
                            class="form-input c-font-15"
                            @focus="formFocus($event, formIndex)"
                            @input="formInput($event, formIndex)"
                            @blur="formBlur($event, formIndex)"
                        >
                        <view
                            v-if="(form.value && (curInputName === form.inputName))"
                            class="form-select-close"
                            @tap.stop="delTap(formIndex)"
                        >
                            <c-icon
                                name="close-circle"
                                font-size="18px"
                                class="c-color-gray"
                                @tap.stop="delTap(formIndex)"
                            />
                        </view>
                    </view>
                    <!-- 级联选择器 先不上-->
                    <view v-else-if="form.type === 'multiSelect'">
                        <view
                            :class="[
                                'form-select-text',
                                'pr',
                                'c-line-clamp1',
                                form.value ? 'c-color-title' : 'c-color-b8',
                            ]"
                            @tap.stop="selectTap"
                        >
                            {{ form.value || form.placeholder }}
                            <c-icon
                                name="more"
                                font-size="12px"
                                class="form-select-arrow c-font-wb c-color-gray"
                            />
                        </view>
                    </view>
                    <!-- 选择地址 -->
                    <view v-else-if="form.type === 'chooseLocation'" class="form-select form-item__box">
                        <input
                            type="text"
                            :value="form.value"
                            :focus="form.focus"
                            :name="form.inputName"
                            :placeholder="form.placeholder"
                            :maxlength="form.maxlength"
                            autocomplete="off"
                            cursor-spacing="300"
                            placeholder-class="form-input-placeholder"
                            class="form-input c-font-15"
                            @input="formInput($event, formIndex)"
                            @blur="formBlur($event, formIndex)"
                        >
                        <view
                            v-if="showAddressTip && addSuglist && addSuglist.length"
                            class="form-item__select__container"
                        >
                            <view class="form-item__select__box">
                                <view
                                    v-for="(info, index) in addSuglist"
                                    :key="index"
                                    class="form-item__select__item"
                                    @tap.stop="autoCompletionTap(info, formIndex)"
                                >
                                    <rich-text
                                        class="c-line-clamp1 c-color form-item__select__item__title"
                                        :nodes="info.otherName"
                                        @tap.stop="autoCompletionTap(info, formIndex)"
                                    />
                                    <rich-text
                                        class="c-line-clamp1 c-color-gray form-item__select__item__detail"
                                        :nodes="info.otherAddress"
                                        @tap.stop="autoCompletionTap(info, formIndex)"
                                    />
                                </view>
                            </view>
                        </view>
                    </view>
                    <!-- 普通输入框 -->
                    <input
                        v-else-if="form.type === 'input'"
                        type="text"
                        :value="form.value"
                        :focus="form.focus"
                        :name="form.inputName"
                        :placeholder="form.placeholder"
                        :maxlength="form.maxlength"
                        autocomplete="off"
                        cursor-spacing="20"
                        placeholder-class="form-input-placeholder"
                        class="form-input c-font-15"
                        @input="formInput($event, formIndex)"
                        @blur="formBlur($event, formIndex)"
                    >
                </view>
            </view>
        </view>
    </view>
</template>

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

/**
 * @author kangpuqing01
 * @file 地址表单组件
 * @categories 通用组件
 * @tags [component]
 */

let timer;
export default {
    config: {
        component: true
    },
    components: {
        CIcon
    },
    props: {
        /**
         * 表单数据
         * @param
         */
        forms: {
            type: Array,
            default: () => []
        },
        /**
         * areaInfos
         */
        areaInfos: {
            type: Object,
            default: () => {}
        },
        /**
         * placesuggestion
         */
        placesuggestion: {
            type: String,
            default: ''
        },
        /**
         * api Host
         */
        apiHost: {
            type: String,
            default: '56'
        }
    },
    computed: {
        host() {
            return this.apiHost === '56' ? Conf.apiHost : Conf.goApiHost;
        }
    },
    watch: {
        addSuglist(newList) {
            if (newList) {
                for (let i = 0; i < newList.length; i++) {
                    const info = newList[i];
                    const address = `${info.province}${info.city}${info.district || ''}${
                        info.town || ''
                    }`;
                    const name = info.name;
                    const otherAddress = this.getOtherText(address, this.detailAddress);
                    const otherName = this.getOtherText(name, this.detailAddress);

                    this.$set(newList[i], 'otherAddress', otherAddress);
                    this.$set(newList[i], 'otherName', otherName);
                }
            }
        }
    },
    data() {
        return {
            callbackUrl: '/med/page/gy/medstorecontactedit?vn=med',
            pageLoading: true,
            pageType: 'add',
            addSuglist: [],
            showAddressTip: false,
            curInputName: '',
            detailAddress: ''
        };
    },
    methods: {
        selectTap() {
            /** selectAreaTap */
            this.$emit('selectAreaTap');
        },
        formInput(e, formIndex) {
            const value = e.detail.value;
            this.$set(this.forms[formIndex], 'value', value);
            if (this.forms[formIndex].inputName === 'address') {
                this.$set(this, 'detailAddress', value);
                this.addressSug(value);
            }

            // 缓存收货信息。输入的时候就缓存，防止处方状态更新时刷新页面导致用户正在输入的内容丢失
            const storageContactInfo = this.$api.getStorageSync('contactInfo') || {};
            let formInfo = {};
            this.forms.forEach(item => {
                formInfo[item.inputName] = item.value;
            });
            this.$api.setStorage({
                key: 'contactInfo',
                data: {
                    ...storageContactInfo,
                    formInfo
                }
            });
        },
        formFocus(e, formIndex) {
            const form = this.forms[formIndex];
            // 异步设置，防止blur设置为空了
            setTimeout(() => {
                this.$set(this, 'curInputName', form.inputName);
            }, 0);
        },
        formBlur(e, formIndex) {
            this.$set(this.forms[formIndex], 'focus', false);
            // 解决收货地址blur隐藏用户选择提示，造成点击不成功问题
            setTimeout(() => {
                this.hideAll();
                this.$set(this, 'curInputName', '');
            }, 0);
            /** selectAreaTap */
            this.$emit('formBlur', this.forms, formIndex);
        },
        trim(str) {
            if (typeof str === 'string') {
                return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            }
        },
        addressSug(value) {
            if (!this.placesuggestion) {
                return;
            }
            clearTimeout(timer);
            timer = setTimeout(() => {
                request({
                    url: this.placesuggestion,
                    data: {
                        query: value,
                        region: this.areaInfos.city ||
                            (['北京市', '天津市', '上海市', '重庆市'].indexOf(this.areaInfos.province) >= 0
                                ? this.areaInfos.province : this.areaInfos.district),
                        cityLimit: true
                    },
                    method: 'POST',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    isFirstScreen: false,
                    isNeedLogin: true
                }).then(({data = {}}) => {
                    let {suggestion = []} = data;
                    this.$set(this, 'addSuglist', suggestion || []);
                    if (suggestion && suggestion.length) {
                        this.$set(this, 'showAddressTip', true);
                    }
                });
            }, 500);
        },
        autoCompletionTap(info, formIndex) {
            const form = this.forms[formIndex];
            info.addressName = this.forms[formIndex - 1].inputName;
            info.areaName = form.inputName;
            info.addressIndex = formIndex - 1;
            this.$set(form, 'value', info.name);
            /** changeAreaInfo */
            this.$emit('changeAreaInfo', info);
            this.hideAll();
        },
        hideAll() {
            this.$set(this, 'showAddressTip', false);
        },
        delTap(index) {
            const form = this.forms[index];

            form.value = '';
            this.$set(this.forms, index, form);
        },
        getOtherText(data, detailAddress) {
            if (!data || !detailAddress) {
                return '';
            }
            const text = data.replace(detailAddress, `<span style="color: #FD503E">${detailAddress}</span>`);
            return text;
        }
    }
};
</script>
<style lang="less" scoped>
.form-input-placeholder {
    color: #b8b8b8;
    font-size: 0.15rem;
    line-height: 0.23rem;
    margin: 0;
    padding: 0;
}

.form {
    color: #1f1f1f;

    &-wrapper {
        // box-shadow: 0 3px 20px rgba(0, 0, 0, 0.08);
        border-radius: 0.12rem;
        background: #fff;

        &__title {
            padding-left: 0;
        }

        &__input {
            padding-left: 0;
        }
    }

    &-item {
        margin: 0 0.13rem;
        height: 0.47rem;
        line-height: 0.47rem;
        font-size: 0.15rem;
        flex-wrap: wrap;
    }

    &-item-border {
        position: relative;

        &::after {
            content: '';
            position: absolute;
            background-color: #e0e0e0;
            display: block;
            width: 100%;
            height: 1px; /* no */
            transform: scale(1, 0.33);
            bottom: 0;
            left: 0;
        }
    }

    &-item:nth-last-child(1) {
        border: none;
    }

    &-input {
        color: #1f1f1f;
        line-height: 0.47rem;
        height: 0.47rem;
        outline: none;
        margin: 0;
        padding: 0;

        &:disabled {
            border: none;
            background-color: transparent;
            opacity: 1;
        }

        &::placeholder {
            .form-input-placeholder();
        }
    }
}

.form-item__box {
    width: 100%;
    position: absolute;

    .form-item__select__container {
        max-height: 3.3rem;
        z-index: 2;
        position: absolute;
        width: 3.21rem;
        background: #fff;
        border-radius: 6px;
        left: -20px;
    }

    .form-item__select__container::before {
        position: absolute;
        content: '';
        width: 8px;
        height: 8px;
        background-color: #fff;
        border-top: 1px solid rgba(208, 208, 208, 0.50);
        border-right: 1px solid rgba(208, 208, 208, 0.50);
        transform: rotate(-45deg);
        top: -5px;
        left: 15px;
        z-index: 3;
    }

    .form-item__select__box {
        max-height: 3.3rem;
        overflow: hidden;
        overflow-y: scroll;
        z-index: 2;
        position: absolute;
        width: 100%;
        background: #fff;
        border: 1px solid rgba(208, 208, 208, 0.50);
        border-radius: 5px;
        box-shadow: 2px 4px 5px #eee;
    }

    .form-item__select__item {
        line-height: 0.34rem;
        font-size: 0.14rem;
        padding-left: 0.14rem;
        position: relative;

        &__detail {
            line-height: 0.22rem;
            margin-bottom: 0.06rem;
            margin-top: -0.06rem;
        }

        &::after {
            content: " ";
            display: block;
            width: 100%;
            height: .01rem;
            position: absolute;
            left: 0;
            right: 0;
            background: #e0e0e0;
            transform: scaleY(.33);
        }
    }

    .form-item__select__item:nth-last-child(1) {
        border-bottom: none;
    }
}

.pr {
    position: relative;
}

.form-select-close {
    z-index: 2;
    height: 44px;
    width: 24px;
    position: absolute;
    right: -5px;
    top: 0;
    padding: 0 5px;
}

.form-select-arrow {
    position: absolute;
    right: 0;
    top: 0;
}

.c-color-b8 {
    color: #b8b8b8;
}
</style>
