import utils from '../../utils/utils'
import biUtils from '../../utils/biUtils'
const itemClickMixins = {
    data() {
        return {
            stopClickLogin: false,
            isScrollLoading: false, // 滚动加载
            tableSource: {
                dataType: 'local',
                data: this.colData()
            } // 表格源
        }
    },
    methods: {
        //点击右侧标题链接
        clickRightTitle(item) {
            let url = item.rightTitleUrl
            if (url && !this.isEditable) {
                if (item.isTokenRight) { // 需要权限
                    url = url ? biUtils.setUserInfo(url, item, this) : url
                }
                biUtils.goHrefUrl(global, url)
            }
        },
        sortableHandler() {},
        // 滚动事件
        scroll(ev, item) {
            const _this = this
            if (item.isPage && item.pageSize) { // 是否分页
                let scrollTop = this.$refs.biReportLayout.scrollTop
                let clientHeight = this.$refs.biReportLayout.clientHeight
                let scrollHeight = this.$refs.biReportLayout.scrollHeight
                if (scrollTop + clientHeight >= scrollHeight && !this.isScrollLoading) { // 滑到底
                    this.isScrollLoading = true
                    let biDsUrls = this.$store.state.bi.biDSUrls['d' + (this.$store.state.bi.dialogEditors.length - 1)]
                    for (let biUs of biDsUrls) {
                        if (biUs.item && biUs.item.id == item.id && (!biUs.data.pageCount || biUs.data.pageCount > biUs.data.pageNo)) {
                            biUs.data.pageNo = biUs.data.pageNo + 1
                            this.$api({
                                url: biUs.url,
                                method: biUs.method,
                                data: biUs.data,
                                headers: biUs.headers
                            }).then(res => {
                                this.isScrollLoading = false
                                if (res.success) {
                                    biUs.data.pageCount = res.pageCount
                                    _this.$store.commit('setBiDSUrls', biDsUrls)
                                    this.$eventBus.$emit('initServeData', item, res, false)
                                } else {
                                    _this.$utils.msg(_this, '系统异常', 'error')
                                }
                            }).catch(error => {
                                this.isScrollLoading = false
                            })
                            break
                        }
                    }
                    // if (this.pageSize > this.total) {
                    //     return false
                    // } else {
                    //     this.pageSize = this.pageSize + 10 //显示条数新增
                    //     this.getpageList() //请求列表list 接口方法
                    // }
                } else {
                    return false
                }
            }
        },
        // 固定组件
        onStatic(e, item) {
            e.stopPropagation()
            item.static = !item.static
            this.$store.commit('saveArr', { data: {...item }, biModel: this.biModel })
            this.setStoreNatureArr()
        },
        // 业务组件-设计
        onDesign(e, item) {
            e.stopPropagation()
            this.$eventBus.$emit('openDesignDialog', item)
        },
        // 业务组件-刷新
        onRefreshBusiness(e, item) {
            e.stopPropagation()
            this.getBusinessOther(item)
        },
        // 获取业务组件信息
        getBusinessOther(d) {
            const _this = this
            let url =
                d.versionCode && d.versionCode != '草稿' ?
                '/ts-version/api/version/data?versionCode=' + d.versionCode :
                'ts-version/api/version/data?type=3&systemName=平台应用&moduleName=自定义报表&name=' +
                d.bid +
                '&copyFlag=1'
            this.$api({
                    url: url,
                    method: 'get',
                    contentType: 'application/x-www-form-urlencoded; charset=utf-8'
                })
                .then(function(res) {
                    if (res.success) {
                        d.natureArr = res.object ? JSON.parse(res.object).natureArr : []
                        _this.$store.commit('saveArr', { data: {...d } })
                        _this.setStoreNatureArr()
                    } else {
                        _this.$utils.msg(_this, '加载失败，请联系管理员', 'error')
                    }
                })
                .catch(function(error) {
                    // 请求失败
                })
        },
        setStoreNatureArr() {
            if (this.biModel == 'mobile') {
                this.$store.commit('setPhoneNature', [...this.$store.state.bi.phoneNature])
            } else {
                this.$store.commit('setNatureArr', {...this.$store.state.bi.natureArr })
            }
        },
        // 复制控件
        onCopy(e, item) {
            e.stopPropagation()
                // 所有控件重新分配id
            let newItem = JSON.parse(JSON.stringify(item))
            newItem.id = this.$utils.uuid(6)
            newItem.i = newItem.id
            newItem.y = newItem.h + newItem.y
            if (newItem.type == 'tab') {
                for (let tab of newItem.tabs) {
                    this.resetID(tab.natureArr)
                }
            } else if (newItem.type == 'table') {
                for (let col of newItem.cols) {
                    col.id = this.$utils.uuid(16)
                    if (col.type != 'seq') { //判断是否有序号列
                        col.pid = newItem.id
                    }
                }
            }
            if (newItem.natureArr && newItem.natureArr.length > 0) {
                //所有的页面控件id 都得重新部署
                this.resetID(newItem.natureArr)
            } else if (newItem.state == 1 && newItem.type == 'element') { // 快捷链
                this.resetID(newItem.dataSourceData)
            }
            // 放在控件位置
            let natureArr = this.biModel == 'mobile' ? this.$store.state.bi.phoneNature : this.$store.state.bi.natureArr['d' + (this.$store.state.bi.dialogEditors.length - 1)] || []
            this.setNatuPostion(item, natureArr, newItem)
            this.setStoreNatureArr()
        },
        // 删除控件
        onDelete(e, item) {
            e.stopPropagation()
            this.$eventBus.$emit('optDel', item)
        },
        // 放在控件位置
        setNatuPostion(data, arr, newItem) {
            for (let natu of arr) {
                if (natu.id === data.id) {
                    arr.push(newItem)
                    return true
                } else {
                    if (natu.type === 'tab') {
                        for (let tab of natu.tabs) {
                            if (this.setNatuPostion(data, tab.natureArr, newItem)) {
                                return true
                            }
                        }
                    } else if (natu.type === 'panel') {
                        if (this.setNatuPostion(data, natu.natureArr, newItem)) {
                            return true
                        }
                    }
                }
            }
            return false
        },
        //刷新整个页面数据
        refreshData(param) {
            this.$nextTick(() => {
                this.$emit('refreshData', param)
            })
        },
        //交互数据
        interData(interData) {
            this.$nextTick(() => {
                this.$emit('interData', interData)
            })
        },
        // 定时器刷新
        refreshDataTimer() {
            this.refreshData({})
        },
        // 刷新单选框下拉数据
        refreshRadioScreen(ev, item) {
            item.value = ev.label
            this.refreshScreen()
        },
        // 刷新单选框下拉数据
        refreshSelectScreen(ev, item) {
            item.value = ev.value
                // 下来框是数据源的情况
            if (item.selectDataSourceCode) {
                item.value = ev[item.selectDataSourceCode]
            }
            this.refreshScreen()
        },
        // 列拖拽
        columnDrop(args, item) {
            const arr = [...item.cols]
            let currRow = arr.splice(args[0], 1)[0]
            arr.splice(args[1], 0, currRow)
            item.cols = [...arr]
            this.$store.commit('saveArr', { data: {...item } })
            this.setStoreNatureArr()
        },
        // 刷新过滤器
        refreshFilter(item, ev) {
            if (this.isEditable) {
                return
            }
            item.area = ev.area //院区字段值
            item.start = ev.s //开始时间
            item.end = ev.e //结束时间
            this.$nextTick(() => {
                this.refreshScreen()
            })
        },
        // 日期控件回调
        selectDate(item, ev) {
            if (item.dateType == 'range' || item.dateType == 'rangetime' || item.controlType == '日期') {
                item.value = ev.s + ' ~ ' + ev.e
            } else {
                item.value = ev
            }
            this.refreshScreen()
        },
        //点击按钮
        onRealClick(item) {
            if (item.clickEvent == '查询' || item.clickEvent == '刷新') {
                this.refreshScreen('all')
            } else if (item.clickEvent == '导出') {
                this.$refs.bibutton.isChoose = true
            }
        },
        // // 刷新筛选树
        // refreshScreenTree(item, ev) {
        //     console.log(item.value, ev)
        //     this.refreshScreen()
        // },
        //导出
        exportExcel(val) {
            this.$emit('exportExcel', val)
        },
        //更新数据
        refreshScreen(val) {
            this.$emit('refreshData', { item: this.item, isRefreshScreen: val ? false : true })
        },
        // 改变日程组件中 当前日期的值
        changeNowDay(args, item) {
            item.nowDay = args[0].monthDay
            if (args[0].startDate || args[0].endDate) {
                item.startDate = args[0].startDate
                item.endDate = args[0].endDate
            }
            this.$store.commit('saveArr', { data: {...item } })
            this.$store.commit('setNatureArr', {...this.$store.state.bi.natureArr })
        },
        //刷新数字框
        inputRefresh(args, item) {
            item.value = args[0].value
            this.refreshScreen()
        },
        // 列表配置
        sourceRealFn(item) {
            let lazyOption = {
                sortName: item.sortName,
                sortOrder: item.sortOrder,
                lazyUrl: item.reqUrl,
                reqType: item.reqType,
                contentType: item.contentType,
                lazyType: item.dsType == 1 ? 'url' : 'custom',
                lazyId: item.lazyId
            }
            return {
                lazyOption: lazyOption,
                dataType: 'local',
                id: item.id,
                treeNode: item.treeNode || false,
                offPage: item.offPage || false,
                rownumbers: item.rownumbers,
                showOverflow: true,
                pageSize: item.offPage && item.data ? item.data.length : 100,
                data: this.biData || [],
                totalSet: item.totalSet ? [...item.totalSet] : [],
                colModel: item.cols || [],
                mergeCells: [],
                isExport: item.isExport || false,
                isPrint: item.isPrint || false
                    // resizable: false
            }
            // mergeCells.push({ row: 0, col: 1, rowspan: 1, colspan: 2 }) //这个获取数据的长度赋值
        },
        // getRealCols(cols) {
        //     for (let col of cols) {
        //         col.field = col.targetId
        //     }
        //     return cols
        // },
        // 列表配置
        sourceFn(item) {
            item.cols = (item.cols && item.cols.length > 0) ? item.cols : this.colFn(item.id)
            if (item.cols[0].type === 'seq' || (item.cols[0].title == '#' && !item.cols[0].field)) { // 兼容老版本
                item.rownumbers = true
                item.cols.splice(0, 1)
            }
            if (item.cols.length < 20) { // 少于10个，补齐，便于提交上传时，去掉多余无效cols
                for (let i = item.cols.length; i < 10; i++) {
                    item.cols.push({
                        id: utils.uuid(6),
                        title: '',
                        align: 'center',
                        field: 'col' + utils.uuid(6),
                        width: 60,
                        // sortable: false,
                        pid: item.id,
                        fontSize: 12,
                        fontColor: '#333',
                        backgroundColor: '',
                        resizable: false
                    })
                }
            }
            this.tableSource.rownumbers = item.rownumbers
            this.tableSource.id = item.id
            this.tableSource.offPage = item.offPage || false
            this.tableSource.colModel = [...item.cols]
            this.tableSource.backgroundColor = item.backgroundColor
            this.tableSource.anotherBackgroundColor = item.anotherBackgroundColor
            this.tableSource.headBackground = item.headBackground
            this.tableSource.headColor = item.headColor
            this.tableSource.stripe = item.stripe
                // this.tableSource.data = []
            this.tableSource.headerOverflow = item.headerOverflow
            return this.tableSource
        },
        // 设置模拟数据
        colData() {
            let colDatas = []
            for (let i = 0; i < 10; i++) {
                colDatas.push({})
            }
            return colDatas
        },
        colFn(pid) {
            let cols = []
            for (let i = 0; i < 10; i++) {
                cols.push({
                    id: utils.uuid(16),
                    title: '',
                    align: 'center',
                    field: 'col' + i,
                    width: 60,
                    // sortable: false,
                    pid: pid,
                    fontSize: 12,
                    fontColor: '#333',
                    backgroundColor: '',
                    resizable: false
                })
            }
            return cols
        },
        //tab编辑
        handleTabsEdit(args, item) {
            event.stopPropagation();
            if (!this.isEditable) {
                return false
            }
            let tabs = item.tabs;
            if (args[1] === 'add') {
                let newTabName = ++item.tabIndex + '';
                tabs.push({
                    title: '标题',
                    index: newTabName,
                    id: item.tabIndex + item.id,
                    natureArr: [],
                    dataSourceData: []
                });
                item.activeIndex = newTabName;
                item.controlTitle = tabs[tabs.length - 1].title
            }
            if (args[1] === 'remove') {
                if (tabs.length === 1) {
                    this.$utils.msg(this, '请至少保留一个')
                    return false
                }
                // 
                // let activeName = item.activeIndex;
                // if (activeName === args[0]) {
                tabs.forEach((tab, index) => {
                    if (tab.index == args[0]) {
                        let nextTab = tabs[index + 1] || tabs[index - 1];
                        if (nextTab) {
                            item.activeIndex = nextTab.index;
                            item.controlTitle = nextTab.label
                        }
                    }
                });
                item.tabs = tabs.filter(tab => tab.index !== args[0]);
            }
            // this.layout = [...this.layout]
            this.$eventBus.$emit('itemselectchange', { target: item, select: true });
            this.$store.commit('saveArr', { data: {...item } })
            this.$store.commit('setNatureArr', {...this.$store.state.bi.natureArr })
        },
        //tab点击的触发
        tabClick(args, item) {
            args[1].stopPropagation()
            if (!this.isEditable) { // 预览
                this.refreshScreen()
                return false
            }
            // 非设计阶段
            item.activeIndex = args[0].name
            item.controlTitle = args[0].label
            item.roleIds = item.tabs[Number(args[0].index)].roleIds || ''
            this.$eventBus.$emit('itemselectchange', { target: item, select: true });
            // this.$store.commit('setSelectData', { ...this.selectData })
            this.$store.commit('saveArr', { data: {...this.item } })
            this.$store.commit('setNatureArr', {...this.$store.state.bi.natureArr })
        },
        // tab的复制功能（复制在最后一个页签）
        onTabCopy(ev, item) {
            ev.stopPropagation()
            if (item.tabs && item.tabs.length > 0) {
                for (let t of item.tabs) {
                    if (t.index == item.activeIndex) {
                        let actItem = _.cloneDeep(t)
                        if (actItem.natureArr && actItem.natureArr.length > 0) {
                            //所有的页面控件id 都得重新部署
                            this.resetID(actItem.natureArr)
                        }
                        actItem.title = actItem.title + '-副本'
                        let newTabName = ++item.tabIndex + '';
                        actItem.index = newTabName
                        actItem.id = item.tabIndex + item.id
                        item.tabs.push(actItem)
                        this.$store.commit('saveArr', { data: {...this.item } })
                        this.setStoreNatureArr()
                        break
                    }
                }

            }
        },
        // 复制后重新部署控件内的id
        resetID(natureArr) {
            for (let natu of natureArr) {
                natu.id = this.$utils.uuid(16)
                natu.i = natu.id
                if (natu.type == 'table') {
                    for (let col of natu.cols) {
                        col.id = this.$utils.uuid(16)
                        col.pid = natu.id
                    }
                } else if (natu.type === 'tab') {
                    for (let tab of natu.tabs) {
                        if (tab.index == natu.activeIndex) {
                            this.resetID(tab.natureArr)
                        }
                    }
                } else if (natu.type === 'panel') {
                    this.resetID(natu.natureArr)
                } else if (natu.type === 'element' && natu.state == '1') { // 快捷链
                    this.resetID(natu.dataSourceData)
                }
            }
        },
        //元素点击
        itemClick(ev, item) {
            ev.stopPropagation()
            if (!this.isEditable) { // 非设计阶段
                return false
            }
            let dom = ev.currentTarget
            if (dom.className.indexOf('business__handle') > -1) { // 为防止业务组件内部被点击到，放一层透明遮罩
                dom = dom.parentElement.parentElement.parentElement
            }
            let itemHandle = dom.getElementsByClassName('biUserDefined-item__handle');
            if (!itemHandle || itemHandle.length == 0) {
                return false
            }
            let selected = itemHandle[0].style.height == '100%'
            this.$eventBus.$emit('resetOtherActive', {}) //清除其他高亮
            itemHandle[0].style.height = '100%'
            itemHandle[0].style.border = '2px'
            itemHandle[0].style.borderColor = 'var(--base-acv)'
            itemHandle[0].style.borderStyle = 'solid'
            if (selected) {
                this.$eventBus.$emit('itemselectchange', { target: item, select: true, isClose: false });
                return false
            }
            this.$eventBus.$emit('itemselectchange', { target: item, select: true, isClose: true });
        },
        //点击表格表头
        headerClickEvent(args, item) {
            event.stopPropagation()
            if (!this.isEditable) {
                return false
            }
            let selected = args[1].headerClassName === 'biUserDefined-table__active'
            this.$eventBus.$emit('resetOtherActive', {}) //清除其他高亮
            if (selected) {
                this.$eventBus.$emit('itemselectchange', { target: {}, select: !selected });
                return false
            }
            args[1].headerClassName = !selected ? 'biUserDefined-table__active' : ''
            let prop = args[1].property
            let selectColItem = this.getColItem(item.cols, prop)

            this.$store.commit('setBISelectTable', {
                ...this.item
            })
            this.$eventBus.$emit('itemselectchange', { target: selectColItem, select: !selected });
        },
        // 得到单元格
        getColItem(cols, prop) {
            for (let colItem of cols) {
                if (colItem.children && colItem.children.length > 0) {
                    let nItem = this.getColItem(colItem.children, prop)
                    if (Object.keys(nItem).length > 0) {
                        return nItem
                    }
                }
                if (colItem.field === prop) {
                    colItem.type = 'col';
                    return colItem
                }
            }
            return {}
        },
        // 节流
        stopClick(name = `stopClickLogin`, time = 300, msg = `操作太快了`) {
            let that = this
            return new Promise((resolve, reject) => {
                if (that[name]) {
                    return false
                }
                that[name] = true
                setTimeout(() => { that[name] = false }, time)
                resolve()
            })
        },
        cellClickEvent(args, item) {
            event.stopPropagation()
            if (this.isEditable) {
                return false
            }
            this.stopClick(`stopClickLogin`).then(() => {
                let fieldValue = args[0][args[1].property] //获取点击的值
                for (let col of item.cols) { //判断列里面是否有钻取
                    if (col.field == args[1].property) { //找到点击的那列对应的col配置
                        if (col.clickEvent && col.clickEvent.length > 0) { //如果有则打开弹窗 传的数据为那一列的配置
                            this.$nextTick(() => {
                                this.$eventBus.$emit('openTable', col.clickEvent, fieldValue)
                            })
                            return
                        }
                        if (col.showMainText) {
                            this.$eventBus.$emit('openDialog', fieldValue)
                        }
                    }

                    //判断是否有钻取文本
                }

                // 超链接
                if (args[1].params && args[1].params.link) {
                    if (args[1].params.link.linkTypeId == 1) { //网络报表
                        this.$router.push({
                            path: '#/bi/biPreview_' + args[1].params.link.reportNameId + '?mid=' + this.$utils.uuid(16)
                        })
                    } else if (args[1].params.link.linkTypeId == 2) { //网络报表
                        window.open(args[1].params.link.reportName, '_blank')
                    }
                }
                if (item.clickEvent && item.clickEvent.length > 0) {
                    this.$emit('interData', { row: args[0], thisItem: item })
                }
            })
        },
        // 图表的超链接
        chartClick(ev, item) {
            if (this.isEditable) { // 非编辑
                return false
            }
            if (item.linkTypeId == 1) { //网络报表
                this.$router.push({
                    path: '/bi/biPreview?id=' + item.reportNameId + '&mid=' + this.$utils.uuid(16)
                })
            } else if (item.linkTypeId == 2) { //网络报表
                window.open(item.reportName, '_blank')
            }
        },
        // 懒加载业务组件内部控件
        getBusinessNatureArr(item) {
            this.getBusinessOther(item)
            return []
        },
        // 初始化筛选框下拉
        initDimensionSelect(item) {
            //  日期或者维度
            if (item.state == 1 || item.dataType == 0) {
                return {
                    dataType: 'json',
                    url: '/ts-bi/api/bi/cube/queryDimLevels',
                    method: 'get',
                    data: {
                        dimension: item.state == 1 ? 'DIM_DATE_DAY' : item.fieldNamesId || ''
                    },
                    choice: item.state == 3,
                    page: 'pageNo',
                    code: 'LEVEL_NAME',
                    text: 'DESCRIPTION',
                    isReq: true,
                    value: {
                        name: '',
                        code: ''
                    },
                    condition: 'condition'
                }
            } else {
                // 数据源
                let isResult = (item.dataSource && item.dataSource.serviceType == 2) || (item.dataSourceDataResult && item.dataSourceDataResult.length) || (item.selectDataSourceResultData && item.selectDataSourceResultData.length)
                let url = isResult ? '/ts-query/api/user/query/procFun/query' : '/ts-query/api/user/query/table/query'
                let data = {
                    id: item.selectDataSource
                }
                return {
                    dataType: item.dataType == 2 ? 'local' : 'json', // 若为选项配置，则为本地数据
                    url: url,
                    contentType: 'application/x-www-form-urlencoded',
                    data: item.dataType == 2 ? item.dataTypeList : data,
                    method: 'post',
                    choice: item.state == 3,
                    page: 'pageNo',
                    code: item.dataType == 2 ? 'value' : item.selectDataSourceCode,
                    text: item.dataType == 2 ? 'text' : item.selectDataSourceName,
                    isReq: true
                }
            }
        }
    }

}
export default itemClickMixins