import {
    ApiModel
} from "../../utils/api";
const _Http = new ApiModel();
const handleList = require("../../utils/processingData");
Page({
    /**
     * 页面的初始数据
     */
    data: {
        pageType: 0, //页面类型 0是添加成员 1是成员列表
        inputValue: '', //群名
        buddyList: [], //好友列表
        buddyListCopy: [], //备份
        activeNames: [], //折叠面板展开项
        identity: '全部', //选择身份
        result: [],
        checkAll: false, //是否全选
        numberOfPeople: 0, //全部人员计数
        searchText: '', //搜索内容
        timdialogid: 0, //群聊id
        users: [], //成员列表
        closure: false, //截流
        itemData: {}, //修改群聊原信息
        showRemove: false, //是否开启移除成员
        removeList: [], //清楚列表
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "customer.tagents.tagents",
            "method": "query_cooperation",
            "content": {
                "getdatafromdbanyway": true,
                "pageNumber": 1,
                "pageSize": 999,
                "where": {
                    "condition": "",
                    "ftype": "",
                    "fstatus": ""
                }
            }
        }).then(res => {
            let activeNames = [];
            for (let index = 0; index < res.data.length; index++) {
                this.query_CooperationAgentUsers(res.data[index])
                activeNames.push(index)
            }
            this.setData({
                activeNames
            })
            //修改群聊信息
            if (options.timdialogid) {
                _Http.basic({
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.im.imdialog.imdialog",
                    "method": "query_imdialogMain",
                    "content": {
                        "timdialogid": options.timdialogid
                    }
                }).then(res => {
                    console.log("群聊详情", res)
                    if (res.msg != '成功') return wx.showToast({
                        title: res.data,
                        icon: "none"
                    });
                    let data = res.data[0],
                        result = [];
                    for (let i = 0; i < data.users.length; i++) {
                        result.push(data.users[i].tenterprise_userid.toString())
                    }
                    this.setData({
                        inputValue: data.fimdialogname,
                        timdialogid: options.timdialogid,
                        users: data.users,
                        result,
                        itemData: data,
                        pageType: 1
                    })
                })
            }
        })
    },
    /* 移除成员 */
    removeMember() {
        let list = this.data.removeList,
            that = this,
            _succeed = 0,
            _fail = 0;
        if (list.length == 0) return;
        wx.showModal({
            title: "提示",
            content: "是否移除选中成员",
            success: async function (res) {
                if (res.confirm) {
                    wx.showLoading({
                        title: '移除中...',
                        mask: true
                    })
                    for (let i = 0; i < list.length; i++) {
                        await _Http.basic({
                            "accesstoken": wx.getStorageSync('userData').token,
                            "classname": "system.im.imdialog.imdialog",
                            "method": "updateDialoguser",
                            "content": {
                                "timdialogid": that.data.timdialogid,
                                "tenterprise_userid": list[i],
                                "fisremove": 1,
                                "fimdialognotes": ""
                            }
                        }, false).then(res => {
                            (res.msg == '成功') ? _succeed += 1: _fail += 1;
                        })
                    };
                    wx.hideLoading()
                    wx.showToast({
                        title: '移除成功' + _succeed + '个,失败' + _fail + '个',
                        icon: "none"
                    });
                    that.setData({
                        closure: true
                    })
                    setTimeout(() => {
                        wx.navigateBack({
                            delta: 0,
                        })
                    }, 500)
                }
            }
        })
    },
    /* 移除成员列表更新 */
    removeListChange(event) {
        if (event.detail.length == this.data.users.length - 1) return wx.showToast({
            title: "不可将全部成员移除",
            icon: "none"
        });
        this.setData({
            removeList: event.detail,
        });
    },
    /* 修改群名 */
    changeName(e) {
        if (this.data.users.length == 0) return;
        const {
            value
        } = e.detail,
            that = this;
        if (value == this.data.itemData.fimdialogname) return;
        if (this.data.inputValue != '') {
            wx.showModal({
                title: "提示",
                content: "是否将群聊名称修改为:" + that.data.inputValue,
                success: function (res) {
                    if (res.confirm) {
                        that.createdGroup(true)
                    } else {
                        console.log(that.data.itemData.fimdialogname)
                        that.setData({
                            inputValue: that.data.itemData.fimdialogname
                        })
                    }
                }
            })
        }
    },
    /* 返回 */
    goBack() {
        if (this.data.users.length !== 0) {
            this.setData({
                showRemove: false,
                pageType: 1
            })
        }
    },
    /* 编辑群聊，新增或删除成员 */
    addAndRemove(e) {
        const {
            type
        } = e.target.dataset;
        console.log(type)
        if (type == 'add') {
            this.setData({
                pageType: 0
            })
        } else {
            this.setData({
                showRemove: !this.data.showRemove
            })
        }
    },
    //本地模糊搜索
    indistinct(e) {
        const value = e.detail.value.trim();
        if (value == this.data.searchText) return;
        if (value == '') {
            this.setData({
                buddyList: buddyListCopy
            })
        } else {
            let list = this.data.buddyListCopy,
                newList = [];
            for (let i = 0; i < list.length; i++) {
                if (list[i].fbrand.includes(value)) newList.push(list[i])
            };
            this.setData({
                buddyList: newList
            })
        }
    },
    /* 创建群聊 */
    createdGroup(isChangeUsers = false) {
        /*         if (this.data.users.length == 0) {
                    if (this.data.result.length == 0) return
                } */
        if (this.data.result.length == 0) {
            wx.showToast({
                title: '当前还未选择群聊成员',
                icon: "none"
            })
        } else {
            if (this.data.closure) return;
            _Http.basic({
                "accesstoken": wx.getStorageSync('userData').token,
                "classname": "system.im.imdialog.imdialog",
                "method": "insertOrModify",
                "content": {
                    "timdialogid": this.data.timdialogid,
                    "fimdialogname": (this.data.inputValue == '') ? '讨论组' : this.data.inputValue,
                    "fimdialogtype": "话题",
                    "ownertable": "",
                    "ownerid": "",
                    "users": (isChangeUsers == true) ? [] : this.data.result
                }
            }).then(res => {
                if (res.msg != '成功') return wx.showToast({
                    title: res.data,
                    icon: "none"
                })
                this.setData({
                    closure: true
                })
                wx.showToast({
                    title: '保存成功',
                })
                if (isChangeUsers == true) return;
                setTimeout(() => {
                    if (this.data.users.length == 0) {
                        wx.redirectTo({
                            url: '/pages/chatRoom/dialogbox?id=' + res.data[0].timdialogid,
                        })
                    } else {
                        wx.navigateBack({
                            delta: 0,
                        })
                    }
                }, 500)
            })
        }
    },
    /* 是否全选 */
    allChange({
        detail
    }) {
        this.setData({
            checkAll: detail
        })
        if (detail) {
            let result = [];
            for (let i = 0; i < this.data.buddyList.length; i++) {
                if (this.data.identity == '全部') {
                    this.batchChange(i, true)
                } else {
                    result.push(this.data.buddyList[i].userList[0].tenterprise_userid.toString())
                }
            }
            if (this.data.identity != '全部') this.setData({
                result
            })
        } else {
            this.setData({
                result: []
            })
        }
    },
    /* 商户成员列表 */
    query_CooperationAgentUsers(data) {
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "customer.tagents.tagents",
            "method": "query_CooperationAgentUsers",
            "content": {
                "getdatafromdbanyway": true,
                "tagentsid": data.tcooperationagentsid,
                "hasAdministrator": "1"
            }
        }, false).then(res => {
            console.log("成员列表", res)
            if (res.msg != '成功') return wx.showToast({
                title: res.data,
                icon: "none"
            })
            data.userList = handleList.imageType(res.data, 'headportrait');
            let numberOfPeople = this.data.numberOfPeople += data.userList.length; //计数
            let buddyList = this.data.buddyList;
            buddyList.push(data)
            this.setData({
                buddyList,
                buddyListCopy: buddyList,
                numberOfPeople
            })
        })
    },
    /* 职位选择类型 */
    selectType({
        detail
    }) {
        /* if (detail == '仅老板') {
            let list = this.data.buddyList,
                result = []
            for (let index = 0; index < list.length; index++) {
                result.push(list[index].userList[0].tenterprise_userid.toString())
            }
            this.setData({
                result
            })
        } */
        if (this.data.identity != detail) this.setData({
            identity: detail
        });
        this.isAll()
    },
    /* 编辑群名称 */
    nameInput(e) {
        const {
            value
        } = e.detail;
        this.setData({
            inputValue: value
        })
    },
    /* 折叠面板 */
    collapseChange(event) {
        this.setData({
            activeNames: event.detail,
        });
    },
    //多选选中
    userListCheckboxChange(e) {
        this.setData({
            result: e.detail
        })
        this.isAll();
    },
    /* 商户选中 */
    titleRadio(e) {
        const {
            index,
            id
        } = e.target.dataset;
        this.isAll()
        if (!this.data.result.some((value) => value == id)) return this.batchChange(index, false);
        if (this.data.identity == '全部') this.batchChange(index, true);
    },
    //批量修改
    batchChange(index, bool) {
        let data = this.data.buddyList[index].userList,
            result = this.data.result;
        for (let index = 0; index < data.length; index++) {
            if (bool) {
                if (!result.some((v) => v == data[index])) {
                    result.push(data[index].tenterprise_userid.toString())
                    result = result.reduce((pre, cur) => {
                        if (!pre.includes(cur)) {
                            return pre.concat(cur)
                        } else {
                            return pre
                        }
                    }, [])
                }
            } else {
                result = result.filter((value) => value != data[index].tenterprise_userid);
            }
        }
        this.setData({
            result
        })
        this.isAll();
    },
    /* 选择子账号同时选中主账号 */
    listClick(e) {
        const index = e.currentTarget.dataset.index,
            itemId = e.currentTarget.dataset.id,
            id = e.currentTarget.id;
        if (index == 0) return;
        let result = this.data.result;
        if (!result.some((v) => v == itemId)) return;
        if (!result.some((value) => value == id)) {
            result.push(id)
            this.setData({
                result
            })
        }
    },
    isAll() {
        let checkAll = this.data.checkAll;
        if (this.data.identity == '全部') {
            checkAll = (this.data.numberOfPeople == this.data.result.length) ? true : false;
        } else {
            checkAll = (this.data.result.length == this.data.buddyList.length) ? true : false;
        }
        console.log("isall", checkAll)
        this.setData({
            checkAll
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {}
})