define(['jquery', 'vue'], function ($, Vue) {
    return Vue.component('popup-multi', {
        template: '<span>\
                       <template v-if="!buttonMode">\
                           <div class="popup_common_box">\
                                <p class="content">\
                                    <span v-for="(item,index) in innerText">{{item}}</span>\
                                </p>\
                                <van-button type="primary" size="small" @click="popup">{{buttonText}}</van-button>\
                            </div>\
                       </template>\
                       <van-button type="primary" size="small" v-else @click="popup">{{buttonText}}</van-button>\
                        <!--多选列表-->\
                         <van-popup position="bottom" class="select_popup full_screen" v-model="showPopup">\
                            <!-- 标题-->\
                            <van-sticky>\
                                <van-nav-bar :title="popupTitle" left-text="返回" left-arrow right-text="清除"\
                                             @click-left="showPopup = false"\
                                             @click-right="clearData"></van-nav-bar>\
                                <van-button plain hairline block style="font-size: 18px;" @click="showSearchPopup = true">\
                                    <van-icon name="search" color="#3498db"/>\
                                    搜索\
                                </van-button>\
                            </van-sticky>\
                            <van-empty description="暂无数据" v-if="dataList && dataList.length == 0"></van-empty>\
                            <van-checkbox-group v-model="selectedKey">\
                            <van-list\
                                    v-model="loading"\
                                    :finished="finished"\
                                    finished-text="没有更多了"\
                                    @load="bindData"\
                            >\
                                <div class="chose_item" v-for="item in dataList" :key="item.id">\
                                    <van-checkbox shape="square" :name="item.id"\
                                                  @click="toggleSelected(item)"></van-checkbox>\
                                    <div class="chose_item_info">\
                                        <p><i>组织：</i>{{item.organization}}</p>\
                                        <p><i>名称：</i>{{item.name}}</p>\
                                    </div>\
                                </div>\
                            </van-list>\
                            </van-checkbox-group>\
                            <div class="footer">\
                                <van-button @click="showSelectedPopup = true">已选列表( {{selectedNum}} )</van-button>\
                                <van-button type="primary" @click="confirm">确定</van-button>\
                            </div>\
                        </van-popup>\
                        <!--筛选-->\
                        <van-popup position="bottom" round v-model="showSearchPopup" class="search_popup"\
                                   :style="{minHeight: \'30%\'}">\
                            <p class="title">\
                                <van-icon name="arrow-down" @click="showSearchPopup = false"></van-icon>\
                                筛选\
                            </p>\
                            <van-cell-group>\
                                <van-field v-model="criteria.text" label="文本" placeholder="请填写内容"></van-field>\
                            </van-cell-group>\
                            <div class="search_footer_container">\
                                <van-button plain hairline @click="reset">\
                                    重置\
                                </van-button>\
                                <van-button type="primary" @click="search">\
                                    确定\
                                </van-button>\
                            </div>\
                        </van-popup>\
                        <!--已选列表-->\
                        <van-popup position="bottom" round v-model="showSelectedPopup" class="selected_popup"\
                                   :style="{height: \'50%\'}">\
                            <p class="title">已选人员\
                                <van-icon name="cross" @click="showSelectedPopup = false"></van-icon>\
                            </p>\
                            <div class="selected_list">\
                                <div class="selected_item" v-for="(item, index) in selected">\
                                    <p>{{item.name}}</p>\
                                    <van-button type="danger" size="mini" class="remove_btn" @click="removeSelected(item,index)">删除</van-button>\
                                </div>\
                            </div>\
                        </van-popup>\
                    </span>',
        props: {
            buttonMode: {type: Boolean, default: false}, // 按钮模式 false
            buttonText: {default: '选择'}, // 按钮文字
            popupTitle: {default: '选择'}, // 弹框标题
            disabled: {default: false},
            beforePopup: {type: Function, default: undefined}, //弹出前事件
            afterPopup: {type: Function, default: undefined}, //关闭选择页面前事件
            pageParams: { // 传递给弹窗页面的参数
                default: function () {
                    return {}
                }
            },
            value: {default: undefined}, // 选中项key值
            list: {default: undefined},  // 选中项集合
        },
        data: function () {
            return {
                showPopup: false, // 多选弹框
                showSearchPopup: false, // 多选弹框查询条件
                showSelectedPopup: false, // 多选弹框已选列表
                selectedNum: 0, // 已选数量
                innerText: [],
                selectedKey: this.value, //
                selected: [], // 已选列表
                innerPageParams: this.pageParams,
                id: Math.random().toString(36).substr(2),
                pageSize: 10,
                pageNum: 0,
                loading: false,
                finished: false,
                total: undefined, // 列表总数
                dataList: [],
                criteria: {}, // 查询条件
            }
        },
        watch: {
            value: function (newVal, oldVal) { // 数组/undefined
                this.updateSelected(newVal)
            },
            list: function (newVal, oldVal) {
                var type = Object.prototype.toString.call(newVal)
                if (type == "[object Object]" || type == "[object Array]") {
                    this.selected = JSON.parse(JSON.stringify(newVal));
                } else {
                    this.selected = []
                }
            },
            selected: function (newVal, oldVal) {
                this.selectedKey = this.getValue()
                this.selectedNum = this.selectedKey.length
            },
            pageParams: {
                handler: function (newVal, oldVal) {
                    if (Object.prototype.toString.call(newVal) == "[object Object]") {
                        this.criteria = JSON.parse(JSON.stringify(newVal))
                    } else {
                        this.criteria = {}
                    }
                    this.bindData()
                },
                deep: true
            }
        },
        computed: {},
        created() {
            if (!$.isArray(this.selectedKey)) {
                this.selected = []
                this.selectedKey = []
            }
            this.fetchSelected()
        },
        mounted() {
            this.bindData()
        },
        methods: {
            popup() {
                if (this.disabled)
                    return;

                if (this.beforePopup != undefined) {
                    if (!this.beforePopup())
                        return;
                }

                this.showPopup = true
            },
            // 更新选中项 （场景：value变化，关闭弹框）
            updateSelected: function (val) {
                if (val && $.isArray(val) && val.length > 0) {
                    var selectedKey = this.getValue()
                    var flag = this.compareArray(val, selectedKey)
                    if (!flag) {
                        this.selectedKey = val
                        this.fetchSelected()
                    }
                } else {
                    this.selectedKey = []
                    this.selected = []
                    this.innerText = this.getText()
                    this.$emit('update:list', this.getList())
                }
            },
            // 查询选择的对象
            fetchSelected() {
                var that = this;
                $.ajax({
                    contentType: "application/json",
                    url: "./json/list.json",
                    success: function (res) {
                        that.selected = res.data.data;
                        that.innerText = that.getText()
                        that.$emit('update:list', that.getList())
                    }
                });
            },
            // 列表
            bindData() {
                var that = this;
                if (that.finished) {
                    return
                }
                $.ajax({
                    type: "GET",
                    url: "./json/list.json",
                    data: {pageNum: this.pageNum},
                    success: function (res) {
                        if (res.data) {
                            that.pageNum++
                            if ($.isArray(res.data.data)) {
                                res.data.data.forEach((item, index) => {
                                    item.id = (that.pageNum * 10 + index) + ''
                                })
                                that.dataList.push(...res.data.data)
                            }
                            that.total = res.data.total
                        }
                        that.loading = false;
                        if (that.dataList.length >= that.total) {
                            // 测试
                            //if (that.dataList.length >= 40) {
                            that.finished = true;
                        }
                    },
                    error: function () {
                        that.loading = false;
                        that.finished = true;
                    }
                });
            },
            toggleSelected(item) {
                var i = $.inArray(item.id, this.getValue());
                if (i >= 0)
                    this.selected.splice(i, 1);
                else
                    this.selected.push(item);
            },
            removeSelected(item, index) {
                this.selected.splice(index, 1)
            },
            clearData: function () {
                this.innerText = '';
                this.selectedKey = [];
                this.selected = [];
            },
            confirm() {
                if (this.afterPopup != undefined) {
                    if (!this.afterPopup(this.selectedKey))
                        return;
                }
                this.innerText = this.getText()
                this.$emit("update:value", this.selectedKey);
                this.$emit("update:list", this.getList());
                this.$emit('popup-change', this.selectedKey, this.selected);
                this.showPopup = false
            },
            getText() {
                return $.map(this.selected, function (item) {
                    return item.name
                });
            },
            getValue() {
                return $.map(this.selected, function (item) {
                    return item.id
                })
            },
            getList() {
                return this.selected
            },
            search() {
                this.pageNum = 0
                this.finish = false;
                this.showSearchPopup = false;
                this.bindData();
            },
            reset() {
                if (Object.prototype.toString.call(this.pageParams) == "[object Object]") {
                    this.criteria = JSON.parse(JSON.stringify(this.pageParams))
                } else {
                    this.criteria = {}
                }
                this.pageNum = 0
                this.finish = false;
                this.showSearchPopup = false;
                this.bindData()
            },
            // 比较数组是否相同
            compareArray(arr1, arr2) {
                var flag = true;
                if (arr1.length == arr2.length) {
                    for (var i = 0; i < arr1.length; i++) {
                        var index = arr2.indexOf(arr1[i].toString())
                        if (index == -1) {
                            flag = false;
                            break;
                        }
                    }
                } else {
                    flag = false;
                }
                return flag
            },
        }
    })
})
