<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000px">
    <el-form :model="searchForm" label-width="0" inline>
      <el-form-item>
        <el-date-picker
          v-model="searchForm.consultTime"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="选择日期"
          end-placeholder="选择日期"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item>
        <el-tree-select
          v-model="searchForm.sourceId"
          :data="props.sourceOptions"
          :props="defaultProps"
          check-strictly
          clearable
          node-key="sourceId"
          placeholder="请选择渠道"
          @change="sourceChange"
        />
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.licenseType" placeholder="选择驾照类型" clearable>
          <el-option
            v-for="item in props.licenseTypeOptions"
            :key="item.label"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="showPane" class="pb-10px">
      <el-tab-pane label="详细数据" :name="1">
        <el-table v-loading="loading" :data="tableList" border stripe>
          <el-table-column prop="sourceName" label="渠道名称" width="100" fixed="left" />
          <el-table-column prop="newClueNumber" label="新线索数" sortable min-width="100" />
          <el-table-column prop="signNumber" label="成交数" sortable min-width="100" />
          <el-table-column prop="signRate" label="成交率" sortable min-width="100" />
          <el-table-column prop="averageSignPeriod" label="成交周期" sortable min-width="100" />
          <el-table-column
            prop="grossProfitOfSingleSign"
            label="毛利/单"
            sortable
            min-width="100"
          />
          <el-table-column prop="payPriceOfSingleSign" label="支出/单" sortable min-width="100" />
          <el-table-column prop="costOfSingleClue" label="线索成本/条" sortable min-width="100" />
          <el-table-column
            prop="netProfitOfSingleSign"
            label="净利润/单"
            sortable
            min-width="100"
          />
          <el-table-column label="总线索成本" prop="clueCostTotal" sortable min-width="100" />
          <el-table-column label="总支出" prop="payPriceTotal" sortable min-width="100" />
          <el-table-column label="总利润" prop="profitTotal" sortable min-width="100" />
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="图表展示" :name="2" lazy>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-checkbox-group v-model="showChannel" @change="setReportData">
              <el-checkbox v-for="(item, index) in channelArr" :key="index" :label="item" />
            </el-checkbox-group>
          </el-col>

          <el-col :span="12" :offset="0">
            <el-skeleton :loading="loading" animated>
              <Echart :options="echart1Option" width="100%" :height="400" />
            </el-skeleton>
          </el-col>
          <el-col :span="12" :offset="0">
            <Echart :options="echart2Option" width="100%" :height="400" />
          </el-col>
          <el-col :span="24" :offset="0">
            <Echart :options="echart3Option" width="100%" :height="400" />
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </Dialog>
</template>

<script setup name="DialogSalerReportDetail">
import { set } from 'lodash-es'
import * as reportApi from '@/api/home/reportSaler'
import { getIntDictOptions } from '@/utils/dict'
import { removeNullField } from '@/utils'

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

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

const showChannel = ref([])
const intentionOptions = getIntDictOptions('intention_state')

const channelArr = computed(() => {
  if (searchForm.value.sourceId) {
    let arr =
      props.sourceOptions.find((it) => it.sourceId == searchForm.value.sourceId)?.children || []
    return arr.map((it) => it.sourceName)
  } else {
    return props.sourceOptions.map((it) => it.sourceName)
  }
})

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const loading = ref(false)
const searchForm = ref({})

const showPane = ref(1)

function handleReset() {
  searchForm.value = {
    nickname: undefined,
    consultTime: []
  }
}

