<template>
  <ContentWrap>
    <el-form ref="searchRef" :model="searchForm" :rules="searchRules" label-width="100px" inline>
      <el-form-item label="咨询日期" prop="consultDate">
        <el-date-picker
          v-model="searchForm.consultDate"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="选择日期"
          end-placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="成交周期" prop="periodNumber">
        <el-input-number
          v-model="searchForm.periodNumber"
          :min="1"
          :controls="false"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="渠道来源" prop="sourceId">
        <el-tree-select
          v-model="searchForm.sourceId"
          :data="props.sourceOptions"
          :props="defaultProps"
          check-strictly
          filterable
          node-key="sourceId"
          placeholder="请选择渠道"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="tableList"
      border
      stripe
      :summary-method="getSummaries"
      show-summary
    >
      <el-table-column prop="sourceName" label="渠道名称" />
      <el-table-column prop="newClueSignNum" label="新线索成交数" sortable>
        <template #header>
          <Tooltip message="咨询日期在查询范围内，且在所查成交周期内成交的线索数" />
          <span>新线索成交数</span>
        </template>
      </el-table-column>
      <el-table-column prop="newClueNum" label="新线索总数" sortable>
        <template #header>
          <Tooltip message="咨询日期在查询范围内，咨询的线索数" /> <span>新线索总数</span>
        </template>
      </el-table-column>
      <el-table-column prop="rate" label="新线索成交率" sortable :formatter="parseRate" />
    </el-table>
  </ContentWrap>
</template>

<script setup name="ChannelPeriod">
import { getPeriodList } from '@/api/home/reportChannel'
import { removeNullField } from '@/utils'
import { formatDate } from '@/utils/formatTime'

const props = defineProps({
  sourceOptions: {
    type: Array,
    default: () => []
  }
})

const defaultProps = {
  children: 'children',
  label: 'sourceName',
  value: 'sourceId',
  isLeaf: 'leaf'
}

const searchRef = ref()

const searchRules = {
  // consultDate: { required: true, type: 'array', message: '请选择咨询日期', trigger: 'change,blur' },
  periodNumber: { required: true, message: '请输入成交周期', trigger: 'blur' }
}

onMounted(() => {
  getOptions()
  handleReset()
  handleSearch()
})

const searchForm = ref({})

function handleReset() {
  const date = new Date()
  date.setDate(1)
  searchForm.value = {
    sourceId: undefined,
    periodNumber: 30,
    consultDate: [formatDate(date), formatDate(new Date())]
  }
}

function getOptions() {}

const loading = ref(false)
const tableList = ref([])
async function handleSearch() {
  try {
    const valid = await searchRef.value.validate()
    if (!valid) return
    loading.value = true
    const params = { ...searchForm.value }
    if (params.consultDate && params.consultDate.length) {
      params.startDateTime = params.consultDate[0]
      params.endDateTime = params.consultDate[1]
    }
    const data = await getPeriodList(removeNullField(params))
    tableList.value = data
  } finally {
    loading.value = false
  }
}

function parseRate(row) {
  return Number(row.rate * 100).toFixed(2) + '%'
}

function getSummaries({ columns, data }) {
  let sums = []
  columns.forEach((column, index) => {
    if (index == 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      if (column.property == 'rate') {
        const sum = data.reduce(
          (pre, cur) => ({
            clueNum: pre.clueNum + cur.newClueNum,
            signNum: pre.signNum + cur.newClueSignNum
          }),
          { clueNum: 0, signNum: 0 }
        )
        sums[index] = sum.clueNum > 0 ? ((sum.signNum * 100) / sum.clueNum).toFixed(2) + '%' : 0
      } else {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}
</script>

<style lang="scss" scoped></style>
