<template>
  <div v-loading="loading">
    <div class="data-board">
      <!-- 标题与提示 -->
      <div class="board-header">数据统计-大数据看板</div>
      <!-- 筛选区域 -->
      <div class="filter-bar">
        <!-- 客户关键词搜索 -->
        <el-input
          v-model="searchKey"
          @blur="getEcharts"
          @keyup.enter="getEcharts"
          placeholder="请输入客户关键词"
          clearable
          class="filter-item"
        >
          <template #suffix>
            <i class="el-icon-arrow-down" @click="openSearchDropdown"></i>
          </template>
        </el-input>

        <!-- 统计维度筛选 -->
        <el-select
          v-model="statType"
          placeholder="请选择"
          class="filter-item"
          @change="handleStatChange"
        >
          <el-option label="请选择" value="" />
          <el-option label="年统计" value="year" />
          <el-option label="月统计" value="month" />
          <el-option label="日统计" value="day" />
        </el-select>

        <!-- 时间范围选择 -->
        <el-date-picker
          v-model="timeRange"
          :type="pickerType"
          range-separator="至"
          :start-placeholder="startPlaceholderype"
          :end-placeholder="endPlaceholder"
          :format="format"
          :value-format="valueFormat"
          class="filter-item"
          @change="getPickerValue"
        />
      </div>
    </div>
    <card ref="cardRef" :homeInfoFirst="homeInfoFirst" />
    <div class="page-container">
      <div class="top top_1">
        <div>
          <BarChart
            :title="homeInfoBfztjVal"
            :xData="homeInfoBfztj?.weeks"
            :yData="homeInfoBfztj?.visitCounts"
            seriesName="拜访量"
            color="#a9d672"
            height="350px"
            width="100%"
          />
        </div>
        <div>
          <LineChart
            :title="homeInfoBfrtjVal"
            :xData="homeInfoBfrtj?.dates"
            :yData="homeInfoBfrtj?.counts"
            seriesName="访问量"
            color="#5793f3"
            height="350px"
          />
        </div>
      </div>

      <div class="top top_2">
        <div>
          <PieChart :data="homeInfoKhxzdjzbqk" :total="homeInfoKhxzdjzbqkTotal" tooltipTip="客户性质等级占比情况" />
        </div>
        <div>
          <BarChart_1
            :data="homeInfoBfrjfbqk"
            title="拜访人均分布情况"
            width="600px"
            height="400px"
          />
        </div>
      </div>
      <div class="top top_3">
        <div>
          <PieChart :data="homeInfoKhbffszbqk" :total="homeInfoKhbffszbqkTotal" tooltipTip="客户拜访方式占比情况" />
        </div>
        <div>
          <PieChart :data="homeInfoKhbmzbqk" :total="homeInfoKhbmzbqkTotal" tooltipTip="客户部门占比情况" />
        </div>
        <div>
          <PieChart :data="homeInfoKhbflxzbqk" :total="homeInfoKhbflxzbqkTotal" tooltipTip="客户拜访类型占比情况" />
        </div>
      </div>
      <BarChart_1
        :data="homeInfoBfcplxzbqk"
        title="拜访产品类型占比情况"
        width="100%"
        height="400px"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import card from './card.vue'
