import {
  Button,
  Cell,
  Checkbox,
  CheckboxGroup,
  Col,
  DatetimePicker,
  Picker,
  Popup,
  Row
} from 'vant'
import { defineComponent, markRaw } from 'vue'
import styles from './index.module.less'
import * as echarts from 'echarts/core'
import {
  BarChart,
  // 系列类型的定义后缀都为 SeriesOption
  BarSeriesOption,
  LineChart,
  LineSeriesOption
} from 'echarts/charts'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  // 组件类型的定义后缀都为 ComponentOption
  TitleComponentOption,
  TooltipComponent,
  TooltipComponentOption,
  GridComponent,
  GridComponentOption,
  // 数据集组件
  DatasetComponent,
  DatasetComponentOption,
  // 内置数据转换器组件 (filter, sort)
  TransformComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = echarts.ComposeOption<
  | BarSeriesOption
  | LineSeriesOption
  | TitleComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | DatasetComponentOption
>

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  PieChart,
  ToolboxComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart
])

import { lineChartOption, pieChartOption } from './echarts'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import { formatterDate, moneyFormat } from '@/helpers/utils'
import ColHeader from '@/components/col-header'

export const getAssetsHomeFile = (fileName: string) => {
  const path = `./images/${fileName}`
  const modules = import.meta.globEager('./images/*')
  return modules[path].default
}

const yearColumns: any = []
const year = dayjs().year()
let defaultIndex = 10
for (let i = year - 10; i <= year + 10; i++) {
  yearColumns.push({
    text: `${i}年`,
    value: i
  })
}

