<script setup lang="ts">
import { QuestionFilled } from '@element-plus/icons-vue'
import { useUserAttr, useMetaEvent, useUserAttrRange } from '@/composables/useRFMData'
import { searchMetaMemberAttrs } from '@/api/base'
import { cloneDeep } from 'lodash-es'

defineProps<{ label: string }>()
const form = defineModel<any>()

const ruleList = [
  { label: '属性值平均法', value: '101', basis: ['1'] },
  { label: '属性值分类法', value: '102', basis: ['1'] },
  { label: '事件发生次数平均法', value: '201', basis: ['2'] },
]

const defaultLevel = [
  { level: '高', value: '' },
  { level: '低', value: '' },
]

const defaultScore = [
  { score: 1, min_value: '', max_value: '' },
  { score: 2, min_value: '', max_value: '' },
  { score: 3, min_value: '', max_value: '' },
  { score: 4, min_value: '', max_value: '' },
  { score: 5, min_value: '', max_value: '' },
]

onMounted(() => {
  form.value = Object.assign(
    {
      basis: '1',
      rule: '101',
      event_id: '-1',
      attr_id: '',
      attr_type: '',
      config: cloneDeep(defaultScore),
      extend_config: { default_score_config: { switch: false, score: undefined } },
    },
    form.value
  )
})

const { userAttrList, fetchUserAttrList } = useUserAttr()
const { metaEventList, fetchMetaEventList } = useMetaEvent()
const { userAttrRange, fetchUserAttrRange } = useUserAttrRange()

const currentRuleList = computed(() => {
  return ruleList.filter((item) => item.basis.includes(form.value.basis))
})

const currentMetaEventList = computed(() => {
  return [{ event_id: '-1', event_name: '所有事件' }, ...metaEventList.value]
})

function handleBasisChange(value: any) {
  if (value === '1') {
    form.value.rule = '101'
  } else {
    form.value.rule = '201'
  }
  // 清空数据
  Object.assign(
    form.value,
    cloneDeep({
      event_id: '-1',
      attr_id: '',
      attr_type: '',
      config: defaultScore,
      extend_config: { default_score_config: { switch: false, score: undefined } },
    })
  )
  handleRuleChange(form.value.rule)
}

function handleRuleChange(value: any) {
  if (value === '102') {
    form.value.config = cloneDeep(defaultLevel)
  } else {
    form.value.config = cloneDeep(defaultScore)
  }
  form.value.attr_id = ''
}

function handleAttrChange(value: any) {
  form.value.attr_type = userAttrList.value.find((item) => item.id === value)?.type
}

const options = ref<{ label: string; value: string }[]>([])
const loading = ref(false)
async function remoteMethod(search: string = '') {
  options.value = []
  if (form.value.attr_id) {
    loading.value = true
    await searchMetaMemberAttrs({ search, member_meta_id: form.value.attr_id, per_page: 100 }).then((res) => {
      options.value = res.data.list.map((item: any) => {
        return { label: item.attr_value, value: item.attr_value }
      })
    })
    loading.value = false
  }
}

function querySearch(queryString: string, cb: any) {
  cb(options.value)
}

watch(
  () => form.value.attr_id,
  (attrId) => {
    if (form.value.rule === '102') {
      remoteMethod()
    } else {
      attrId && fetchUserAttrRange(attrId)
    }
  },
  { immediate: true }
)

watch(
  () => form.value.rule,
  () => {
    const type = form.value.rule === '102' ? 1 : 2
    form.value.basis === '1' ? fetchUserAttrList(type) : fetchMetaEventList(type)
  },
  { immediate: true }
)

const a = [
  { id: '001', label: '2000' },
  { id: '002', label: '1500' },
  { id: '003', label: '3000' },
  { id: '004', label: '2200' },
  { id: '005', label: '1800' },
]

