<!--
@name 业务组件：单选、多选列表信息选择
@desc 基于 vant-ui
【必填入参】：
    @param {Array} [dataList]   - 选择数据，必填，默认：[]
            @example: [{locacode:"",locaname:"",stoargecode:"",stoargename:""}...]
    @param {String} [listId]   - 关键字，唯一性，必填，默认：""
    @param {String} [keyword]   - 显示搜索结果，必填，默认：""

【选填入参】： 
    @param {Array} [selectedModel] - 当前选中的列表(选填)，如果数据不可以重复，就导入此项数据
            @example: [{locacode:"",locaname:"",stoargecode:"",stoargename:""}] 
    @param {Boolead} [multi]   - 是否开启多选，默认：false
    @param {Boolead} [finished]   - 是否加载完，默认：false
    @param {Boolead} [confirmLoading]   - 确认按键加载状态，默认：false
    @param {String} [errorTips]   - 添加选项时的错误提示，默认：已添加，无法重复选择
    

【回调出参】：
    @function {out} confirm(Array) - 确认事件
            返回数据: [{locacode:"",locaname:"",stoargecode:"",stoargename:""}...]
    @function {out} load() - 加载更多
    @function {out} popupItem(data) - 弹出详情信息
    @function {out} closed() - 关闭回调

【父组件控制方法】：
    @function {in} open()- 开启组件  -- this.$refs.modle.open();
    @function {in} close() - 关闭组件  -- this.$refs.modle.close();

【插槽】
    @slot [listitem]  列表模块
        @param {Number} index -  当前item的索引
        @param {Object} item  -  当前item
        @function handleSelItem - 点击当前item回调事件
        @function handleShowDetail - 展示当前item详情回调事件

        @example 调用实例
            <template slot="listitem" slot-scope="data"><div @click="data.handleSelItem(data.index)">{{data.item}}</div></template>

@example 调用示例
    <barcode-widget :dataList="barcode"></barcode-widget>
@time 2020年7月17日 -- design by Yj_cHen
-->

<template>
    <van-popup
        v-model="showPopup"
        :style="{ width: '90%', height: '80%' }"
        get-container="body"
        class="lj-sel-order-popup"
        @closed="handleCloseWidget"
    >
        <div class="popup-main">
            <header class="header">
                <div class="header-inner">
                    <div class="keyword">
                        {{ `搜索"${keyword.toString().trim()}` }}
                    </div>
                    <div class="result">
                        {{ `", ${title}(${dataList.length})`}}
                    </div>
                </div>
                <i class="close-btn iconfont icon-close" @click="close"></i>
            </header>
            <main class="main barcode-content">
                <van-list
                    v-model="listLoading"
                    :finished="finished"
                    finished-text="没有更多了"
                    :immediate-check="false"
                    @load="loadmore"
                >
                    <van-swipe-cell
                        v-for="(item, index) in dataList"
                        :key="index"
                        :name="item[listId]"
                        ref="selItemOrder"
                        :class="{'selected': oldSelList.indexOf(item[listId]) > -1}"
                        :before-close="handleBeforeCloseSwipe"
                        @close="handleCloseSwipe"
                        @open="handleOpenSWipe"
                        
                    >
                        <template slot="left">
                            <div class="select-status" @click="handleSelItem(index, item)">
                                <div class="inner">
                                    <svg class="icon svg-icon" aria-hidden="true">
                                        <use xlink:href="#icon-zhengque1"></use>
                                    </svg>
                                    已选
                                </div>
                            </div>
                        </template>
                        <slot name="listitem" :item="item" :index="index" :handleSelItem="handleSelItem" :handleShowDetail="handleShowDetail">
                            <van-cell
                                class="barcode-item"
                                title-class="barcode-item-title"
                                label-class="barcode-item-subtitle"
                                value-class="barcode-item-value"
                                @click="handleSelItem(index, item)"
                            >
                                <template slot="title">
                                    <span class="title" @click.stop="handleShowDetail(item)">
                                        {{ item.barcode }}
                                    </span>
                                </template>
                                <template slot="label">
                                    <span style="padding-right: 10px">
                                        {{ item.mtrlmode }}
                                    </span>
                                    <span>
                                        基数:{{ item.packqty }}
                                    </span>
                                </template>
                                <template slot="default">
                                    <div class="item-default">
                                        <div class="item-code">
                                            {{ item.mtrlcode }}
                                        </div>
                                        <div class="item-name">
                                            {{ item.mtrlname }}
                                        </div>
                                    </div>
                                </template>
                            </van-cell>
                        </slot>
                    </van-swipe-cell>
                </van-list>
            </main>
            <footer class="footer">
                <div class="footer-selall" v-if="multi">
                    <van-checkbox ref="checkboxAll" v-model="checkboxAll" checked-color="#07c160" @click="handleSelAll">当前全选</van-checkbox>
                </div>
                <div class="footer-controller">
                    <van-button
                        class="footer-btn"
                        mini round type="info"
                        :disabled="!selectList.length || confirmLoading"
                        :loading="confirmLoading"
                        @click="handleConfirm"
                    >
                        确定
                        <template v-if="selectList.length">
                            {{ `(${selectList.length})`}}
                        </template>
                    </van-button>
                </div>
            </footer>
            <div class="popup-loading" v-if="showLoading">
                <van-loading type="spinner" color="#1989fa" />
            </div>
        </div>
    </van-popup>