// import chartsCard from './chartsCard.vue'
import { homesApi } from '@/api/visit/home'
import BarChart from './components/BarChart.vue'
import BarChart_1 from './components/barChart_1.vue'
import LineChart from './components/LineChart.vue'
import PieChart from './components/PieChart.vue'
import { log } from 'console'
const searchKey = ref('')
const statType = ref('')
const timeRange = ref<[string, string] | []>([]) // 实际存储时间戳或标准格式
const pickerType = ref('daterange')
const startPlaceholderype = ref('开始日期')
const endPlaceholder = ref('结束日期')
const format = ref('YYYY年MM月DD日')
const valueFormat = ref('YYYY-MM-DD')
// const pieData = ref([
//   { name: '电话', value: 765, color: '#5793f3' },
//   { name: '上门', value: 560, color: '#a9d672' },
//   { name: '社交网络', value: 400, color: '#fac858' },
//   { name: '推广渠道', value: 200, color: '#f96c6a' },
//   { name: '其他', value: 120, color: '#c2a6f2' }
// ])
// const chartData_1 = ref([
//   { name: '业务员1', value: 78, color: '#fcd36e' },
//   { name: '业务员2', value: 68, color: '#f28b8b' },
//   { name: '业务员3', value: 50, color: '#a491f2' },
//   { name: '业务员4', value: 42, color: '#fbbc58' },
//   { name: '业务员5', value: 32, color: '#7ecb5c' },
//   { name: '业务员6', value: 30, color: '#68c0cf' },
//   { name: '业务员7', value: 28, color: '#66b1fc' }
// ])
const handleStatChange = (val: string) => {
  console.log('切换统计维度：', val)
  timeRange.value = []
  if (val == 'year') {
    pickerType.value = 'yearrange'
    startPlaceholderype.value = '开始年份'
    endPlaceholder.value = '结束年份'
    format.value = 'YYYY年'
    valueFormat.value = 'YYYY'
  } else if (val == 'month') {
    pickerType.value = 'monthrange'
    startPlaceholderype.value = '开始月份'
    endPlaceholder.value = '结束月份'
    format.value = 'YYYY年MM月'
    valueFormat.value = 'YYYY-MM'
  } else {
    pickerType.value = 'daterange'
    startPlaceholderype.value = '开始日期'
    endPlaceholder.value = '结束日期'
    format.value = 'YYYY年MM月DD日'
    valueFormat.value = 'YYYY-MM-DD'
  }
  // 调用接口，根据 statType 和 timeRange 获取数据
  getEcharts()
}
const openSearchDropdown = () => {
  // 打开下拉菜单（如筛选条件、历史记录等）
  console.log('打开搜索下拉')
}
// 获取日期
const getPickerValue = (e: any) => {
  console.log(e)
}
// 图表数据
// 加载状态
const loading = ref(false)
// 错误信息
const error = ref('')

// 各图表数据存储
const homeInfoFirst: Ref<any | null> = ref(null)
const homeInfoBfztj: Ref<any | null> = ref(null)
const homeInfoBfrtj: Ref<any | null> = ref(null)
const homeInfoKhxzdjzbqk: Ref<any | null> = ref([])
const homeInfoBfrjfbqk: Ref<any | null> = ref([])
const homeInfoKhbffszbqk: Ref<any | null> = ref([])
const homeInfoKhbmzbqk: Ref<any | null> = ref([])
const homeInfoKhbflxzbqk: Ref<any | null> = ref([])
const homeInfoBfcplxzbqk: Ref<any | null> = ref([])
const homeInfoBfztjVal = ref('拜访周统计')
const homeInfoBfrtjVal = ref('拜访日统计')

