<template>
    <view
        class="invoice"
        :style="{zIndex: zIndex}"
    >
        <c-popup
            show-title-line
            show-close
            :show-close-handler="false"
            :title="title"
            :max-height="maxHeight"
            :height="height"
            :show="show"
            :z-index="zIndex"
            :row-tile="rowTile"
            :visibility-only-mask="visibilityOnlyMask"
            :btns="cInvoiceData.button"
            :btn-close="false"
            @onSubmit="onSubmit"
            @close="onClose"
        >
            <view class="invoice__tips c-font-normal c-color-gray">{{ cInvoiceData.desc }}</view>
            <view v-if="list && list.length" class="invoice__list">
                <view
                    v-for="(item, index) in list"
                    :key="index"
                    :class="['invoice__item', 'invoice__item-' + item.name]"
                >
                    <view 
                        v-if="item.title || item.text || (item.tags && item.tags.length)"
                        class="invoice__item__header"
                    >
                        <view v-if="item.title" class="invoice__item__header__title c-font-15 c-font-wb c-color-title">{{ item.title }}</view>
                        <!-- 普通文本 -->
                        <view
                            v-if="item.text"
                            class="invoice__item__header__text c-font-15 c-color-gray"
                            :style="{color: item.color}"
                        >
                            {{ item.text }}
                        </view>
                        <!-- tags -->
                        <view v-if="item.tags && item.tags.length" class="c-font-normal c-color-gray">
                            <view class="invoice__item__header__tags-box">
                                <view 
                                    v-for="(tagsItem, tagsIndex) in item.tags"
                                    :key="tagsIndex"
                                    :class="{
                                        'invoice__item__header__tags': true, 
                                        'act': tagsIndex === item.selectedIndex,
                                    }"
                                    @tap="onToggle('tags', item, index, tagsIndex)"
                                >
                                    {{ tagsItem.text }}
                                </view>
                            </view>
                        </view>
                    </view>
                    
                    <view class="invoice__item__cont">
                        <!-- tags -->
                        <template v-if="item.tags && item.selectedIndex <= item.tags.length - 1 && item.tags[item.selectedIndex].cont">
                            <view class="invoice__item__cont__tag">
                                <!-- 默认显示项 -->
                                <view
                                    v-for="iptItem in item.tags[item.selectedIndex].cont"
                                    :key="iptItem.name"
                                >
                                    <invoice-input
                                        :input="iptItem"
                                        :value="formParams[iptItem.name] || ''"
                                        @onFormInput="onFormInput"
                                    />
                                </view>
                                <!-- 展开收起项 -->
                                <view v-if="item.tags[item.selectedIndex].optional && item.tags[item.selectedIndex].optional.cont" class="invoice__item__cont__optional">
                                    <view class="invoice__item__cont__optional__header">
                                        <view class="invoice__item__cont__optional__title c-font-normal">{{ item.tags[item.selectedIndex].optional.title }}</view>
                                        <view 
                                            class="invoice__item__cont__optional__desc c-font-normal c-color-title c-line-clamp1"
                                            :style="{color: formParams.optionalDesc ? '#1F1F1F' : '#858585'}"
                                        >{{ formParams.optionalDesc || item.desc }}</view>
                                        <view class="invoice__item__cont__optional__opearte c-font-normal c-color-gray" @tap="onToggle('speart', item, index, item.isSpread)">
                                            {{ item.isSpread ? '收起' : '展开' }}
                                            <c-icon :name="item.isSpread ? 'up' : 'down'"/>
                                        </view>
                                    </view>
                                    <view v-show="item.isSpread">
                                        <view
                                            v-for="iptItem in item.tags[item.selectedIndex].optional.cont"
                                            :key="iptItem.name"
                                        >
                                            <invoice-input
                                                :input="iptItem"
                                                :value="formParams[iptItem.name] || ''"
                                                @onFormInput="onFormInput"
                                            />
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </template>
                        <!-- 普通输入框 -->
                        <template v-else-if="item.cont && item.cont.length">
                            <!-- 默认显示项 -->
                            <view
                                v-for="iptItem in item.cont"
                                :key="iptItem.name"
                            >
                                <invoice-input
                                    v-if="iptItem"
                                    :input="iptItem"
                                    :value="formParams[iptItem.name] || ''"
                                    :margin-left="inputMarginLeft"
                                    @onFormInput="onFormInput"
                                    @onFormInputFocus="onFormInputFocus"
                                />
                            </view>
                        </template>
                        <!-- 文本域 -->
                        <template v-else-if="item.type === 'textarea'">
                            <textarea
                                class="textarea-inner c-font-normal"
                                :value="formParams[item.name] || ''"
                                :maxlength="100"
                                cursor="-1"
                                :placeholder="item.placehoder"
                                placeholder-class="textarea-ph" 
                                selection-start="-1"
                                selection-end="-1"
                                :fixed="true"
                                :adjust-position="true"
                                @input="onTextareaChange($event, item)"
                            ></textarea>
                        </template>
                    </view>
                </view>
            </view>

            <view 
                v-if="cInvoiceData.attention"
                class="invoice__attention c-gap-top c-color-gray c-font-normal c-gap-bottom-small"
            >
                <text class="c-color-mall">*</text>
                <text>{{ cInvoiceData.attention }}</text>
            </view>
            <!-- 占位 -->
            <view style="height: 20px"/>
        </c-popup>
    </view>
