<script setup>
import ChartCard from '@/components/ChartCard.vue'
import { DataLine } from '@element-plus/icons-vue'
import { useUser } from '@/composables/useAllData'
import { useEvent } from '../composables/useEvent'
import * as api from '../api'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')

const MarketingDialog = defineAsyncComponent(() => import('../components/MarketingDialog.vue'))

const { userValue, userList } = useUser()
const info = ref()
async function fetchInfo() {
  const res = await api.getExperiment()
  info.value = res.data.detail
}
onMounted(fetchInfo)

async function handleStart() {
  fetchEventAction()
  fetchMarketing()
  fetchUser()
}

const loading = computed(() => {
  return loading1.value || loading2.value || loading3.value
})

const { eventValue, eventList } = useEvent()

// 事件行为分析
const loading1 = ref(false)
const eventAction = ref()
const eventActionDate = ref([])
async function fetchEventAction() {
  const [startDate, endDate] = eventActionDate.value
  if (!userValue.value || !eventValue.value || !startDate || !endDate) return
  loading1.value = true
  try {
    const res = await api.getEventAction({ sso_id: userValue.value, start_date: startDate, end_date: endDate, event_id: eventValue.value })
    eventAction.value = res.data
  } finally {
    loading1.value = false
  }
}
const eventActionOption = computed(() => {
  if (!eventAction.value) return
  return {
    grid: { left: '80', top: '40', right: '40', bottom: '60' },
    tooltip: { trigger: 'axis' },
    legend: {
      bottom: '10',
      data: ['行为数量', '用户数量']
    },
    xAxis: {
      type: 'category',
      boundaryGap: ['20%', '20%'],
      data: eventAction.value.event_action_items.map(item => {
        return item.group_name
      })
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '行为数量',
        type: 'line',
        smooth: true,
        label: { show: true, position: 'top' },
        data: eventAction.value.event_action_items.map(item => item.total)
      },
      {
        name: '用户数量',
        type: 'line',
        smooth: true,
        label: { show: true, position: 'top' },
        data: eventAction.value.event_member_items.map(item => item.total)
      }
    ]
  }
})

// 营销漏斗分析
const dialogVisible = ref(false)
const loading2 = ref(false)
const marketing = ref([])
const marketingDate = ref([])
async function fetchMarketing() {
  const [startDate, endDate] = marketingDate.value
  if (!userValue.value || !startDate || !endDate) return
  loading2.value = true
  try {
    const res = await api.getEventMarketing({ sso_id: userValue.value, start_date: startDate, end_date: endDate })
    marketing.value = res.data.items
  } finally {
    loading2.value = false
  }
}
const marketingOption = computed(() => {
  return marketing.value.map((item, index, items) => {
    // 总转换率
    let rate = 0
    if (index === 0) {
      rate = ((items[items.length - 1]?.total / item.total) * 100).toFixed(2)
    } else {
      rate = ((item.total / (items[index - 1]?.total || 0)) * 100).toFixed(2)
    }
    if (isNaN(rate)) rate = 0
    return { ...item, rate }
  })
})

// 用户留存分析
const loading3 = ref(false)
const user = ref([])
const userStartDate = ref('')
const userEndDate = computed(() => {
  return dayjs(userStartDate.value).add(7, 'day').format('YYYY-MM-DD')
})

async function fetchUser() {
  if (!userValue.value || !userStartDate.value || !userEndDate.value) return
  loading3.value = true
  try {
    const res = await api.getMemberList({ sso_id: userValue.value, start_date: userStartDate.value, end_date: userEndDate.value })
    user.value = res.data.items
  } finally {
    loading3.value = false
  }
}

function format(date) {
  return dayjs(date).format('MM-DD (dd)')
}
</script>