</template>

<script>
export default {
    name: "ljSelOrder",
    data() {
        return {
            showPopup: false,
            showLoading: false,
            listLoading: false,
            // btnLoading: false,
            isSelAll: false, // 是否全选
            checkboxAll: false, // checkbox
            selectList: [], // 待确定订单
            oldSelList: [], // 历史已选
            title: "查询结果"
        }
    },
    props: {
        keyword: {
            type: String,
            default: ""
        },
        dataList: {
            type: Array,
            default: function() {
                return []
            }
        },
        listId: {
            type: String,
            required: true,
            default: ""
        },
        multi: {
            type: Boolean,
            default: false
        },
        selectedModel: {
            type: Array,
            default: function() {
                return []
            }
        },
        finished: {
            type: Boolean,
            default: false
        },
        confirmLoading: {
            type: Boolean,
            default: false
        },
        errorTips: {
            type: String,
            default: "已添加，\n无法重复选择"
        }
    },
    watch: {
        selectList(newVal) {
            // if (this.multi) {
                let self = this;
                this.$nextTick(function () {
                    if(self.multi) {
                        self.isSelAll = newVal.length == (self.dataList.length - self.oldSelList.length);
                        self.$refs.checkboxAll.toggle(self.isSelAll);
                    }
                    
                    self.showLoading = false;
                })
            // }
        },
        dataList(newVal) {
            console.log("dataList数据变化=》newVal", JSON.stringify(newVal));
            // if (this.multi) {
                let self = this;
                this.$nextTick(function () {
                    if(self.multi) {
                        self.isSelAll = self.selectList.length == (newVal.length - self.oldSelList.length);
                        self.$refs.checkboxAll.toggle(self.isSelAll);
                    }
                    self._autoPretreatment();
                    
                    self.listLoading = false;
                })
            // }
        }
    },
    methods: {
        /**展示详情信息 */
        handleShowDetail(item) {
            this.$emit("popupItem", item)
        },
        /**加载更多数据 */
        loadmore() {
            this.$emit("load");
        },
        /**关闭加载 */
        loadingOff() {
            // this.btnLoading = false;
        },
        /**关闭组件 */
        handleCloseWidget() {
            this.$emit("closed")
        },
        /**确定选择 */
        handleConfirm() {
            if (!this.selectList.length) {
                $lj.toast("请点击或右滑选择列表数据");
                return false;
            } else {
                this.$emit("confirm", this.selectList);
            }
            // this.showPopup = false;
        },
        handleBeforeCloseSwipe({name, position, instance}) {
            // 虽然是空，但是不能删除，作用类似与重置该事件差不多
        },
        /**关闭swipe时回调 */
        handleCloseSwipe({position, name}) {
            console.log("handleCloseSwipe position==》", name);
            if (!this.selectList.length) return false;
            for (let i = 0; i < this.selectList.length; i++) {
                if (name == this.selectList[i][this.listId]) {
                    this.selectList.splice(i, 1);
                    break;                                                                                                                                                                    
                }
            }
        },
        /**全选按钮事件 */
        handleSelAll() {
            console.log("点击全部事件", this.isSelAll);
            if (this.oldSelList.length >= this.dataList.length) {
                $lj.toast(`数据已添加，无法重复选择`);
                this.$refs.checkboxAll.toggle(this.isSelAll);
                return false;
            }
            let length = this.$refs.selItemOrder.length;
            
            this.showLoading = true;
            setTimeout(() => {
            console.time("点击全选测试时间==》");
                // 是否已经全选
                if (this.isSelAll) {
                    for (let i = 0; i < length; i++) {
                        this.$refs.selItemOrder[i].opened && this.$refs.selItemOrder[i].close();
                    }
                    this.selectList = [];
                } else {
                    for (let i = 0; i < length; i++) {
                        !this.$refs.selItemOrder[i].opened && this.$refs.selItemOrder[i].open("left");
                    }
                    // this.selectList = JSON.parse(JSON.stringify(this.dataList));
                }
            console.timeEnd("点击全选测试时间==》");
            }, 1);
        },
        /**打开swipe时回调 */
        handleOpenSWipe(item) {
            // console.log("拖拽事件", item);
            if (this.oldSelList.length) {
                if (this.oldSelList.indexOf(item.name) > -1) {
                    $lj.toast(`单号:${item.name.trim() + this.errorTips}`);
                    let length = this.$refs.selItemOrder.length;
                    for (let i = 0; i < length; i++) {
                        if (item.name == this.$refs.selItemOrder[i].name) {
                            this.$refs.selItemOrder[i].close();
                            break;
                        }
                    }
                    return false;
                }
            }

            if (!this.multi) {
                // 单选-清空已选
                let sellength = this.selectList.length;
                if (sellength) {
                    for (let j = 0; j < sellength; j++) {
                        let length = this.$refs.selItemOrder.length;
                        if (this.selectList[j][this.listId] != item.name) {
                            for (let i = 0; i < length; i++) {
                                if (this.selectList[j][this.listId] == this.$refs.selItemOrder[i].name) {
                                    this.$refs.selItemOrder[i].close();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            // 查重，然后添加入待选择列表
            let checkVal = _fnHasVal(this.selectList, this.listId, item.name);
            if (!checkVal) {
                let length = this.dataList.length
                for (let i = 0; i < length; i++) {
                    if (item.name == this.dataList[i][this.listId]) {
                        this.selectList.push(this.dataList[i]);
                        break;
                    }
                }
            }
            // console.log("多选结果：==》", this.selectList);

            // 内部方法-查重
            function _fnHasVal(aList, targetValue, val) {
                let hasVal = false;
                for (let i = 0; i < aList.length; i++) {
                    if (aList[i][targetValue] == val) {
                        hasVal = true;
                        break;
                    }
                }
                return hasVal;
            }
        },
        /**点击条码——相当于右滑选择 */
        handleSelItem(idx, item) {
            console.log("点击事件", idx);
            
            if (this.oldSelList.length) {
                if (this.oldSelList.indexOf(item[this.listId]) > -1) {
                    $lj.toast(`单号:${item[this.listId].trim() + this.errorTips}`);
                    return false;
                }
            }
            
            if (this.multi) {
                // 多选
                if (this.$refs.selItemOrder[idx].hasOwnProperty("opened") && this.$refs.selItemOrder[idx].opened) {
                    this.$refs.selItemOrder[idx].close();
                } else {
                    this.$refs.selItemOrder[idx].open("left");
                }
            } else {
                // // 单选
                this.$refs.selItemOrder[idx].open("left");
            }
            console.log("已选列表：", this.selectList);
        },
        /**显示组件，并赋值 */
        open() {
            this.showPopup = true;
            // this.btnLoading = false;
            this._autoPretreatment();
        },
        close() {
            this.showPopup = false;
        },
        _autoPretreatment () {  
            if (!this.selectedModel.length) return false;
            
            this.oldSelList = [];
            let length = this.selectedModel.length;
            let dataL = this.dataList.length;
            let dataMini = [];
            for (let i = 0; i < dataL; i++) {
                dataMini.push(this.dataList[i][this.listId])
            }
            for (let i = 0; i < length; i++) {
                if (dataMini.indexOf(this.selectedModel[i][this.listId]) > -1) {
                    this.oldSelList.push(this.selectedModel[i][this.listId]);
                }
            }
            console.log("this.oldSelList==>", this.oldSelList);
        }
    }
}
</script>

<style lang="less">
@import "../../../assets/css/lj-style-variable";
@import "../../../assets/css/lj-base";
@import "../../../assets/css/lj-pda";

.lj-sel-order-popup {
    .shadow_border();

    .van-popup__close-icon--top-right {
        top: 10px;
    }
    
    .popup-main {
        position: relative;
        display: flex;
        flex-direction: column;
        height: 100%;

        .popup-loading {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255,255,255,0.6);
            .middle_center();
            z-index: 100;
        }
    }
    .header {
        .middle_center();
        position: relative;
        text-align: center;
        font-size: 16px;
        height: 48px;
        line-height: 48px;
        border-bottom: 1px solid #f1f1f1;
        
        .header-inner {
            display: flex;
            max-width: 90%;
            .keyword {
                flex: 1;
                .word_one_line();
                text-align: right;
            }
            .result {
                text-align: left;
                flex-shrink: 0;
            }
        }
        .close-btn {
            position: absolute;
            right: 15px;
            top: 0;
            bottom: 0;
            margin: auto;
        }
    }
    .main {
        flex: 1;
        overflow: auto;

        /**条码样式 */
        &.barcode-content {
            .van-cell {
                padding: 3px 5px;
            }
            .barcode-item-title {
                text-align: left;
                .title {
                    font-weight: bold;
                }
            }
            
            .barcode-item {
                position: relative;
                border-bottom: 1px solid @detailAreaTitleDividerColor;
            }
            
            .selected {
                .van-cell {
                    background-color: @summaryAreaBackgroundColor;
                    color: @summaryLightTextColor;
                }
            }

            .select-status {
                .middle_center();
                height: 100%;
                padding: 0 10px;
                background-color: @colorNormalThr;
                .inner {
                    vertical-align: middle;
                    display: flex;
                    align-items: center;
                    color: @colorNormal;
                }
                svg {
                    margin-right: 5px;
                    width: 26px;
                    height: 26px;
                }
            }
        }
    }
    .footer {
        display: flex;
        border-top: 1px solid #f1f1f1;
        height: 48px;
        // line-height: 48px;
        padding: 5px 15px;

        .footer-selall {
            flex-shrink: 0;
            margin: auto 15px;
            margin-left: 0;
        }
        .footer-controller {    
            flex: 1;
            height: 100%;

            .footer-btn {
                width: 100%;
                height: 100%;
                line-height: unset;
            }
        }
    }
}
</style>