</template>

<script>
 /**
 * @author mayifan02
 * @file 核酸发票popup
 * @categories 组件
 * @tags [component]
 */
import CPopup from '@baidu/med-ui/components/Popup/Popup';
import {getSystemInfo} from '@baidu/med-utils/lib/Mars/system';
import InvoiceInput from './InvoiceInput';
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import {isValidEmail} from '@utils/validate';
import {filterEmptyObj} from '@utils/core';
import {request} from '@utils/request';
import * as conf from '@utils/conf';
// import CTagItem from '@baidu/med-ui/components/Tags/TagItem';
export default {
    config: {
        component: true
    },
    components: {
        CPopup,
        InvoiceInput,
        CIcon
        // CTagItem
    },
    props: {
        /** zIndex */
        zIndex: {
            'type': String,
            'default': '921'
        },
        /** invoiceData */
        invoiceData: {
            type: Object,
            default: () => {
                return {};
            }
        },
        /** show  */
        show: {
            type: Boolean,
            default: false
        },
        /** 是否不要内边距 */
        rowTile: {
            'type': Boolean,
            'default': false
        },
        /* visibility 是否只生效于 mask 上（在内容区 slot 上如果有输入框等容易在不同机型上出问题的控件，需要保持 content 一直显示）*/
        visibilityOnlyMask: {
            'type': Boolean,
            'default': true
        },
        /** 标题 */
        title: {
            type: String,
            default: '开具发票'
        },
        /** height */
        height: {
            type: String,
            default: '90%'
        },
        /** maxHeight */
        maxHeight: {
            type: String,
            default: '90%'
        },
        /** inputMarginLeft */
        inputMarginLeft: {
            type: String,
            default: '13px'
        }
    },
    data() {
        return {
            cInvoiceData: {},
            isIphoneX: false,
            isCheck: true,
            list: [],
            formParams: {}
        };
    },
    watch: {
        show(n, o) {
            if (n) {
                this.getFormValue(this.list);
            }
        },
        invoiceData(n, o) {
            if (n) {
                this.initInvoiceData();
            }
        }
    },
    created(){
        this.initInvoiceData();
        const systemInfo = getSystemInfo();
        if (systemInfo.model.search('iPhone X') !== -1 || systemInfo.model.search('iPhone 11') !== -1) {
            this.isIphoneX = true;
        }
    },
    methods: {
        // copy发票数据
        initInvoiceData() {
            this.cInvoiceData = this.invoiceData;
            this.cInvoiceData.button = [this.cInvoiceData.button];
            this.list = this.cInvoiceData.list;
            // 获取参数默认值
            this.getFormValue(this.list);
        },
        onClose() {
            /** onInvoicePopupClose */
            this.$emit('onInvoicePopupClose');
        },
        onToggle(type, invoiceItem, itemIndex, selectValue) {
            let item = {};
            if (type === 'tags') {
                item = Object.assign({}, invoiceItem, {
                    selectedIndex: selectValue
                });
                this.getFormValue(this.list, selectValue);
            } else if (type === 'speart') {
                // 取出选填项的内容
                const {optional} = invoiceItem.tags && invoiceItem.tags.find(item => {
                    if (item.optional) {
                        return true;
                    } 
                });
                // 输入的内容回填
                let desc = '';
                optional && optional.cont.forEach((item, index) => {
                    const value = this.formParams[item.name];
                    if (value) {
                        desc += `${index === 0 ? '' : ' '}${value}`;
                    }
                });
                this.$set(this.formParams, 'optionalDesc', desc);
                item = Object.assign({}, invoiceItem, {
                    isSpread: !selectValue
                });
            }

            this.$set(this.list, itemIndex, item);
        },
        // 去空格
        trim(str) {
            if (typeof (str) === 'string') {
                return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            }
            return str;
        },
        // 文本框输入
        onFormInput(name, value) {
            this.$set(this.formParams, name, this.trim(value));
        },
        // 获得焦点
        onFormInputFocus(name, value) {
            // 手机号特殊处理
            if (name === 'receive_mobile' && value.indexOf('*') !== -1) {
                this.$set(this.formParams, name, '');
            }
        },
        // 文本域
        onTextareaChange(e, inputItem) {
            const value = e.detail.value;
            if (value && value.length > 100) {
                this.$api.showToast({
                    title: '最多输入100个字',
                    icon: 'none'
                });
            }
            this.formParams[inputItem.name] = value;
        },
        // 按钮提交
        onSubmit({btn, btnIndex}) {
            const params = {};
            this.isCheck = true;
            // 必填项校验
            this.list.every((invoiceItem, index) => {
                // tags标签项
                if (invoiceItem.tags) {
                    const curTags = invoiceItem.tags[invoiceItem.selectedIndex];
                    params[invoiceItem.name] = curTags.value;
                    // 当前选中标签项的内容
                    curTags.cont && curTags.cont.every(item => {
                        item.required && this.validateData(item.name, this.formParams[item.name], item.text);
                        params[item.name] = this.formParams[item.name];
                        return this.isCheck;
                    });
                    // 当前标签的选填项
                    curTags.optional && curTags.optional && curTags.optional.cont.forEach(item => {
                        params[item.name] = this.formParams[item.name];
                    });
                // 普通input
                } else if (invoiceItem.cont) {
                    const cont = invoiceItem.cont;
                    cont.every(item => {
                        item.required && this.validateData(item.name, this.formParams[item.name], item.text);
                        params[item.name] = this.formParams[item.name];
                        return this.isCheck;
                    });
                // 文本域
                } else if (invoiceItem.type === 'textarea') {
                    params[invoiceItem.name] = this.formParams[invoiceItem.name];
                }
                return this.isCheck;
            });
            if (this.isCheck) {
                // 提交信息
                this.submitInvoiceInfo(btn.async, params);
            }
        },
        // 获取表单默认值
        getFormValue(formList, tagSelectIndex) {
            formList.forEach(invoiceItem => {
                // tags标签项
                if (invoiceItem.tags) {
                    const selectedIndex = typeof tagSelectIndex === 'number' ? tagSelectIndex : invoiceItem.selectedIndex;
                    const curTags = invoiceItem.tags[selectedIndex];
                    this.$set(this.formParams, invoiceItem.name, curTags.text);
                    // 当前选中标签项的内容
                    curTags.cont && curTags.cont.forEach(item => {
                        this.$set(this.formParams, item.name, item.value);
                    });
                    // 当前标签的选填项
                    let desc = '';
                    curTags.optional && curTags.optional && curTags.optional.cont.forEach((item, index) => {
                        if (item.value) {
                            desc += `${index === 0 ? '' : ' '}${item.value}`;
                            this.$set(this.formParams, item.name, item.value);
                        }
                    });
                    this.$set(this.formParams, 'optionalDesc', desc);
                // 普通input
                } else if (invoiceItem.cont) {
                    const cont = invoiceItem.cont;
                    cont.forEach(item => {
                        this.$set(this.formParams, item.name, item.value);
                    });
                // 文本域
                } else if (invoiceItem.type === 'textarea') {
                    this.$set(this.formParams, invoiceItem.name, invoiceItem.value);
                }
            });
        },
        submitInvoiceInfo(api, params) {
            request({
                url: conf.apiHost + api,
                method: 'POST',
                data: filterEmptyObj(params),
                isNeedLogin: true,
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                }
            })
                .then(res => {
                    const {toast} = res.data;
                    if (toast) {
                        this.$api.showToast({
                            title: toast,
                            icon: 'none'
                        });
                    }
                    /** onSubmitSuccess */
                    this.$emit('onSubmitSuccess', res);
                })
                .catch(() => {
                });
        },
        // 数据校验
        validateData(key, value, tips) {
            // 不为空字段名
            let notNullKey = ['personal_name', 'company_name', 'tax_identification', 'receive_email', 'receive_mobile', 'receive_address', 'recipient', 'recipient_mobile', 'recipient_address'];
            
            if (notNullKey.indexOf(key) !== -1 && !value) {
                this.$api.showModal({
                    title: '',
                    content: '您的发票信息未填写，请填写后提交',
                    showCancel: false
                });
                this.isCheck = false;
            } else if (key === 'receive_email' && !isValidEmail(value)) {
                this.$api.showModal({
                    title: '',
                    content: `${tips}格式错误`,
                    showCancel: false
                });
                this.isCheck = false;
            }
        }
    }
};
</script>
<style lang="less" scoped>
.invoice {
    &__tips {
        padding-top: 6px;
    }
    &__item {
        &__header {
            position: relative;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 45px;
            &__tags {
                &-box {
                    display: flex;
                    .act {
                        background: #DFE9FF;
                        color: #6897FF;
                        font-weight: 500;
                    }
                }
                padding: 0px 21px;
                height: 30px;
                line-height: 30px;
                border-radius: 4px;
                background: #f6f6f6;
                color: #525252;
                margin-left: 8px;
                &:first-child {
                    margin-left: 0;
                }
                
            }
            &::after{
                content: '';
                position: absolute;
                background-color: #e0e0e0;
                display: block;
                width: 100%;
                height: 1px; /*no*/
                transform: scale(1, 0.5);
                bottom: 0;
                left: 0;
            }
        }
        &__title {
            font-weight: bold;
        }
        &__cont {
            &__optional {
                &__header {
                    position: relative;
                    height: 43px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    &::after{
                        content: '';
                        position: absolute;
                        background-color: #e0e0e0;
                        display: block;
                        width: 100%;
                        height: 1px; /*no*/
                        transform: scale(1, 0.5);
                        bottom: 0;
                        left: 0;
                    }
                }
                &__desc {
                    flex: 1;
                    margin-left: 20px;
                    margin-right: 20px;
                }
            }
        }
    }
    &__item-remark {
        .invoice__item__header {
            &::after {
                content: '';
                width: 0;
                height: 0;
            }
        }
    }
    &__attention {
        line-height: 21px;
    }
}
.textarea-inner {
    width: 100%;
    display: block;
    padding: 10px;
    height: 80px;
    border: none;
    resize: none;
    word-wrap: break-word;
    box-sizing: border-box;
    border-radius: 6px;
    font-size: 13px;
    background-color: #fff;
    outline: none;
    line-height: 22px;
    color: #333;
    border: 1px solid #EEEEEE;
}
textarea::-webkit-input-placeholder,
.textarea-inner-placeholder {
    text-align: left;
    color: #999;
    font: 13px/23px Arial, Helvetica, sans-serif;
}
.cancel-border {
    &::after {
        content: '';
    }
}
</style>