const homeInfoKhxzdjzbqkTotal: Ref<any | null> = ref('')
const homeInfoKhbflxzbqkTotal: Ref<any | null> = ref('')
const homeInfoKhbmzbqkTotal: Ref<any | null> = ref('')
const homeInfoKhbffszbqkTotal: Ref<any | null> = ref('')
// 获取图表数据
const getEcharts = async () => {
  error.value = ''
  if (loading.value) return // ✅ 防止重复调用
  loading.value = true

  const params: any = {
    companyName: searchKey.value,
    searchTimeString: timeRange.value
  }

  try {
    const allTasks = [
      homesApi.getHomeInfoFirst(params).then((res) => {
        homeInfoFirst.value = res
        console.log('卡片数据:', res)
      }),

      homesApi.getHomeInfoBfztj(params).then((res) => {
        homeInfoBfztj.value = res
        console.log('竖柱状图数据:', res)
      }),

      homesApi.getHomeInfoBfrtj(params).then((res) => {
        homeInfoBfrtj.value = res
        console.log('折线图数据:', res)
      }),

      homesApi.getHomeInfoKhxzdjzbqk(params).then((res) => {
        if (res.list.length) {
          const allNum = res.list.map((item) => item.value) // [20, 30]
          const sum = allNum.reduce((acc, cur) => acc + cur, 0) // 50

          res.list.forEach((item: any, index: number) => {
            // 防御性获取 allNum 值
            const allNumVal = allNum?.[index] ?? '未知'
            // 避免除以 0
            const ratio = sum !== 0 ? ((item.value / sum) * 100).toFixed(1) + '%' : '0%'

            // 拼接名称（清晰分隔符）
            item.name = `${item.name}   ${allNumVal}   ${ratio}`
          })
        }
        homeInfoKhxzdjzbqkTotal.value=res.total
        homeInfoKhxzdjzbqk.value = res.list
        console.log('客户性质等级占比:', res.list)
      }),

      homesApi.getHomeInfoBfrjfbqk(params).then((res) => {
        homeInfoBfrjfbqk.value = res.list
        console.log('拜访人均分布:', res)
      }),

      homesApi.getHomeInfoKhbffszbqk(params).then((res) => {
        if (res.list.length) {
          const allNum = res.list.map((item) => item.value) // [20, 30]
          const sum = allNum.reduce((acc, cur) => acc + cur, 0) // 50

          res.list.forEach((item: any, index: number) => {
            // 防御性获取 allNum 值
            const allNumVal = allNum?.[index] ?? '未知'
            // 避免除以 0
            const ratio = sum !== 0 ? ((item.value / sum) * 100).toFixed(1) + '%' : '0%'

            // 拼接名称（清晰分隔符）
            item.name = `${item.name}   ${allNumVal}   ${ratio}`
          })
        }
        homeInfoKhbffszbqkTotal.value=res.total
        homeInfoKhbffszbqk.value = res.list
        console.log('客户拜访方式占比:', res)
      }),

      homesApi.getHomeInfoKhbmzbqk(params).then((res) => {
        if (res.list.length) {
          const allNum = res.list.map((item) => item.value) // [20, 30]
          const sum = allNum.reduce((acc, cur) => acc + cur, 0) // 50

          res.list.forEach((item: any, index: number) => {
            // 防御性获取 allNum 值
            const allNumVal = allNum?.[index] ?? '未知'
            // 避免除以 0
            const ratio = sum !== 0 ? ((item.value / sum) * 100).toFixed(1) + '%' : '0%'

            // 拼接名称（清晰分隔符）
            item.name = `${item.name}   ${allNumVal}   ${ratio}`
          })
        }
        homeInfoKhbmzbqkTotal.value=res.total
        homeInfoKhbmzbqk.value = res.list
        console.log('客户部门占比:', res)
      }),

      homesApi.getHomeInfoKhbflxzbqk(params).then((res) => {
        if (res.list.length) {
          const allNum = res.list.map((item) => item.value) // [20, 30]
          const sum = allNum.reduce((acc, cur) => acc + cur, 0) // 50

          res.list.forEach((item: any, index: number) => {
            // 防御性获取 allNum 值
            const allNumVal = allNum?.[index] ?? '未知'
            // 避免除以 0
            const ratio = sum !== 0 ? ((item.value / sum) * 100).toFixed(1) + '%' : '0%'

            // 拼接名称（清晰分隔符）
            item.name = `${item.name}   ${allNumVal}   ${ratio}`
          })
        }
        homeInfoKhbflxzbqkTotal.value=res.total
        homeInfoKhbflxzbqk.value = res.list
        console.log('客户拜访类型占比:', res)
      }),

      homesApi.getHomeInfoBfcplxzbqk(params).then((res) => {
        if (res.list.length) {
          const allNum = res.list.map((item) => item.value) // [20, 30]
          const sum = allNum.reduce((acc, cur) => acc + cur, 0) // 50

          res.list.forEach((item: any, index: number) => {
            // 防御性获取 allNum 值
            const allNumVal = allNum?.[index] ?? '未知'
            // 避免除以 0
            const ratio = sum !== 0 ? ((item.value / sum) * 100).toFixed(1) + '%' : '0%'

            // 拼接名称（清晰分隔符）
            item.name = `${item.name}   ${allNumVal}   ${ratio}`
          })
        }
        homeInfoBfcplxzbqk.value = res.list
        console.log('拜访产品类型占比:', res)
      })
    ]

    const results = await Promise.allSettled(allTasks)

    results.forEach((result, index) => {
      if (result.status === 'rejected') {
        console.error(`第 ${index + 1} 个接口调用失败：`, result.reason)
        error.value = '部分数据获取失败'
      }
    })
  } catch (err) {
    console.error('请求异常:', err)
    error.value = '数据获取出错，请重试'
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getEcharts()
})
watch(timeRange, (newVal: any) => {
  getEcharts()
})
</script>
<style scoped lang="scss">
/* 自定义 Element Plus 组件样式 */
.filter-item {
  width: 200px;
}
.data-board {
  display: flex;
  .board-header {
    margin-right: 200px;
  }
  .filter-bar {
    display: flex;
    align-items: center;
    // justify-content: space-around;
    width: 70%;
    .el-date-editor {
      margin-left: 30px;
      flex: none;
    }
  }
}
.page-container {
  padding: 20px;
}

h3 {
  margin-top: 30px;
}
.top {
  display: flex;
  > div {
    padding: 20px;
    margin: 10px;
    border: 1px dashed #999;
  }
}
.top_1 {
  > div {
    flex: 1;
  }
}
.top_2 {
  > div {
    flex: 1;
  }
}
.top_3 {
  justify-content: space-between;
  // flex-wrap: wrap;
  > div {
    width: 32%;
  }
}
</style>
