<template>
  <div class="app-container" v-loading="loading">
    <template>
      <!-- 添加操作按钮 -->


      <!-- 统计卡片行 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="3" v-for="(stat, index) in statisticsData" :key="index">
          <div class="stat-card">
            <div class="stat-icon" :class="stat.color">
              <i :class="stat.icon"></i>
            </div>
            <div class="stat-content">
              <div class="stat-label">{{ stat.label }}</div>
              <div class="stat-value">
                <template v-if="stat.isMoney">¥ {{ detail[stat.field] || '0.00' }}</template>
                <template v-else>{{ detail[stat.field] || '0' }} {{ stat.unit }}</template>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="12" class="detail-row">
        <!-- 用户详情卡片 -->
        <el-col :lg="10" :md="12" :xs="24">
          <el-card class="box-card detail-card">
            <template #header>
              <el-row type="flex" style="justify-content: space-between">
                <div>用户详情</div>
              </el-row>
              <el-row type="flex" justify="end" class="mb-2">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate"
                  v-hasPermi="['system:smUser:edit']">修改</el-button>
                <el-button type="primary" icon="el-icon-setting" size="mini" @click="handleUpdateRisk"
                  v-hasPermi="['system:smUser:edit']">配置</el-button>
              </el-row>
            </template>
            <div class="user-detail">
              <div class="user-header">
                <img :src="userAvatar" alt="用户头像" class="user-avatar"/>
                <div class="name-box">
                  <span class="user-name">{{ detail.userName }}</span>
                  <dict-tag :value="detail.userType" :options="dict.type.ss_user_type" style="margin-top: 4px;" />
                </div>
                <div class="phone-number">{{ detail.phonenumber }}</div>
              </div>

              <div class="user-description">
                <el-descriptions :column="3">
                  <el-descriptions-item label="充值服务费">
                    {{ detail.serviceFeeProportion | money | defaultValue }} %
                  </el-descriptions-item>
                  <el-descriptions-item label="代理服务费">
                    {{ detail.agentServiceRate | money | defaultValue }} %
                  </el-descriptions-item>
                  <el-descriptions-item label="提现服务费">
                    <template v-if="detail.withdrawServiceRate == null || detail.withdrawServiceType == null">
                      跟随渠道
                    </template>
                    <template v-else>
                      <dict-tag :options="dict.type.withdraw_service_type" :value="detail.withdrawServiceType"
                        size="mini" />
                      {{ detail.withdrawServiceRate }} {{ serviceUnit(detail.withdrawServiceType) }}
                    </template>
                  </el-descriptions-item>
                  <el-descriptions-item label="姓名">
                    {{ detail.realName | dv }}
                  </el-descriptions-item>
                  <el-descriptions-item label="身份证">
                    {{ detail.idCard | dv }}
                  </el-descriptions-item>
                  <el-descriptions-item label="实名手机">
                    {{ detail.phonenumber | dv }}
                  </el-descriptions-item>
                  <el-descriptions-item label="备注" :span="2">
                    {{ detail.remark | dv }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 报表卡片 -->
        <el-col :lg="14" :md="12" :xs="24">
          <el-card class="box-card">
            <el-tabs v-model="reportActiveTab" @tab-click="handleReportTabClick" style="width: 100%">
              <!-- 日报表 -->
              <el-tab-pane label="日报表" name="daily">
                <div class="report-container">
                  <div class="filter-section">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                      end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd"
                      @change="loadDailyReport" />
                  </div>
                  <div class="chart-container">
                    <div ref="dailyChart" style="width: 100%; height: 300px"></div>
                  </div>
                </div>
              </el-tab-pane>

              <!-- 月报表 -->
              <el-tab-pane label="月报表" name="monthly">
                <div class="report-container">
                  <div class="filter-section">
                    <el-date-picker v-model="selectedMonth" type="month" placeholder="选择月份" value-format="yyyy-MM"
                      @change="loadMonthlyReport" />
                  </div>
                  <div class="chart-container">
                    <div ref="monthlyChart" style="width: 100%; height: 300px"></div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
      </el-row>
    </template>

    <!-- 添加修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="form.userType" placeholder="请选择用户类型">
                <el-option v-for="dict in filteredUserTypes" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                  dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.userType === '01'">
          <el-col :span="12">
            <el-form-item label="服务费率" prop="serviceFeeProportion">
              <el-input-number v-model="form.serviceFeeProportion" :min="0" :max="100" :precision="2"
                controls-position="right">
                <template slot="append">%</template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.userType === '05'">
          <el-col :span="12">
            <el-form-item label="分红状态" prop="dividendStatus">
              <el-switch v-model="form.dividendStatus" active-value="0" inactive-value="1"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分红比例" prop="dividendProportion">
              <el-input-number v-model="form.dividendProportion" :min="0" :max="100" :precision="2"
                controls-position="right">
                <template slot="append">%</template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户配置对话框 -->
    <user-config-dialog :show.sync="showConfigDialog" :user-id="detail.userId" @success="getDetail" />
    <el-tabs v-model="mainActiveTab" class="detail-tabs" v-if="detail.userId">
      <el-tab-pane label="收入订单" name="orders">
        <order :userId="detail.userId"></order>
      </el-tab-pane>
      <el-tab-pane label="充值订单" name="recharge">
        <order :merchantId="detail.userId"></order>
      </el-tab-pane>
      <el-tab-pane label="设备列表" name="devices">
        <device :userId="detail.userId"></device>
      </el-tab-pane>
      <el-tab-pane label="套餐列表" name="rules">
        <rule :userId="detail.userId"></rule>
      </el-tab-pane>
      <el-tab-pane label="设施列表" name="equipments">
        <equipment :userId="detail.userId"></equipment>
      </el-tab-pane>
      <el-tab-pane label="店铺列表" name="stores">
        <store :userId="detail.userId"></store>
      </el-tab-pane>
      <el-tab-pane label="房间列表" name="rooms">
        <room :userId="detail.userId"></room>
      </el-tab-pane>
      <el-tab-pane label="分账明细" name="detail">
        <detail :userId="detail.userId"></detail>
      </el-tab-pane>
      <el-tab-pane label="帐变记录" name="changeBalance">
        <changeBalance :userId="detail.userId"></changeBalance>
      </el-tab-pane>
      <el-tab-pane label="提现记录" name="withdraw">
        <withdraw :userId="detail.userId"></withdraw>
      </el-tab-pane>
      <el-tab-pane label="提现渠道" name="userWithdraw">
        <userWithdraw :userId="detail.userId"></userWithdraw>
      </el-tab-pane>
      <el-tab-pane label="设备绑定" name="bindList">
        <bindList :userId="detail.userId"></bindList>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getUser, updateUser } from "@/api/user/user";