<template>
  <AppCard title="营销分析">
    <el-form inline label-suffix="：">
      <el-form-item label="实验名称">{{ info?.name }}</el-form-item>
      <el-form-item label="请选择学生/老师">
        <el-select v-model="userValue" filterable>
          <el-option v-for="item in userList" :label="item.name" :value="item.sso_id" :key="item.sso_id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="DataLine" :loading="loading" @click="handleStart">分析</el-button>
      </el-form-item>
    </el-form>
    <el-divider />
    <el-row :gutter="20">
      <el-col :span="16">
        <ChartCard title="事件行为分析" :options="eventActionOption" :loading="loading1">
          <template #tools>
            <el-date-picker
              type="monthrange"
              v-model="eventActionDate"
              value-format="YYYY-MM"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="width: 200px"
              @change="fetchEventAction"></el-date-picker>
            <p style="white-space: nowrap; margin: 0 5px 0 10px">请选择事件</p>
            <el-select v-model="eventValue" placeholder="请选择事件" style="width: 140px" @change="fetchEventAction">
              <el-option v-for="item in eventList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </template>
        </ChartCard>
        <ChartCard title="用户留存分析" style="margin-top: 20px">
          <template #tools>
            <el-date-picker
              v-model="userStartDate"
              value-format="YYYY-MM-DD"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="fetchUser"></el-date-picker>
          </template>

          <el-table :data="user" border height="290" :headerCellStyle="{ color: '#fff', backgroundColor: '#68bbc4' }">
            <el-table-column prop="date" label="总体" align="center">
              <template #default="{ row }">
                <p>{{ format(row.date) }}</p>
              </template>
            </el-table-column>

            <el-table-column prop="total" label="总人数" align="center">
              <template #default="{ row }">
                <p>{{ row.total }}人</p>
              </template>
            </el-table-column>
            <el-table-column label="当日" align="center">
              <template #default="{ row }">
                <p>{{ row.day0 }}人</p>
                <p class="is-red">{{ row.day0_rate }}%</p>
              </template>
            </el-table-column>
            <template v-for="index in 7" :key="index">
              <el-table-column :label="index === 1 ? '次日' : '第' + index + '日'" align="center">
                <template #default="{ row }">
                  <p>{{ row['day' + index] }}人</p>
                  <p class="is-red">{{ row['day' + index + '_rate'] }}%</p>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </ChartCard>
      </el-col>
      <el-col :span="8">
        <ChartCard title="营销漏斗分析" style="height: 100%">
          <template #tools>
            <el-date-picker
              type="monthrange"
              v-model="marketingDate"
              value-format="YYYY-MM"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="width: 200px"
              @change="fetchMarketing"></el-date-picker>
            <el-button text @click="dialogVisible = true">编辑</el-button>
          </template>
          <div class="card">
            <template v-if="marketingOption.length">
              <div class="item" v-for="(item, index) in marketingOption" :key="index">
                <!-- <div class="item-left">{{ item.group_name }}</div> -->
                <div class="item-center">
                  <p v-if="index === 0">总转换率 {{ item.rate }}%</p>
                  <p v-else>{{ item.rate }}%</p>
                  <div class="circle">{{ item.group_name }}</div>
                </div>
                <div class="item-right">{{ item.total }}人</div>
              </div>
            </template>
            <el-empty v-else />
          </div>
        </ChartCard>
      </el-col>
    </el-row>
    <MarketingDialog v-model="dialogVisible" v-if="dialogVisible"></MarketingDialog>
  </AppCard>
</template>

<style lang="scss" scoped>
.row {
  display: flex;
  gap: 20px;
  & + .row {
    margin-top: 20px;
  }
}
.card {
  margin: 0 20px 20px;
  background-color: #fff;
  padding: 20px;
  min-height: 410px;
  border-radius: 4px;
  .item {
    min-height: 40px;
    display: flex;
    align-items: flex-end;
    border-bottom: 1px solid #ebeef5;
    .item-left {
      padding: 0 10px;
      max-width: 100px;
      font-size: 14px;
      color: #999;
      text-align: center;
    }
    .item-center {
      position: relative;
      margin: 40px 0 0;
      flex: 1;
      height: 40px;
      .circle {
        width: 100%;
        height: 100%;
        font-size: 12px;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        background-color: #1b41a0;
      }
      p {
        position: absolute;
        color: #000;
        top: -30px;
        left: 50%;
        transform: translateX(-50%);
      }
    }
    &:nth-child(1) {
      .circle {
        clip-path: polygon(0 0, 100% 0%, 95% 100%, 5% 100%);
      }
    }
    &:nth-child(2) {
      .circle {
        clip-path: polygon(5% 0, 95% 0%, 90% 100%, 10% 100%);
      }
    }
    &:nth-child(3) {
      .circle {
        clip-path: polygon(10% 0, 90% 0%, 85% 100%, 15% 100%);
      }
    }
    &:nth-child(4) {
      .circle {
        clip-path: polygon(15% 0, 85% 0%, 80% 100%, 20% 100%);
      }
    }
    &:nth-child(5) {
      .circle {
        clip-path: polygon(20% 0, 80% 0%, 75% 100%, 25% 100%);
      }
    }
    .item-right {
      font-size: 14px;
      color: #999;
      text-align: right;
    }
  }
}
.is-red {
  color: var(--main-color);
}
</style>