export default defineComponent({
  name: 'IncomeConsus',
  data() {
    return {
      moneyInfo: {
        totalSingleRate: 0,
        totalShareRate: 0,
        totalInAmount: 0,
        practiceAmount: 0,
        practiceRate: 0,
        liveAmount: 0,
        liveRate: 0,
        videoAmount: 0,
        videoRate: 0,
        musicAmount: 0,
        musicRate: 0,
        vipShareAmount: 0,
        vipShareRate: 0,
        liveShareAmount: 0,
        liveShareRate: 0,
        videoShareAmount: 0,
        videoShareRate: 0,
        mallShareAmount: 0,
        mallShareRate: 0,
        musicShareAmount: 0,
        musicShareRate: 0,
        albumShareAmount: 0,
        albumShareRate: 0,
        actiRegistShareAmount: 0,
        actiRegistShareRate: 0
      },
      params: {
        timeType: 'YEAR' as 'YEAR' | 'MONTH',
        dateTime: `${year}`
      },
      dateTimeStr: `${year}年`,
      myChart: null as any,
      myChart2: null as any,
      timerStatus: false,
      currentDate: new Date()
    }
  },
  async mounted() {
    this.myChart = markRaw(
      echarts.init(document.getElementById('incomeClass') as HTMLDivElement)
    )
    this.myChart2 = markRaw(
      echarts.init(document.getElementById('structrueClass') as HTMLDivElement)
    )
    this.getList()
  },
  methods: {
    async getList() {
      try {
        const params = this.params
        const res = await request.post(
          '/api-teacher/userAccount/accountTotal',
          {
            data: params
          }
        )
        const result = res.data || {}
        this.moneyInfo = {
          totalSingleRate: Number(
            (
              result.practiceRate +
              result.liveRate +
              result.videoRate +
              result.musicRate
            ).toFixed(2)
          ),
          totalShareRate: Number(
            (
              result.vipShareRate +
                result.liveShareRate +
                result.videoShareRate +
                result.musicShareRate +
                result.mallShareRate +
                result.actiRegistShareRate +
                result.albumShareRate || 0
            ).toFixed(2)
          ),
          totalInAmount: result.totalInAmount || 0,
          practiceAmount: result.practiceAmount || 0,
          practiceRate: result.practiceRate || 0,
          liveAmount: result.liveAmount || 0,
          liveRate: result.liveRate || 0,
          videoAmount: result.videoAmount || 0,
          videoRate: result.videoRate || 0,
          musicAmount: result.musicAmount || 0,
          musicRate: result.musicRate || 0,
          vipShareAmount: result.vipShareAmount || 0,
          vipShareRate: result.vipShareRate || 0,
          liveShareAmount: result.liveShareAmount || 0,
          liveShareRate: result.liveShareRate || 0,
          videoShareAmount: result.videoShareAmount || 0,
          videoShareRate: result.videoShareRate || 0,
          mallShareAmount: result.mallShareAmount || 0,
          mallShareRate: result.mallShareRate || 0,
          musicShareAmount: result.musicShareAmount || 0,
          musicShareRate: result.musicShareRate || 0,
          albumShareAmount: result.albumShareAmount || 0,
          albumShareRate: result.albumShareRate || 0,
          actiRegistShareAmount: result.actiRegistShareAmount || 0,
          actiRegistShareRate: result.actiRegistShareRate || 0
        }
        console.log(this.moneyInfo)
        // 处理折线图数据
        const lineData = {
          xAxis: [] as any,
          practiceAmount: [] as any,
          liveAmount: [] as any,
          videoAmount: [] as any,
          musicAmount: [] as any,
          vipShareAmount: [] as any,
          liveShareAmount: [] as any,
          videoShareAmount: [] as any,
          mallShareAmount: [] as any,
          musicShareAmount: [] as any,
          albumShareAmount: [] as any,
          actiRegistShareAmount: [] as any
        }
        ;(result.infoList || []).forEach((item: any) => {
          if (params.timeType === 'YEAR') {
            lineData.xAxis.push(dayjs(item.timeStr).format('MM月'))
          } else if (params.timeType === 'MONTH') {
            lineData.xAxis.push(dayjs(item.timeStr).format('DD日'))
          }
          lineData.practiceAmount.push(item.practiceAmount)
          lineData.liveAmount.push(item.liveAmount)
          lineData.videoAmount.push(item.videoAmount)
          lineData.musicAmount.push(item.musicAmount)
          lineData.vipShareAmount.push(item.vipShareAmount) // 小酷Ai
          lineData.liveShareAmount.push(item.liveShareAmount)
          lineData.videoShareAmount.push(item.videoShareAmount)
          lineData.mallShareAmount.push(item.mallShareAmount)
          lineData.musicShareAmount.push(item.musicShareAmount)
          lineData.albumShareAmount.push(item.albumShareAmount || 0)
          lineData.actiRegistShareAmount.push(item.actiRegistShareAmount)
        })
        // 初始化折线图
        lineChartOption.xAxis.data = lineData.xAxis
        lineChartOption.series[0].data = lineData.practiceAmount
        lineChartOption.series[1].data = lineData.liveAmount
        lineChartOption.series[2].data = lineData.videoAmount
        lineChartOption.series[3].data = lineData.musicAmount
        lineChartOption.series[4].data = lineData.vipShareAmount
        lineChartOption.series[5].data = lineData.liveShareAmount
        lineChartOption.series[6].data = lineData.videoShareAmount
        lineChartOption.series[7].data = lineData.mallShareAmount
        lineChartOption.series[8].data = lineData.musicShareAmount
        lineChartOption.series[9].data = lineData.albumShareAmount
        lineChartOption.series[10].data = lineData.actiRegistShareAmount
        // console.log(lineChartOption)
        this.myChart.clear()
        this.myChart.setOption(lineChartOption)

        // 处理饼图数据
        pieChartOption.series[0].data[0].value = result.practiceAmount
        pieChartOption.series[0].data[1].value = result.liveAmount
        pieChartOption.series[0].data[2].value = result.videoAmount
        pieChartOption.series[0].data[3].value = result.musicAmount
        pieChartOption.series[0].data[4].value = result.vipShareAmount
        pieChartOption.series[0].data[5].value = result.liveShareAmount
        pieChartOption.series[0].data[6].value = result.videoShareAmount
        pieChartOption.series[0].data[7].value = result.mallShareAmount
        pieChartOption.series[0].data[8].value = result.musicShareAmount
        pieChartOption.series[0].data[9].value = result.albumShareAmount
        pieChartOption.series[0].data[10].value = result.actiRegistShareAmount
        console.log(pieChartOption)
        this.myChart2.clear()
        this.myChart2.setOption(pieChartOption)
      } catch (e) {
        // console.log(e)
      }
    }
  },
  render() {
    return (
      <div style={{ overflow: 'hidden' }}>
        <ColHeader />
        <div class={styles.incomeConsus}>
          <Cell
            class={styles.income}
            title="总收入(元)"
            v-slots={{
              label: () => (
                <span class={styles.countPrice}>
                  {moneyFormat(this.moneyInfo.totalInAmount)}
                </span>
              ),
              value: () => (
                <span
                  class={styles.searchTime}
                  onClick={() => (this.timerStatus = true)}
                >
                  {this.dateTimeStr}
                </span>
              )
            }}
          ></Cell>

          <div class={styles.section}>
            <Row class={styles.numberCount}>
              <Col span={6}>
                <i></i>
                <div class={styles.type}>
                  <span>陪练课</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.practiceAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color1}></i>
                <div class={styles.type}>
                  <span>直播课</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.liveAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color2}></i>
                <div class={styles.type}>
                  <span>视频课</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.videoAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color3}></i>
                <div class={styles.type}>
                  <span>乐谱</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.musicAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color4}></i>
                <div class={styles.type}>
                  <span>小酷Ai推广</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.vipShareAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color5}></i>
                <div class={styles.type}>
                  <span>直播课推荐</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.liveShareAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color6}></i>
                <div class={styles.type}>
                  <span>视频课推荐</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.videoShareAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color7}></i>
                <div class={styles.type}>
                  <span>商品推荐</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.mallShareAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color8}></i>
                <div class={styles.type}>
                  <span>乐谱推荐</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.musicShareAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color10}></i>
                <div class={styles.type}>
                  <span>专辑推荐</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.albumShareAmount)}
                  </span>
                </div>
              </Col>
              <Col span={6}>
                <i class={styles.color9}></i>
                <div class={styles.type}>
                  <span>活动报名</span>
                  <span class={styles.price}>
                    {moneyFormat(this.moneyInfo.actiRegistShareAmount)}
                  </span>
                </div>
              </Col>
            </Row>
          </div>

          <div id="incomeClass" class={styles.incomeLine}></div>

          <div class={styles.incomeTitle}>
            <i></i>收入结构
          </div>

          <div class={[styles.pieSection, 'van-hairline--bottom']}>
            <div id="structrueClass" class={styles.pieIncome}></div>

            <div class={styles.rateAll}>
              <div>
                <img src={getAssetsHomeFile('icon_user.png')} />
                <span>个人收入总占比</span>
                <span class={styles.rate}>
                  {this.moneyInfo.totalSingleRate}%
                </span>
              </div>
              <div>
                <img src={getAssetsHomeFile('icon_fly.png')} />
                <span>推广收益总占比</span>
                <span class={styles.rate}>
                  {this.moneyInfo.totalShareRate}%
                </span>
              </div>
            </div>
          </div>

          <div class={styles.pieData}>
            <div>
              <i class={styles.piePractice}></i>
              <span class={styles.pieTitle}>陪练课</span>
              <span>{this.moneyInfo.practiceRate}%</span>
            </div>
            <div>
              <i class={styles.pie1}></i>
              <span class={styles.pieTitle}>小酷Ai推广</span>
              <span>{this.moneyInfo.vipShareRate}%</span>
            </div>

            <div>
              <i class={styles.pieLive}></i>
              <span class={styles.pieTitle}>直播课</span>
              <span>{this.moneyInfo.liveRate}%</span>
            </div>
            <div>
              <i class={styles.pie2}></i>
              <span class={styles.pieTitle}>直播课推荐</span>
              <span>{this.moneyInfo.liveShareRate}%</span>
            </div>

            <div>
              <i class={styles.pieVideo}></i>
              <span class={styles.pieTitle}>视频课</span>
              <span>{this.moneyInfo.videoRate}%</span>
            </div>
            <div>
              <i class={styles.pie3}></i>
              <span class={styles.pieTitle}>视频课推荐</span>
              <span>{this.moneyInfo.videoShareRate}%</span>
            </div>

            <div>
              <i class={styles.pieMusic}></i>
              <span class={styles.pieTitle}>乐谱</span>
              <span>{this.moneyInfo.musicRate}%</span>
            </div>

            <div>
              <i class={styles.pie6}></i>
              <span class={styles.pieTitle}>活动报名</span>
              <span>{this.moneyInfo.actiRegistShareRate}%</span>
            </div>
            <div>
              <i class={styles.pie4}></i>
              <span class={styles.pieTitle}>商品推荐</span>
              <span>{this.moneyInfo.mallShareRate}%</span>
            </div>
            <div>
              <i class={styles.pie5}></i>
              <span class={styles.pieTitle}>乐谱推荐</span>
              <span>{this.moneyInfo.musicShareRate}%</span>
            </div>
            <div>
              <i class={styles.pie7}></i>
              <span class={styles.pieTitle}>专辑推荐</span>
              <span>{this.moneyInfo.albumShareRate}%</span>
            </div>
          </div>
        </div>

        <Popup
          v-model:show={this.timerStatus}
          position="bottom"
          round
          zIndex={99999999}
        >
          {this.params.timeType === 'MONTH' && (
            <DatetimePicker
              v-model={this.currentDate}
              type="year-month"
              title="选择时间"
              formatter={formatterDate}
              onCancel={() => (this.timerStatus = false)}
              onConfirm={(value: any) => {
                this.params.dateTime = dayjs(value).format('YYYY-MM')
                this.dateTimeStr = dayjs(value).format('YYYY年MM月')
                this.timerStatus = false
                this.getList()
              }}
              v-slots={{
                'columns-top': () => (
                  <div class={styles.timePopup}>
                    <Button
                      type="primary"
                      plain={this.params.timeType !== 'MONTH'}
                      size="mini"
                      class={styles.timeMonth}
                      onClick={() => (this.params.timeType = 'MONTH')}
                    >
                      按月
                    </Button>
                    <Button
                      type="primary"
                      plain={this.params.timeType !== 'YEAR'}
                      size="mini"
                      class={styles.timeYear}
                      onClick={() => (this.params.timeType = 'YEAR')}
                    >
                      按年
                    </Button>
                  </div>
                )
              }}
            />
          )}

          {this.params.timeType === 'YEAR' && (
            <Picker
              v-model={this.currentDate}
              title="选择时间"
              columns={yearColumns}
              defaultIndex={defaultIndex}
              onCancel={() => (this.timerStatus = false)}
              onConfirm={(obj: any, index: number) => {
                this.params.dateTime = obj.value
                defaultIndex = index // 记录当前选择的年份
                this.dateTimeStr = obj.text
                this.timerStatus = false
                this.getList()
              }}
              v-slots={{
                'columns-top': () => (
                  <div class={styles.timePopup}>
                    <Button
                      type="primary"
                      plain={this.params.timeType !== 'MONTH'}
                      size="mini"
                      class={styles.timeMonth}
                      onClick={() => (this.params.timeType = 'MONTH')}
                    >
                      按月
                    </Button>
                    <Button
                      type="primary"
                      plain={this.params.timeType !== 'YEAR'}
                      onClick={() => (this.params.timeType = 'YEAR')}
                      size="mini"
                      class={styles.timeYear}
                    >
                      按年
                    </Button>
                  </div>
                )
              }}
            />
          )}
        </Popup>
      </div>
    )
  }
})
