<template>
  <div>
    <el-card style="margin-top: 50px;">
      <h1>用户余额</h1>
      <p>余额：{{ userBalanceData.userBalance || '加载中...' }}</p>
      <el-button type="primary" @click="navigateToRecharge">充值</el-button>
      <el-dialog
        title="实名认证"
        :visible.sync="dialogVisible"
        width="30%"
        @close="handleDialogClose"
      >
        <el-form :model="authForm" :rules="rules" ref="authFormRef">
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="authForm.name"></el-input>
          </el-form-item>
          <el-form-item label="身份证号" :label-width="formLabelWidth">
            <el-input v-model="authForm.idCard"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>
      </el-dialog>
    </el-card>


    <el-card style="margin-top: 50px">
      <!-- Form -->
      <h1>余额预警</h1>
      <el-button type="text" @click="dialogFormVisible = true">开启</el-button>
      <el-dialog title="添加预警号码" :visible.sync="dialogFormVisible">
        <el-divider style="border-color: #00afff;">
          <el-tag content-position="right" type="warning">
            账户可用余额小于该值时,每天短信通知一次(最多连续提醒5天)
          </el-tag>
        </el-divider>
        <el-form :model="form">
          <el-form-item label="预警阈值：" :label-width="formLabelWidth">
            <el-input v-model="form.userBalance" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="预警号码：" :label-width="formLabelWidth">
            <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>


    <el-card style="margin-top: 50px">
      <div>
        <!-- 装ECharts的容器 -->
        <div id="main" style="width: 100%; height: 520px; background: #fff">
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import {userBalance,months} from "@/api/system/user"; //
import * as echarts from 'echarts' //引用echarts
import {checkRealNameAuth} from "@/api/system/user";
import item from "@/layout/components/Sidebar/Item.vue";

export default {
  data() {
    return {
      charts: "",
      dialogVisible: false,
      listDate:[],
      a:[],
      b:[],
      dialogFormVisible: false,
      formLabelWidth: '120px',
      opinionData: [],
      userBalanceData: {
        userBalance: '加载中...'
      },
      authForm: {
        name: '',
        idCard: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        idCard: [
          {required: true, message: '请输入身份证号', trigger: 'blur'},
          {pattern: /^\d{17}[\dXx]$/, message: '身份证号格式不正确', trigger: 'blur'}
        ],
      },
      form: {}
    };
  },
  created() {
    this.fetchUserBalance();
    this.getList()
  },
  mounted() {
    this.drawLine();
  },
  methods: {
    getList(){
      months().then(response => {
        const responseDate = response;
         responseDate.forEach(item => {
            console.log('月',item.month, '总金额:', item.totalAmount)
         });
         this.listDate = responseDate;
         this.drawLine();
         this.$nextTick( () => {
           console.log(JSON.stringify(this.listDate))
         });
      });
    },
    handleCancel() {
      this.dialogVisible = false;
    },
    handleDialogClose() {
      this.authForm.name = '';
      this.authForm.idCard = '';
    },
    async navigateToRecharge() {
      try {
        const response = await checkRealNameAuth(this.authForm);
        if (response.data && response.data.desc) {
          // 如果已实名认证，直接跳转页面
          this.$router.push('/money/zfb');
        } else {
          // 如果未实名认证，显示对话框
          this.dialogVisible = true;
        }
      } catch (error) {
        this.$message.error('实名认证检查失败，请稍后再试');
        console.error('实名认证检查失败:', error);
      }
    },
    async handleConfirm() {
      this.$refs.authFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const {name, idCard} = this.authForm;
            const authResponse = await checkRealNameAuth(this.authForm);
            if (authResponse.data && authResponse.data.desc) {
              this.$message.success('实名认证成功');
              this.dialogVisible = false;
              this.$router.push('/money/zfb');
            } else {
              this.$message.error('实名认证失败，请检查您的信息');
            }
          } catch (error) {
            this.$message.error('实名认证验证失败，请稍后再试');
            console.error('实名认证验证失败:', error);
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    async fetchUserBalance() {
      try {
        const userId = localStorage.getItem('userId');
        console.log(userId)// 登录后把userId存到了localStorage
        if (!userId) {
          this.userBalanceData = {userBalance: '未登录'};
          return;
        }
        const response = await userBalance(userId);
        if (response.data) {
          console.log(response.data)
          this.userBalanceData.userBalance = response.data;
        } else {
          this.userBalanceData.userBalance = {userBalance: '获取失败'};
        }
      } catch (error) {
        this.userBalanceData = {userBalance: '获取失败'};
        console.error('Error fetching user balance:', error);
      }
    },
    drawLine() {
      // 初始化折线图
      this.charts = echarts.init(document.getElementById('main'));


      this.a = this.listDate.map(item => item.month)
      this.b = this.listDate.map(item => item.totalAmount)

      // 设置折线图数据和样式
      this.charts.setOption({
        title: {
          left: "3%",
          top: "5%",
          text: "近12月消费趋势", // 自定义
        },

        tooltip: {
          trigger: "axis",
        },

        legend: {
          align: "right",
          left: "3%",
          top: "15%",
          data: ["消费金额"], // 自定义
        },

        grid: {
          top: "30%",
          left: "5%",
          right: "5%",
          bottom: "5%",
          containLabel: true,
        },

        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },

        // 自定义：设置x轴刻度
        xAxis: {
          type: "category",
          boundaryGap: true,
          axisTick: {
            alignWithLabel: true,
          },
          // 自定义标签
          data: this.a,
        },

        // 自定义：设置y轴刻度
        yAxis: {
          type: "value",
          boundaryGap: true,
          splitNumber: 4,
          interval: 250,
        },

        // 设置数据
        series: [
          {
            name: "消费金额", // 自定义
            type: "line",
            stack: "总量", // 自定义
            data: this.b,
            areaStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgb(255,200,213)",
                  },
                  {
                    offset: 1,
                    color: "#ffffff",
                  },
                ],
                global: false,
              },
            },
            itemStyle: {
              color: "rgb(255,96,64)",
              lineStyle: {
                color: "rgb(255,96,64)",
              },
            },
          },
        ],
      });
    },
  },
};
</script>
