<template>
    <view
        class="invoice"
    >
        <view @tap="onInvoiceShow">
            <view
                class="c-row z-info c-gap-inner-bottom-small c-color-title"
                :style="containerStyle"
            >
                <view class="tit c-span1">
                    {{ data.title }}
                </view>
                <view
                    class="cic c-span11 c-line-clamp1"
                >
                    <view
                        v-if="invoiceName"
                        class="c-line-clamp1 invoice__value c-gap-left"
                    >
                        <view class="invoice__value__info">普票（</view>
                        <view class="invoice__value__name c-line-clamp1">商品明细-{{ invoiceName }}</view>
                        <view class="invoice__value__info">）</view>
                    </view>
                    <text v-else>不开发票</text>
                </view>
                <view
                    v-if="data.api"
                    class="c-span1 tit"
                >
                    <c-icon
                        name="more"
                        font-size="13px"
                        :style="{
                            color: '#858585',
                            marginRight: '-4px',
                        }"
                    />
                </view>
            </view>
        </view>
        <c-popup
            :show="popup.show"
            :title="data.title"
            :btns="popup.btns"
            :max-height="'calc(100vh - 120px)'"
            :height="'calc(100vh - 120px)'"
            :show-close-handler="false"
            :btn-close="false"
            show-close
            scroll-view
            row-tile
            show-title-line
            @close="popupClose"
            @confirm="popupConfirm"
        >
            <!-- form -->
            <view 
                v-if="formInfo && formInfo.length"
                class="form c-gap-inner-left c-gap-inner-right c-color-title"
            >
                <template v-for="(form, formIndex) in formInfo">
                    <view
                        v-if="form.isShow"
                        :key="formIndex"
                    >
                        <view
                            v-if="formIndex !== 0 && form.topTitle"
                            :class="{
                                'c-gap-top': formIndex !== 0 && formInfo[formIndex - 1].title,
                            }"
                        >
                            <view class="c-line-superfine-before"/>
                        </view>
                        <view
                            class="form__item c-row c-row-align-middle c-gap-inner-top-small c-gap-inner-bottom-small"
                        >
                            <view
                                v-if="form.topTitle"
                                class="c-span1 form__item__tit c-font-big-less c-gap-inner-top  c-gap-inner-bottom"
                            >
                                <text class="c-font-wb">{{ form.topTitle }}</text>
                            </view>
                            <view
                                v-if="form.title"
                                class="c-span1 form__item__tit"
                            >
                                {{ form.title }}
                            </view>
                            <view
                                class="c-span8 form__item__cic"
                            >
                                <!-- 普通输入框 -->
                                <input
                                    v-if="form.type === 'input'"
                                    :value="formValue[form.inputName]"
                                    type="text"
                                    :name="form.inputName"
                                    :placeholder="form.placeholder"
                                    :maxlength="form.maxlength"
                                    :focus="form.focus"
                                    cursor-spacing="20"
                                    placeholder-class="form__input__placeholder"
                                    class="form__input c-tar"
                                    @input="formInput($event, form.inputName)"
                                >
                                <view v-else-if="form.type === 'select'">
                                    <picker
                                        class="form__select"
                                        :value="form | getIndex"
                                        :range="form.options"
                                        range-key="text"
                                        :title="form.title || form.topTitle"
                                        @change="selectChange($event, form)"
                                    >
                                        <view 
                                            class="form__select__text c-line-clamp1"
                                        >
                                            {{ form | getPickerValue }}
                                            <c-icon
                                                name="right"
                                                font-size="14px"
                                                class="form__select__arrow c-color-gray"
                                            />
                                        </view>
                                    </picker>
                                </view>
                            </view>
                            <view
                                v-if="form.type === 'selectTag'"
                                class="c-span12 form__item__cic c-gap-inner-bottom-small"
                            >
                                <view class="form__tags">
                                    <view
                                        v-for="(item, index) in form.options"
                                        :key="index"
                                        class="form__tags__item"
                                        @tap="handleChangeTag(form, item.value)"
                                    >
                                        <c-tags
                                            primary-color="transparent"
                                            color="#525252"
                                            background-color="#f6f6f6"
                                            background-color-selected="rgba(255,96,80,0.06)"
                                            :selected="item.value === formValue[form.inputName]"
                                            border-radius="20px"
                                            item-height="32px"
                                            selected-bold
                                        >
                                            <text class="form__tags__item__inner c-font-normal" :class="{'c-color-mall': item.value === formValue[form.inputName]}">{{ item.text }}</text>
                                        </c-tags>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </template>
                <view
                    v-if="tips"
                    class="c-gap-inner-top c-color-gray c-font-normal"
                >
                    <view class="c-line-superfine-before"/>
                    <view class="c-gap-top-large">
                        {{ tips }}
                    </view>
                </view>
            </view>
        </c-popup>
    </view>
