import { getUserList, sendMail, } from '../../api/userManagement'

export default {
    data() {
        // 从localStorage获取之前选择的币种，如果没有则使用默认值'nexa'
        const savedCurrency = localStorage.getItem('userManagement_selectedCurrency') || 'nexa';
        
        return {
            userList: [],
            userListLoading: false,
            userListParams: {
                coin: savedCurrency,
                minerUser: "",
                user: "",
                pageNum: 1,
                pageSize: 50
            },
            tableData: [],
            userManagementLoading: false,
            formInline: {
                user: "",
                region: "",
            },
            currencyList: [],
            screenCurrency: savedCurrency,
            rules: {
                user: [
                    {
                        type: 'email',
                        message: this.$t('backendSystem.pleaseInputCorrectEmail'),
                        trigger: ['blur', 'change']
                    }
                ]
            },
            emailRules: {
                subject: [
                    { required: true, message: this.$t('backendSystem.pleaseInputSubject'), trigger: 'blur' }
                ],
                text: [
                    { required: true, message: this.$t('backendSystem.pleaseInputText'), trigger: 'blur' }
                ],
                to: [
                    {
                        /**
                         * 多邮箱校验+去重，支持中英文逗号分隔
                         * @param {Object} rule
                         * @param {string} value
                         * @param {Function} callback
                         */
                        validator: (rule, value, callback) => {
                          if (!value) {
                            callback(); // 允许为空
                            return;
                          }
                          // 以中英文逗号分隔，去除首尾空格
                          const emails = value.split(/[,，]/).map(e => e.trim()).filter(e => e);
                          // 邮箱正则
                          const emailReg = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
                          // 检查格式
                          for (let email of emails) {
                            if (!emailReg.test(email)) {
                              callback(new Error(this.$t('backendSystem.pleaseInputCorrectEmail2')));
                              return;
                            }
                          }
                          // 检查去重（忽略大小写）
                          const lowerSet = new Set();
                          for (let email of emails) {
                            const lower = email.toLowerCase();
                            if (lowerSet.has(lower)) {
                              callback(new Error(this.$t('backendSystem.existDuplicateEmail')));
                              return;
                            }
                            lowerSet.add(lower);
                          }
                          callback();
                        },
                        trigger: ['blur', 'change']
                      }
                ]
            },
            dialogVisible: false,
            senParams:{
                subject:"",
                text:"",
                to:"",
            },
            sendEmailLoading: false,
            total: 0,
            pageSizes: [50, 100, 300],
            currentPage: 1,


        }
    },
    mounted() {
        let token
        try{
          token =JSON.parse(localStorage.getItem('token')) 
        }catch(e){
         console.log(e);
        }
        if (!token) {
            this.$router.push({ path: `/${lang}/login` });
            
        }
        this.fetchUserList(this.userListParams);
        this.currencyList = JSON.parse(localStorage.getItem("currencyList"))
        window.addEventListener("setItem", () => {
            this.currencyList = JSON.parse(localStorage.getItem("currencyList"))
        });
        this.changeScreen(this.screenCurrency);
    },
    methods: {
        async fetchUserList(params) {
          
            this.setLoading('userManagementLoading', true);
            const data = await getUserList(params);
           console.log(data,'data');
           
            if (data && data.code == 200) {
                this.tableData = data.rows;
                this.total = data.total;
              
            }
         
            this.setLoading('userManagementLoading', false);
        },
        async fetchSendEmail(params) {
           
            this.setLoading('sendEmailLoading', true);
            const data = await sendMail(params);
           

            if (data && data.code == 200) {
                this.$message.success(this.$t('backendSystem.sendSuccess'));
                this.dialogVisible = false;
                for (const key in this.senParams) {
                     this.senParams[key] = "";
                }
            }
            this.setLoading('sendEmailLoading', false);
        },
        /**
         * 币种选择变更处理
         * @param {string} scope - 选择的币种
         */
        changeScreen(scope) {
            let brand = scope
            for (let index in this.currencyList) {
                let aa = this.currencyList[index];
                let value = aa.value;
                if (brand === value) {
                    this.$refs.screen.$el.children[0].children[0].setAttribute('style', "background:url(" + aa.imgUrl + ") no-repeat 10PX;background-size: 20PX 20PX;color:#333;padding-left: 33PX;");
                }
            }
            
            // 保存用户选择的币种到localStorage
            localStorage.setItem('userManagement_selectedCurrency', scope);
            
            this.userListParams.coin = scope
            this.fetchUserList(this.userListParams);

        },
        handelImg(coin) {
            if(this.currencyList &&this.currencyList.length > 0 && coin){
                return this.currencyList.find(item => item.value === coin)?.imgUrl || '';
            }else{
                return '';
            }
        },
        handelQuery() {
            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    for (let key in this.userListParams) {
                        if (typeof this.userListParams[key] === 'string') {
                            this.userListParams[key] = this.userListParams[key].trim();
                        }
                    }

                    if (!this.userListParams.minerUser && !this.userListParams.user) {
                        this.$message.error(this.$t('backendSystem.pleaseInputQueryConditions'));
                        return;
                    }
                    this.fetchUserList(this.userListParams);
                }
            });



        },
        sendEmail(row) {
            this.dialogVisible = true;
            this.senParams.to = row.user;
          
        },
        /**
         * 输入框清除后自动重新查询
         */
        handleInputClear() {
            this.fetchUserList(this.userListParams);
        },
        handleClose() {
            this.dialogVisible = false;
        },
        handleInput(val, type) {
           
        },
        sureSendEmail(){
            console.log(this.senParams,'this.senParams');

            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    this.fetchSendEmail(this.senParams);
                }
            });
        },
        handleDetails(row){
                console.log(row,'row');
                
              // 获取当前语言
              const lang = this.$i18n.locale;
            
            //   添加语言参数的路由跳转
              this.$router.push({ 
                  path: `/${lang}/userDetails`, 
                  query: { coin: row.coin,minerUser:row.minerUser,  user: row.user,} 
              }).catch(err => {
                  if(err.name !== 'NavigationDuplicated') {
                  console.error('路由跳转失败:', err);
                  }
              });

              let obj ={
                coin: row.coin,
                minerUser: row.minerUser,
                user: row.user,
              }
  
              // 保存ID到localStorage
              localStorage.setItem("userDetailsParams",JSON.stringify(obj));
        },
        
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.userListParams.pageSize = val
            this.userListParams.pageNum = 1
            this.currentPage = 1
            this.fetchUserList(this.userListParams);
           
        },
        handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.userListParams.pageNum = val
                 this.fetchUserList(this.userListParams);



        },
    }
}