
import { subscriptionConfiguration } from "../../util/subscriptionMetrics";
import { getSubscript, getSubscriptList, getSubscriptDelete } from "../../api/messageSubscription";
export default {
    data() {
        return {
            btLoading: false,
            AlarmLoading: false,
            activeName: "selectAlarm",
            from: [{
                date: `2023-12-02`,
                indicators: "指标1",
                threshold: "22000.05",
                cycle: "10分钟",
                notice: "Android App"
            },
            {
                date: `2023-12-12`,
                indicators: "指标5",
                threshold: "22000.05",
                cycle: "15分钟",
                notice: "Android App、Email"
            }
            ],
            currentPage1: 1,
            pageSizes: [20, 50, 100,],
            totalLimit1: 0,
            formLabelAlign: {
                // region: "",
                // min: "",
                // max: "",
                // percentageMin: "",
                // percentageMax: "",
                // content: "",
                addresses: "",
                cycle: "",
                noticeWay: "",
                channel: "BTCOnChain",
                metrics: "活跃地址数",

            },
            labelPosition: "left",
            options: [{
                value: '选项1',
                label: '选项1'
            }, {
                value: '选项2',
                label: '选项2'
            }, {
                value: '选项3',
                label: '选项3'
            },],
            value: '',
            radio: "",
            cycle: "",
            cycleList: [
                {
                    value: '5m',
                    label: "5分钟",
                },
                {
                    value: '10m',
                    label: "10分钟",
                },
                {
                    value: '15m',
                    label: "15分钟",
                },
                {
                    value: '30m',
                    label: "30分钟",
                },
                {
                    value: '1h',
                    label: "1小时",
                },
                {
                    value: '4h',
                    label: "4小时",
                },
                {
                    value: '8h',
                    label: "8小时",
                },
                {
                    value: '12h',
                    label: "12小时",
                },
                {
                    value: '1d',
                    label: "1天",
                },
                {
                    value: '1w',
                    label: "1周",
                },
                {
                    value: '1M',
                    label: "1月",
                },


            ],
            contactList: [`Email`,],//[`Email`, `Android App`, `站内信`]

            contact: {
                // Email:true,
            },
            contactWeekly: [],
            contactMonthly: [],
            contactMajor: {},
            contactNotice: {
                Email: true,
            },
            range: "",
            rise: "",
            dialogVisible: false,
            newCycle: "",
            modes: "Email",
            reportDialogVisible: false,
            daily: "",
            WeeklyValue: "",
            MonthlyValue: "",
            MajorValue: "",
            Text: "",
            errorMessage: "请输入最多两位小数的数字",
            threshold: "数值",
            indexList: [],
            show: false,
            activeItem: {
                value: '巨鲸钱包监控',
                label: '巨鲸钱包监控',
                alarmType: [`地址`,],
                alarmInterval: [`1天`,],
            },
            threshold2: "",
            defaultIndex: `交易量`,
            threshold3: "",
            alarmType: [],
            alarmInterval: [],
            address: "",
            conditionList: [
                {
                    value: '>',
                    label: "大于",
                },
                {
                    value: '<',
                    label: "小于",
                },
                {
                    value: '+',
                    label: "涨",
                },
                {
                    value: '-',
                    label: "跌",
                },


            ],
            alarmCycleList: [
                {
                    value: '1d',
                    label: "subscribe.day",

                },
                {
                    value: 'realTime',
                    label: "subscribe.realTimeData",

                },

            ],
            flatIndexList:[],
        }
    },
    created() {
        this.indexList = subscriptionConfiguration
        this.activeItem = this.indexList[0].children[0].children[0].children[0]
        this.formLabelAlign.metrics = this.activeItem.id
        this.formLabelAlign.channel = this.activeItem.channel
        this.formLabelAlign.cycle = this.activeItem.alarmInterval
        this.formLabelAlign.noticeWay = this.modes
        this.formLabelAlign.cycle = `realTime`
    },
    mounted() {
        this.indexList = subscriptionConfiguration
        this.flatIndexList = this.handelAllMenu(this.indexList) //扁平化指标选择
        this.handelChoice()
        this.fetchSubscriptionList()
    },

    computed: {
        getTranslatedOptions() {

            return this.translateOptions(this.indexList);

        }
    },
    methods: {
        //扁平化导航数组 递归
        handelAllMenu(arr) {
            var result = [];
            arr.forEach((item) => {
                if (!item.children) {
                    result.push(item);
                } else {
                    var nestedItems = this.handelAllMenu(item.children);
                    result = result.concat(nestedItems);
                }
            });

            return result;
        },
        //映射I18n
        translateOptions(options) {
            return options.map(option => {
                const translatedOption = {
                    ...option,
                    label: this.$t(option.label)
                };
                if (option.children) {
                    translatedOption.children = this.translateOptions(option.children);
                }
                return translatedOption;
            });
        },
        async fetchSubscript(params) {

            this.btLoading = true
            const { data } = await getSubscript(params)
            if (data && data.code == 200) {
                this.$message({
                    message: data.msg,
                    type: "success",
                });
                this.fetchSubscriptionList()
                this.address = ""
                this.dialogVisible = false
            }
            this.btLoading = false
        },

        async fetchSubscriptionList(params) {
            this.AlarmLoading = true
            const { data } = await getSubscriptList(params)
            this.from = data.rows
            this.from.forEach(item => {
                item.date = item.date.split(`T`)[0]
            })
            this.AlarmLoading = false
        },

        async fetchSubscriptionCancel(params) {
            this.AlarmLoading = true
            const { data } = await getSubscriptDelete(params)
            if (data && data.code == 200) {
                this.$message({
                    message: data.msg,
                    type: "success",
                });
                this.fetchSubscriptionList()

            }

            this.AlarmLoading = false

        },
        handelMetrics(metrics){
            
            let obj = this.flatIndexList.find(item => item.id == metrics)
            if (obj) {
                return  this.$t(obj.label);
            }else{
                return metrics
            }
        },
        //处理告警周期
        handelAlarmCycle(value) {
            
             
            let obj = this.alarmCycleList.find(item => item.value == value)
            if (obj) {
                return this.$t(obj.label) 
            }

        },
        handleInputBlur() {

            this.address = this.address.split("/")

            this.address = this.address.filter(value => value !== "")

            if (this.address.length > 5) {
                this.address = this.address.slice(0, 5);
                // console.log("不能超过五条");

                // this.$message({
                //     message:"最多指定5个地址",
                //     type: "warning",
                // });

            }

            this.address = this.address.join("/")
        },
        handleConfirm() {
            this.reportDialogVisible = true
            this.Text = `订阅确认`
        },
        handelUnsubscribe() {
            this.reportDialogVisible = true
            this.Text = `退订确认`
        },
        handleInput(value) {
            let format = /^\d+(\.\d{0,2})?$/.test(value)
            // 使用正则表达式验证输入的值
            if (!format) {
                this.formLabelAlign.region = this.formLabelAlign.region.slice(0, -1); // 不符合规定的格式，移除最后输入的字符
                this.formLabelAlign.min = this.formLabelAlign.min.slice(0, -1); // 不符合规定的格式，移除最后输入的字符

            }
        },
        handleMaxInput(value) {
            let format = /^\d+(\.\d{0,2})?$/.test(value)
            // 使用正则表达式验证输入的值
            if (!format) {
                this.formLabelAlign.max = this.formLabelAlign.max.slice(0, -1); // 不符合规定的格式，移除最后输入的字符

            }
        },
        handleInputPercentage(value) {
            let format1 = /^\d+(\.\d{0,1})?$/.test(value)
            // 使用正则表达式验证输入的值
            if (!format1) {
                this.formLabelAlign.addresses = this.formLabelAlign.type.slice(0, -1); // 不符合规定的格式，移除最后输入的字符

            }
        },
        handleInputPercentageMin(value) {
            let format = /^\d+(\.\d{0,1})?$/.test(value)
            // 使用正则表达式验证输入的值
            if (!format) {
                this.formLabelAlign.percentageMin = this.formLabelAlign.percentageMin.slice(0, -1); // 不符合规定的格式，移除最后输入的字符

            }
        },
        handleInputPercentageMax(value) {
            let format = /^\d+(\.\d{0,1})?$/.test(value)
            // 使用正则表达式验证输入的值
            if (!format) {
                this.formLabelAlign.percentageMax = this.formLabelAlign.percentageMax.slice(0, -1); // 不符合规定的格式，移除最后输入的字符

            }
        },
        // 日报订阅
        handelCheckbox(value) {
            if (value) {
                this.formLabelAlign.channel = "Observations"
                this.formLabelAlign.metrics = "日报订阅"
            }
            const checkedValues = Object.keys(this.contact).filter(key => this.contact[key]);
            checkedValues.forEach(item => {
                if (!this.daily.includes(item)) {
                    this.daily += item + `、`
                }

            })
            this.formLabelAlign.noticeWay = this.daily

        },
        handelCheckboxWeekly() {
            let checkedValuesWeekly = Object.keys(this.contactWeekly).filter(key => this.contactWeekly[key]);
            checkedValuesWeekly.forEach(item => {
                if (!this.WeeklyValue.includes(item)) {
                    this.WeeklyValue += item + `、`
                }

            })
        },
        handelCheckboxMonthly() {
            let checkedValuesMonthly = Object.keys(this.contactMonthly).filter(key => this.contactMonthly[key]);
            checkedValuesMonthly.forEach(item => {
                if (!this.MonthlyValue.includes(item)) {
                    this.MonthlyValue += item + `、`
                }

            })
        },
        handelCheckboxMajor() {
            let checkedValuesMajor = Object.keys(this.contactMajor).filter(key => this.contactMajor[key]);
            checkedValuesMajor.forEach(item => {
                if (!this.MajorValue.includes(item)) {
                    this.MajorValue += item + `、`
                }

            })
        },
        handelCheckboxNotice() {
            let checkedValuesNotice = Object.keys(this.contactNotice).filter(key => this.contactNotice[key]);
            this.modes = ""
            checkedValuesNotice.forEach(item => {

                this.modes += item + `、`
            })
           
           if (this.modes.charAt(this.modes.length - 1) === "、") {
              // 删除最后一个字符
              this.modes = this.modes.slice(0, -1);
           }
            this.formLabelAlign.noticeWay = this.modes
        },
        handelSubmit() {


            if (this.cycle) {
                this.newCycle = this.cycleList.find(item => item.value == this.cycle).label
            }
            if (this.formLabelAlign.type) {
                this.formLabelAlign.type = this.formLabelAlign.type + `%`
            }
            if (this.threshold2 == `subscribe.address`) {//等于地址
                // const regex = /[^\u4e00-\u9fa5]+/g;
                const regex = /[\u4E00-\u9FA5]/

                // 地址不能为空或输入中文字符
                if (regex.test(this.address) || !this.address) {
                    this.$message({
                        message: this.$t(`subscribe.addressVerification`),
                        type: 'warning'
                    });

                    return
                }


                this.formLabelAlign.addresses = this.address.replace(/\//g, ",");

            }
            // 请至少选择一种通知方式
            if (!this.formLabelAlign.noticeWay) {
                this.$message({
                    message: this.$t(`subscribe.noticeVerification`),
                    type: 'warning'
                });
                return
            }

            this.dialogVisible = true


        },
        handelConfirm() {
            // 该指标已订阅，不能重复订阅！
            if (this.from.some(item=>item.metrics == this.formLabelAlign.metrics)) {
                this.$message({
                    message: this.$t(`subscribe.repeatSubscription`),
                    type: 'warning'
                });

                return
            }
            if (this.formLabelAlign.cycle == "1天" || this.formLabelAlign.cycle == `subscribe.day` ) {
                this.formLabelAlign.cycle = "1d"
            }
            this.fetchSubscript(this.formLabelAlign)

        },
        //订阅列表退订
        deleteRow(rows) {
            this.fetchSubscriptionCancel({ id: rows.id })
        },
        handelRadio() {
            this.formLabelAlign.type = ""
            this.formLabelAlign.percentageMax = ""
            this.formLabelAlign.percentageMin = ""
            this.formLabelAlign.max = ""
            this.formLabelAlign.min = ""
            this.formLabelAlign.region = ""
        },
        handelIndex(value) {
            const selectedOptions = this.$refs.cascader.getCheckedNodes(value);
           
            this.activeItem = selectedOptions[0].data
            this.formLabelAlign.cycle = this.activeItem.alarmInterval[0]
            this.formLabelAlign.metrics = this.activeItem.id
            this.formLabelAlign.channel = this.activeItem.channel
            this.address =""
            this.formLabelAlign.addresses = ""
           
            this.handelChoice() 

        },
        handelChoice() {
            this.indexList = subscriptionConfiguration
            if (this.activeItem.children && this.activeItem.children[0]) {

                this.threshold2 = this.activeItem.children[0].alarmType[0]
                this.threshold2 = this.activeItem.children[0].alarmType[0]
                this.threshold3 = this.activeItem.children[0].alarmInterval[0]
                this.alarmType = this.activeItem.children[0].alarmType
                this.alarmInterval = this.activeItem.children[0].alarmInterval

            } else {
                this.threshold2 = this.activeItem.alarmType[0]
                this.threshold2 = this.activeItem.alarmType[0]
                this.threshold3 = this.activeItem.alarmInterval[0]
                this.alarmType = this.activeItem.alarmType
                this.alarmInterval = this.activeItem.alarmInterval

            }


        }



    }
}