/** 打开弹窗 */
const open = async (info, queryInfo) => {
  showPane.value = 1
  dialogVisible.value = true
  dialogTitle.value = info.nickname
  searchForm.value = { ...queryInfo }
  searchForm.value.userId = info.userId

  sourceChange()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const tableList = ref([])

async function handleSearch() {
  loading.value = true
  try {
    const params = { ...searchForm.value }
    const data = await reportApi.getInfo(removeNullField(params))
    tableList.value = data.sourceDetailVOList
    setReportData(data)
  } finally {
    loading.value = false
  }
}

function sourceChange() {
  handleSearch()
  showChannel.value = channelArr.value
}

const echart1Option = ref({
  title: {
    text: '线索分布图'
  },
  radiusAxis: {},
  angleAxis: {},
  tooltip: {
    show: true,
    formatter: '{b0}-{a}: {c}'
  },
  polar: {},
  legend: {
    show: true,
    type: 'scroll',
    left: 100
  }
})

const echart2Option = ref({
  title: {
    text: '成交分布图'
  },
  radiusAxis: {},
  angleAxis: {},
  tooltip: {
    show: true,
    formatter: '{b0}-{a}: {c}'
  },
  polar: {},
  legend: {
    show: true,
    type: 'scroll',
    left: 100
  }
})

const echart3Option = ref({
  title: {
    text: '销售雷达图'
  },
  radar: {
    indicator: [
      { name: '成交周期' },
      { name: '毛利/单' },
      { name: '支出/单' },
      { name: '线索成本/条' },
      { name: '净利润/单' },
      { name: '成交率' }
      // { name: '线索总成本' },
      // { name: '总支出' },
      // { name: '总利润' }
    ]
  },
  legend: {
    show: true,
    right: '10px',
    orient: 'vertical'
  }
})

const setReportData = async (data) => {
  // const data = await HomeApi.getClueSignSignRate()

  const channelClueArr = showChannel.value.sort((pre, cur) => {
    const preArr = tableList.value.find((it) => it.sourceName == pre).clueIntentionNumVOList || []
    const curArr = tableList.value.find((it) => it.sourceName == cur).clueIntentionNumVOList || []
    const preCount = preArr.reduce((preVal, curVal) => preVal + curVal.intentionNum, 0)
    const curCount = curArr.reduce((preVal, curVal) => preVal + curVal.intentionNum, 0)
    return preCount - curCount
  })

  const arr1 = intentionOptions.map((intention) => {
    const list = []
    channelClueArr.map((item) => {
      const row = tableList.value.find((it) => item == it.sourceName)
      if (row) {
        list.push(
          row.clueIntentionNumVOList.find((it) => it.intentionState == intention.value).intentionNum
        )
      }
    })
    return {
      type: 'bar',
      data: list,
      coordinateSystem: 'polar',
      name: intention.label,
      stack: 'a',
      emphasis: {
        focus: 'series'
      },
      label: {
        show: true,
        position: 'middle'
      }
    }
  })

  const channelSignArr = showChannel.value.sort((pre, cur) => {
    const preArr = tableList.value.find((it) => it.sourceName == pre).signLicenseTypeNumVOList || []
    const curArr = tableList.value.find((it) => it.sourceName == cur).signLicenseTypeNumVOList || []
    const preCount = preArr.reduce((preVal, curVal) => preVal + curVal.licenseTypeNum, 0)
    const curCount = curArr.reduce((preVal, curVal) => preVal + curVal.licenseTypeNum, 0)
    return preCount - curCount
  })
  const arr2 = props.licenseTypeOptions.map((cartype) => {
    const list = []
    channelClueArr.map((item) => {
      const row = tableList.value.find((it) => item == it.sourceName)
      if (row) {
        list.push(
          row.signLicenseTypeNumVOList.find((it) => it.licenseType == cartype.label).licenseTypeNum
        )
      }
    })
    return {
      type: 'bar',
      data: list,
      coordinateSystem: 'polar',
      name: cartype.label,
      stack: 'a',
      emphasis: {
        focus: 'series'
      },
      label: {
        show: true,
        position: 'middle'
      }
    }
  })

  set(echart1Option.value, 'radiusAxis', {
    type: 'category',
    data: channelClueArr,
    axisLabel: {
      margin: 5,
      fontSize: 10,
      interval: 0
    }
  })

  set(echart1Option.value, 'series', arr1)

  set(echart2Option.value, 'radiusAxis', {
    type: 'category',
    data: channelSignArr,
    axisLabel: {
      margin: 5,
      fontSize: 10,
      interval: 0
    }
  })
  set(echart2Option.value, 'series', arr2)
  const { personDetail, averageDetail } = data
  set(echart3Option.value, 'series', [
    {
      type: 'radar',
      data: [
        {
          value: [
            averageDetail.averageSignPeriod,
            averageDetail.grossProfitOfSingleSign,
            averageDetail.payPriceOfSingleSign,
            averageDetail.costOfSingleClue,
            averageDetail.netProfitOfSingleSign,
            averageDetail.signRate
            // averageDetail.clueCostTotal,
            // averageDetail.payPriceTotal,
            // averageDetail.profitTotal
          ],
          name: '平均水平',
          lineStyle: {
            type: 'dashed'
          },
          areaStyle: {
            color: 'rgba(0, 191, 255, 0.6)'
          },
          label: {
            show: true
          }
        },
        {
          value: [
            personDetail.averageSignPeriod,
            personDetail.grossProfitOfSingleSign,
            personDetail.payPriceOfSingleSign,
            personDetail.costOfSingleClue,
            personDetail.netProfitOfSingleSign,
            averageDetail.signRate
            // personDetail.clueCostTotal,
            // personDetail.payPriceTotal,
            // personDetail.profitTotal
          ],
          name: dialogTitle.value,
          areaStyle: {
            color: 'rgba(255, 145, 124, 0.4)'
          },
          label: {
            show: true
          }
        }
      ]
    }
  ])
}
</script>

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