import UserConfigDialog from './components/UserConfigDialog.vue';
import { $serviceType, $view } from '@/utils/mixins';
import * as echarts from 'echarts';
import order from '@/views/system/order/index.vue'
import device from '@/views/system/device/index.vue'
import rule from '@/views/system/rule/index.vue'
import equipment from '@/views/system/equipment/index.vue'
import store from '@/views/system/store/index.vue'
import room from '@/views/system/room/index.vue'
import detail from '@/views/system/detail/index.vue'
import changeBalance from '@/views/system/changeBalance/index.vue'
import withdraw from '@/views/system/withdraw/index.vue'
import userWithdraw from '@/views/system/userWithdraw/index.vue'
import bindList from './components/bindList.vue'

export default {
  name: "UserDetail",
  mixins: [$view, $serviceType],
  dicts: ['sys_normal_disable', 'ss_user_type', 'withdraw_service_type'],
  components: {
    UserConfigDialog,
    order,
    device,
    rule,
    equipment,
    store,
    room,
    detail,
    changeBalance,
    withdraw,
    userWithdraw,
    bindList
  },
  data() {
    return {
      detail: {},
      loading: false,
      showConfigDialog: false,

      dateRange: [],
      selectedMonth: '',
      dailyReportData: [],
      monthlyReportData: [],
      dailyChart: null,
      monthlyChart: null,
      open: false,
      title: "",
      form: {},
      reportActiveTab: 'daily',
      mainActiveTab: 'orders',
      statisticsData: [
        { label: '店铺数', field: 'storeNum', icon: 'el-icon-office-building', color: 'blue', unit: '家' },
        { label: '房间数', field: 'roomNum', icon: 'el-icon-house', color: 'pink', unit: '间' },
        { label: '设施数', field: 'equNum', icon: 'el-icon-box', color: 'cyan', unit: '个' },
        { label: '设备数', field: 'deviceNum', icon: 'el-icon-monitor', color: 'green', unit: '台' },
        { label: '账户余额', field: 'balance', icon: 'el-icon-wallet', color: 'purple', isMoney: true },
        { label: '总收入', field: 'totalIncome', icon: 'el-icon-money', color: 'orange', isMoney: true },
        { label: '总提现', field: 'totalWithdrawAmount', icon: 'el-icon-bank-card', color: 'red', isMoney: true },
        { label: '总消费', field: 'totalConsume', icon: 'el-icon-shopping-cart-full', color: 'brown', isMoney: true }
      ],

      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }]
      },

      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        userType: [
          { required: true, message: "用户类型不能为空", trigger: "change" }
        ],
        serviceFeeProportion: [
          { required: true, message: "服务费率不能为空", trigger: "blur" }
        ],
        dividendProportion: [
          { required: true, message: "分红比例不能为空", trigger: "blur" }
        ]
      },

      userName: '',
      phonenumber: '',
      avatar: '', // 用户自定义头像
      defaultAvatar: require('@/assets/icons/svg/user2.png') // 确保路径和文件名正确
    };
  },
  computed: {
    filteredUserTypes() {
      return this.dict.type.ss_user_type.filter(item => item.value !== '09');
    },
    serviceUnit() {
      return (type) => {
        return type === '2' ? '元' : '%'
      }
    },
    userAvatar() {
      return this.avatar || this.defaultAvatar;
    }
  },
  created() {
    this.getDetail();
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    this.dateRange = [this.formatDate(start), this.formatDate(end)];
    this.selectedMonth = this.formatDate(new Date()).substring(0, 7);
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
    });
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.dailyChart) {
      this.dailyChart.dispose();
    }
    if (this.monthlyChart) {
      this.monthlyChart.dispose();
    }
  },
  methods: {
    initCharts() {
    this.$nextTick(() => {
      // 根据当前激活的 tab 初始化对应的图表
      if (this.reportActiveTab === 'daily' && this.$refs.dailyChart) {
        this.dailyChart = echarts.init(this.$refs.dailyChart);
        this.loadDailyReport();
      } else if (this.reportActiveTab === 'monthly' && this.$refs.monthlyChart) {
        this.monthlyChart = echarts.init(this.$refs.monthlyChart);
        this.loadMonthlyReport();
      }

      // 添加窗口大小变化监听
      window.addEventListener('resize', this.handleResize);
    });
  },

  handleResize() {
    // 只对当前激活的图表进行 resize
    if (this.reportActiveTab === 'daily' && this.dailyChart) {
      this.dailyChart.resize();
    } else if (this.reportActiveTab === 'monthly' && this.monthlyChart) {
      this.monthlyChart.resize();
    }
  },

    handleReportTabClick(tab) {
    // 在切换后给图表一个重新渲染的机会
    this.$nextTick(() => {
      if (tab.name === 'daily') {
        // 如果已存在图表实例，先销毁
        if (this.dailyChart) {
          this.dailyChart.dispose();
        }
        // 重新初始化图表
        this.dailyChart = echarts.init(this.$refs.dailyChart);
        this.loadDailyReport();
      } else if (tab.name === 'monthly') {
        // 如果已存在图表实例，先销毁
        if (this.monthlyChart) {
          this.monthlyChart.dispose();
        }
        // 重新初始化图表
        this.monthlyChart = echarts.init(this.$refs.monthlyChart);
        this.loadMonthlyReport();
      }
    });
  },

    getDetail() {
      this.loading = true;
      getUser(this.$route.params.userId).then(response => {
        this.detail = response.data;
      }).finally(() => {
        this.loading = false;
      });
    },

    handleUpdate() {
      this.form = { ...this.detail };
      if (this.form.userType === '01') {
        this.form.serviceFeeProportion = this.form.serviceFeeProportion * 100;
      }
      if (this.form.userType === '05') {
        this.form.dividendProportion = this.form.dividendProportion * 100;
      }
      this.open = true;
      this.title = "修改用户";
    },

    handleUpdateRisk() {
      this.showConfigDialog = true;
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.form = {
        userId: undefined,
        userName: undefined,
        phonenumber: undefined,
        status: "0",
        userType: undefined,
        serviceFeeProportion: 0,
        dividendStatus: "1",
        dividendProportion: 0,
        remark: undefined
      };
      this.resetForm("form");
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitData = { ...this.form };
          if (submitData.userType === '01') {
            submitData.serviceFeeProportion = submitData.serviceFeeProportion / 100;
          }
          if (submitData.userType === '05') {
            submitData.dividendProportion = submitData.dividendProportion / 100;
          }

          updateUser(submitData).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getDetail();
          });
        }
      });
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    loadDailyReport() {
      this.dailyReportData = Array.from({ length: 7 }, (_, i) => {
        const date = new Date();
        date.setDate(date.getDate() - i);
        return {
          date: this.formatDate(date),
          rechargeAmount: Math.floor(Math.random() * 10000),
          consumeAmount: Math.floor(Math.random() * 8000),
          orderCount: Math.floor(Math.random() * 100)
        };
      }).reverse();

      const option = {
        title: {
          text: '日报表统计'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['充值金额', '消费金额', '订单数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.dailyReportData.map(item => item.date)
        },
        yAxis: [
          {
            type: 'value',
            name: '金额',
            axisLabel: {
              formatter: '{value} 元'
            }
          },
          {
            type: 'value',
            name: '订单数',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '充值金额',
            type: 'bar',
            data: this.dailyReportData.map(item => item.rechargeAmount)
          },
          {
            name: '消费金额',
            type: 'bar',
            data: this.dailyReportData.map(item => item.consumeAmount)
          },
          {
            name: '订单数',
            type: 'line',
            yAxisIndex: 1,
            data: this.dailyReportData.map(item => item.orderCount)
          }
        ]
      };

      if (this.dailyChart) {
        this.dailyChart.setOption(option);
      }
    },

    loadMonthlyReport() {
      const [year, month] = this.selectedMonth.split('-');
      const daysInMonth = new Date(year, month, 0).getDate();

      // 生成月度数据
      this.monthlyReportData = Array.from({ length: daysInMonth }, (_, i) => {
        return {
          date: `${this.selectedMonth}-${String(i + 1).padStart(2, '0')}`,
          rechargeAmount: Math.floor(Math.random() * 10000),
          consumeAmount: Math.floor(Math.random() * 8000)
        };
      });

      // 更新图表配置
      const option = {
        title: {
          text: '月度统计'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          }
        },
        legend: {
          data: ['充值金额', '消费金额']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false, // 改为 false，让线条从起点开始
          data: this.monthlyReportData.map((_, index) => index + 1),
          axisLabel: {
            formatter: '{value}日'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}元'
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '充值金额',
            type: 'line',
            symbol: 'circle', // 数据点的形状
            symbolSize: 6,    // 数据点的大小
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 2
                }
              }
            },
            areaStyle: {
              opacity: 0.1
            },
            data: this.monthlyReportData.map(item => item.rechargeAmount)
          },
          {
            name: '消费金额',
            type: 'line',
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 2
                }
              }
            },
            areaStyle: {
              opacity: 0.1
            },
            data: this.monthlyReportData.map(item => item.consumeAmount)
          }
        ]
      };

      if (this.monthlyChart) {
        this.monthlyChart.setOption(option);
      }
    },
  }
};
</script>
<style scoped lang="scss">
.detail-tabs {
  margin-top: 20px;

  .search-form {
    margin-bottom: 20px;

    .el-form-item {
      margin-bottom: 10px;
    }
  }
}