</template>

<script>
/**
 * @file 发票填写
 * @author zhangeryi@baidu.com
 */
import CPopup from '@baidu/med-ui/components/Popup/Popup';
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import CTags from '@baidu/med-ui/components/Tags/TagItem';
import {request} from '@utils/request';
import {apiHost} from '@utils/conf';
import {send} from '@utils/log';
export default {
    config: {
        component: true
    },
    components: {
        CIcon,
        CPopup,
        CTags
    },
    props: {
        data: {
            type: Object,
            default() {
                return {};
            }
        },
        storeId: {
            type: String,
            default: ''
        },
        logkey: {
            type: String,
            default: ''
        },
        containerStyle: {
            type: Object,
            default() {
                return {};
            }
        },
    },
    data() {
        return {
            formInfo: [],
            formValue: {},
            submitApi: '',
            tips: '',
            invoiceName: '',
            popup: {
                show: false,
                title: '',
                btns: [{
                    text: '确定',
                    background: '#ff6050',
                    color: '#fff',
                    event: 'confirm'
                }]
            }
        };
    },
    filters: {
        getPickerValue(val) {
            return val.value && val.options.find(item => item.value === val.value).text;
        },
        getIndex(form) {
            let index = 0;
            for (let i = 0; i < form.options.length; i++) {
                if (form.options[i].value === form.value) {
                    index = i;
                }
            }
            return index;
        }
    },
    created() {
        let gyInvoiceIds = this.$api.getStorageSync('gyInvoiceIds') || {};
        let invoiceId = gyInvoiceIds[this.storeId] || '';
        if (invoiceId) {
            this.getInvoice({invoiceId});
            !this.data.invoiceId && this.$set(this.data, 'invoiceId', invoiceId);
        }
        
    },
    methods: {
        getInvoice(options = {}) {
            this.$api.showLoading({
                title: '加载中'
            });
            return request({
                // url: 'http://yapi.baidu-int.com/mock/200/med/gy/invoice',
                url: apiHost + this.data.api,
                data: {
                    invoiceId: this.data.invoiceId || options.invoiceId || ''
                },
                method: 'GET'
            }).then(({data}) => {
                let {formInfo, submitApi, tips} = data;
                this.getValue(formInfo);
                Object.assign(this, {formInfo, submitApi, tips});
                this.$api.hideLoading();
                options.invoiceId && this.getInvoiceName();
            })
                .catch(err => {
                    this.$api.hideLoading();
                });
        },
        setShow() {
            this.formInfo && this.formInfo.map(item => {
                item.show && this.getShow(item, this.formValue);
            });
        },
        getShow(item, form) {
            let isShow = true;
            if (item.show) {
                let [key, value] = item.show.split('=');
                isShow = form[key] === value;
            }
            this.$set(item, 'isShow', isShow);
        },
        getValue(formInfo) {
            let obj = {};
            formInfo && formInfo.map(item => {
                obj[item.inputName] = item.value;
                this.getShow(item, obj);
            });
            this.$set(this, 'formValue', obj);
        },
        onInvoiceShow() {
            this.getInvoice()
                .then(() => {
                    this.popup.show = true;
                });
            send({
                type: 'b',
                action: 'popupShow',
                extra: {
                    module: 'invoice__show'
                }
            });
        },
        formInput(e, formName) {
            const value = e.detail.value;
            this.$set(this.formValue, formName, value);
        },
        formBlur(e, formIndex) {
            this.$set(this.formInfo[formIndex], 'focus', false);
        },
        // 去空格
        trim(str) {
            if (typeof (str) === 'string') {
                return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            }
        },
        selectChange(e, form) {
            let value = form.options[e.detail.value].value;
            form.value = value;
            this.formValue[form.inputName] = value;
        },
        handleChangeTag(form, val) {
            this.formValue[form.inputName] = val;
            this.setShow();
        },
        popupClose() {
            this.popup.show = false;
            send({
                type: 'b',
                action: 'popupClose',
                extra: {
                    module: this.popup.title
                }
            });
        },
        popupConfirm() {
            if (this.formValue['invoice_info'] === '此订单不开具发票') {
                this.getInvoiceName();
                this.$set(this.data, 'invoiceId', '');
                return this.popupClose();
            } 
            
            let keys = Object.keys(this.formValue);
            let error = '';
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                this.formValue[key] = this.trim(this.formValue[key]);
                let form = this.formInfo.find(f => f.inputName === key);
                if (!this.formValue[key] && form.isShow) {
                    error = `请填写或选择${form.topTitle || form.title}`;
                    break;
                }
            };
            if (error) {
                return this.$api.showToast({
                    title: error,
                    icon: 'none'
                });
            }
            
            request({
                // url: 'http://yapi.baidu-int.com/mock/200/med/gy/invoice',
                url: apiHost + this.submitApi,
                data: {...this.formValue},
                method: 'GET'
            }).then(({data}) => {
                if (data.toast) {
                    return this.$api.showToast({
                        title: data.toast,
                        icon: 'none'
                    });
                }
                let {invoiceId} = data;
                this.$set(this.data, 'invoiceId', invoiceId);
                // 设置缓存
                let gyInvoiceIds = this.$api.getStorageSync('gyInvoiceIds') || {};
                gyInvoiceIds[this.storeId] = invoiceId;
                this.$api.setStorageSync('gyInvoiceIds', gyInvoiceIds);
                this.getInvoiceName();
                this.popupClose();
            });
        },
        getInvoiceName() {
            let text = '';
            if (this.formValue['invoice_info'] !== '此订单不开具发票') {
                this.formValue['invoice_type'] === '1'
                    ? text = this.formValue['personal_name']
                    : text = this.formValue['company_name'];
            }
            this.invoiceName = text;
        }
    }
};
</script>
<style lang="less">
@border: 1px solid #f1f1f1;
.wrapper {
    padding-left: .17rem;
    padding-right: .17rem;
}
.z-input {
    width: 100%;
    height: 25px;
    font: .15rem/.23rem Arial, Helvetica, sans-serif;
    text-align: right;
    outline: none;
    &-placeholder,
    &::placeholder {
        color: #858585;
    }
}
.invoice {
    &__value {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        &__info {
            flex: none;
            width: auto;
            &:last-child {
                margin-right: -7px;
            }
        }
    }
}
.form {
    &__item {
        position: relative;
        line-height: 25px;
        font-size: .15rem;
        flex-wrap: wrap;
        align-items: center;
        &__tit {
            width: auto;
            white-space: nowrap;
            flex: none;
        }
        &:last-child {
            border-bottom: none;
        }
    }
    &__input {
        color: #333;
        border: none;
        font: .15rem/.23rem Arial, Helvetica, sans-serif;
        height: 25px;
        outline: none;
        &:disabled {
            border: none;
            background-color: transparent;
            opacity: 1;
        }
        &::placeholder {
            color: #858585;
        }
    }
    &__select {
        box-sizing: border-box;
        width: 100%;
        vertical-align: middle;
        &__text {
            text-align: right;
            box-sizing: border-box;
        }
    }
    &__tags {
        display: flex;
        flex-wrap: wrap;
        margin-left: -.04rem;
        margin-right: -.04rem;
        &__item {
            margin: 0 .04rem;
            &__inner {
                padding: 0 .05rem;
                font-size: .13rem;
            }
        }
    }
    &__input__placeholder {
        color: #858585;
    }
}
.z-info {
    font-size: .15rem;
    line-height: 23px;
    padding: .11rem 0 .02rem;
    .tit {
        flex: none;
        width: auto;
        white-space: nowrap;
    }
    .cic {
        text-align: right;
        .z-input {
            width: 100%;
            height: 23px;
            font: 13px/23px Arial, Helvetica, sans-serif;
            text-align: right;
            outline: none;
            &-placeholder,
            &::placeholder {
                color: #858585;
            }
        }
    }
}
// 去掉chrome表单自动填充样式
input:-webkit-autofill, 
textarea:-webkit-autofill, 
select:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px white inset; 
}
input[type=text]:focus,
input[type=password]:focus,
textarea:focus {
    -webkit-box-shadow: 0 0 0 1000px white inset;
}
</style>