const defaultOptions = Array.from({ length: 5 }).map((_, index) => ({ value: index + 1, label: index + 1 }))
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="rfm-top">
        <div>
          <el-button circle type="primary" style="width: 32px; margin-right: 10px">{{ label }}</el-button>
          {{ label }}值计算规则
        </div>
        <div>
          <slot name="header-aside" :data="form"></slot>
        </div>
      </div>
    </template>
    <div class="rfm-header">
      <p style="margin-right: 10px">{{ label }}值计算依据</p>
      <el-radio-group v-model="form.basis" @change="handleBasisChange">
        <el-radio value="1">用户属性</el-radio>
        <el-radio value="2">事件属性</el-radio>
      </el-radio-group>
      <p style="margin-left: 10px">计算规则：</p>
      <el-select v-model="form.rule" style="width: 170px" @change="handleRuleChange">
        <el-option
          v-for="item in currentRuleList"
          :key="item.value"
          :label="item.label"
          :value="item.value"></el-option>
      </el-select>
      <div class="rfm-tips">
        <el-popover
          popper-class="rfm-popover"
          placement="right"
          title="属性值平均法"
          :width="400"
          trigger="hover"
          v-if="form.rule == '101'">
          <p>
            用于计算选中属性的平均值，通过对选定的字段中的所有记录进行数值相加，然后除以记录的数量来计算的。主要针对“数字”和“整数”两种字段类型。
          </p>
          <p>举例：</p>
          <el-table :data="a" border>
            <el-table-column prop="id" label="用户ID" />
            <el-table-column prop="label" label="销售额" />
          </el-table>
          <p>“销售额”的平均值为：<br />（2000+1500+3000+2200+1800)/5=2100</p>
          <template #reference>
            <el-icon><QuestionFilled /></el-icon>
          </template>
        </el-popover>
        <el-popover
          popper-class="rfm-popover"
          placement="right"
          title="属性值分类法"
          :width="400"
          trigger="hover"
          v-if="form.rule == '102'">
          <p>将数据的属性值按照一定的规则或特性进行分类，本系统中分了“高”和“低”两类。主要针对“字符串”的字段类型。</p>
          <template #reference>
            <el-icon><QuestionFilled /></el-icon>
          </template>
        </el-popover>
        <el-popover
          popper-class="rfm-popover"
          placement="right"
          title="事件发生次数平均法"
          :width="400"
          trigger="hover"
          v-if="form.rule == '201'">
          <p>分析事件发生频率的方法，即通过计算用户事件发生的平均次数。</p>
          <template #reference>
            <el-icon><QuestionFilled /></el-icon>
          </template>
        </el-popover>
      </div>

      <el-select v-model="form.event_id" placeholder="选择事件" style="width: 160px" v-if="form.basis === '2'">
        <el-option
          v-for="item in currentMetaEventList"
          :key="item.event_id"
          :label="item.event_name"
          :value="item.event_id"></el-option>
      </el-select>
      <el-select v-model="form.attr_id" placeholder="选择属性" style="width: 160px" @change="handleAttrChange" v-else>
        <el-option v-for="item in userAttrList" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <div
        style="flex: 1; display: flex; justify-content: space-between"
        v-if="form.basis == 1 && form.rule != '102' && form.attr_id">
        <p>
          最小值：{{ userAttrRange.min }}<br />最大值：{{ userAttrRange.max }}<br />"0"值数量：{{
            userAttrRange.zero_count
          }}
        </p>
        <p>
          平均值：{{ userAttrRange.avg }}<br />中位数：{{ userAttrRange.median }}<br />中位数(不含0)：{{
            userAttrRange.no_zero_median
          }}
        </p>
      </div>
    </div>
    <div class="rfm-header-extra" v-if="form.rule === '101' && form.extend_config">
      <p>未匹配数据默认赋值</p>
      <el-select-v2
        v-model="form.extend_config.default_score_config.score"
        :options="defaultOptions"
        style="width: 100px; margin: 0 10px"
        clearable />
      <el-switch v-model="form.extend_config.default_score_config.switch"></el-switch>
    </div>
    <div class="rfm-body">
      <template v-if="form.rule === '102'">
        <div class="rfm-box" v-for="item in form.config" :key="item.level">
          <div class="rfm-box-header">
            <b>{{ item.level }}</b>
          </div>
          <div class="rfm-box-body">
            <el-autocomplete v-model="item.value" placeholder="选择属性值" :fetch-suggestions="querySearch" />
            <!-- <el-select placeholder="选择属性值" v-model="item.value" filterable allow-create :loading="loading">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select> -->
          </div>
        </div>
      </template>
      <template v-else>
        <div class="rfm-box" v-for="item in form.config" :key="item.score">
          <div class="rfm-box-header">
            <b>{{ item.score }}</b
            >分
          </div>
          <div class="rfm-box-body">
            <el-input v-model="item.min_value" class="rfm-box-input"></el-input>
            ~
            <el-input v-model="item.max_value" class="rfm-box-input"></el-input>
          </div>
        </div>
      </template>
    </div>
  </el-card>
</template>

<style lang="scss">
.rfm-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.rfm-header {
  display: flex;
  align-items: center;
  .el-radio {
    margin-right: 10px;
  }
  .el-select {
    margin-right: 10px;
  }
}
.rfm-body {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
}
.rfm-box {
  padding: 10px;
  text-align: center;
  border-radius: 4px;
  background-color: rgb(240, 240, 240);
}
.rfm-box-header {
  color: var(--main-color);
  margin-bottom: 10px;
  b {
    font-weight: bold;
    font-size: 18px;
  }
}
.rfm-box-input {
  width: 63px;
  .el-input__inner {
    text-align: center;
  }
}
.rfm-tips {
  margin-right: 10px;
}
.rfm-popover {
  p {
    margin: 10px 0;
  }
}
.rfm-header-extra {
  display: flex;
  align-items: center;
}
</style>