/* 保持原有样式不变 */
.detail-row {
  display: flex;
  margin: 0 -6px;
}

.detail-row>.el-col {
  display: flex;
  padding: 0 6px;
}

.detail-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.box-card {
  width: 100%;
  height: 100%;
}

.user-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-description {
  flex: 1;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 4px;
  padding: 15px;
  display: flex;
  align-items: flex-start;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  margin-bottom: 20px;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
}

.stat-icon i {
  font-size: 20px;
  color: #fff;
}

/* 图标背景色 */
.stat-icon.blue {
  background: linear-gradient(135deg, #409EFF, #36D1DC);
}

.stat-icon.pink {
  background: linear-gradient(135deg, #FF9A9E, #FAD0C4);
}

.stat-icon.cyan {
  background: linear-gradient(135deg, #20B2AA, #90EE90);
}

.stat-icon.green {
  background: linear-gradient(135deg, #84FAB0, #8FD3F4);
}

.stat-icon.purple {
  background: linear-gradient(135deg, #E0C3FC, #8EC5FC);
}

.stat-icon.orange {
  background: linear-gradient(135deg, #FFF1B3, #FFD194);
}

.stat-icon.red {
  background: linear-gradient(135deg, #FF6B6B, #FF8E8E);
}

.stat-icon.brown {
  background: linear-gradient(135deg, #D4A373, #E6B17E);
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.report-container {
  padding: 15px;
}

.filter-section {
  margin-bottom: 15px;
}

.chart-container {
  margin-bottom: 0px;
}

.table-container {
  margin-top: 20px;
}

.user-header {
  text-align: center;
  margin: 0 2em;
}

.user-header .name-box {
  margin: 0 auto;
  width: fit-content;
}

.user-name {
  font-size: 18px;
  line-height: 30px;
  vertical-align: center;
}

.phone-number {
  font-size: 18px;
  line-height: 30px;
  color: #9B9B9B;
}

.user-detail {
  position: relative;
  display: flex;
  height: fit-content;
  flex-direction: column;
}

.user-detail .user-description {
  flex: 1;
  margin-top: 16px;
}

.app-container .box-card:nth-child(n + 1) {
  margin-top: 1em;
}

/* 添加新样式 */
.mb-2 {
  margin-bottom: 1rem;
}

.user-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}
</style>
