import ColSearch from '@/components/col-search'
import {
  ActionSheet,
  Cell,
  CellGroup,
  Col,
  DatetimePicker,
  Dialog,
  Icon,
  Image,
  List,
  Popup,
  Row
} from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import { formatterDate } from '@/helpers/utils'

// import tipBg from './images/tip-bg.png'
import fly from './images/icon_fly.png'
import iconTime from '@/common/images/icon_timer2.png'
import request from '@/helpers/request'
import ColResult from '@/components/col-result'
import dayjs from 'dayjs'
import { bizStatus, postStatus } from '@/constant'
import iconStudent from '@/common/images/icon_student.png'
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
}

export default defineComponent({
  name: 'extendPlan',
  data() {
    return {
      allAmount: {
        cancelAmount: 0,
        recordedAmount: 0,
        studentNum: 0,
        totalAmount: 0,
        waitAmount: 0
      } as any,
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      timeStatus: false,
      currentDate: new Date(),
      params: {
        username: '',
        bizType: '',
        searchDate: dayjs().format('YYYY-MM'),
        page: 1,
        rows: 20
      },
      // 业务类型：PRACTICE, 陪练课 LIVE, 直播课 VIDEO, 视频课 MUSIC, 乐谱 WITHDRAWAL, 提现 LIVE_SHARE, 直播课分润 VIDEO_SHARE, 视频课分润 MUSIC_SHARE, 乐谱分润 VIP_SHARE, 会员分润 MALL_SHARE, 商品分润 ,可用值:PRACTICE,LIVE,VIDEO,MUSIC,VIP,MALL,WITHDRAWAL,LIVE_SHARE,VIDEO_SHARE,MUSIC_SHARE,VIP_SHARE,MALL_SHARE
      actions: [
        { name: '全部推广', value: '' },
        { name: '直播课', value: 'LIVE_SHARE' },
        { name: '视频课', value: 'VIDEO_SHARE' },
        { name: '小酷Ai会员', value: 'VIP_SHARE' },
        { name: '曲谱', value: 'MUSIC_SHARE' },
        { name: '专辑', value: 'ALBUM_SHARE' },
        { name: '商品', value: 'MALL_SHARE' },
        { name: '活动报名', value: 'ACTI_REGIST_SHARE' }
      ],
      actionsType: {
        LIVE_SHARE: '直播课',
        VIDEO_SHARE: '视频课',
        VIP_SHARE: '小酷Ai会员',
        MUSIC_SHARE: '曲谱',
        ALBUM_SHARE: '专辑',
        MALL_SHARE: '商品',
        ACTI_REGIST_SHARE: '活动报名'
      },
      actionType: false
    }
  },
  async mounted() {
    try {
      const res = await request.post(
        '/api-teacher/userAccount/accountShareTotal',
        {}
      )
      this.allAmount = res.data || {}

      this.getList()
    } catch {
      //
    }
  },
  methods: {
    async getList() {
      try {
        const params = this.params
        const res = await request.post('/api-teacher/userAccount/sharePage', {
          data: {
            ...params
          }
        })
        this.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (this.list.length > 0 && result.pageNo === 1) {
          return
        }
        this.list = this.list.concat(result.rows || [])
        this.finished = result.pageNo >= result.totalPage
        this.params.page = result.pageNo + 1
        this.dataShow = this.list.length > 0
      } catch {
        this.dataShow = false
        this.finished = true
      }
    },
    onSelect(item: any) {
      console.log(item)
      this.params.bizType = item.value
      this.onSearch()
    },
    onSearch() {
      this.dataShow = true
      this.loading = false
      this.finished = false
      this.list = []
      this.params.page = 1
      this.getList()
    },
    onSearchStr(name: string) {
      console.log(name)
      this.params.username = name
      this.onSearch()
    },
    onConfirm(item: any) {
      console.log(item)
      this.params.searchDate = dayjs(item).format('YYYY-MM')
      this.timeStatus = false
      this.onSearch()
    },
    onTips(index: number, type = 'center' as any) {
      const template = [
        '累计奖励是您成功分享酷乐秀平台产品所获得的总收益',
        '当您分享酷乐秀平台产品，学生成功购买后获得预计收益，该收益还未进入您的账户，暂时无法结算\n入账规则：学生成功购买后2天入账',
        '您成功分享酷乐秀平台产品且已经入账的收益金额',
        '直播课成课失败或商品退货会造成退费'
      ]

      Dialog.alert({
        title: '提示',
        message: template[index],
        messageAlign: type,
        confirmButtonColor: 'var(--van-primary)'
      })
    }
  },
  render() {
    return (
      <div style={{ overflow: 'hidden' }}>
        <ColHeader />
        <div class={styles.allNumber}>
          {/* <img
            src={tipBg}
            class={styles.tips}
            onClick={() => {
              this.$router.push('/extendPlanDetail')
            }}
          /> */}
          <Cell
            class={styles.cell}
            v-slots={{
              title: () => (
                <div class={[styles.title, 'van-hairline--bottom']}>
                  <Row>
                    <Col
                      onClick={() => {
                        this.onTips(0)
                      }}
                    >
                      <div class={styles.price}>
                        {this.allAmount.totalAmount}
                        <span>元</span>
                      </div>
                      <p style={{ display: 'flex', alignItems: 'center' }}>
                        累计奖励
                        <Icon
                          name={getAssetsHomeFile('info-o.png')}
                          size="13"
                          style={{ paddingLeft: '3px' }}
                        />
                      </p>
                    </Col>
                    <Col
                      onClick={() => {
                        this.onTips(1, 'left')
                      }}
                    >
                      <div class={styles.price}>
                        {this.allAmount.waitAmount}
                        <span>元</span>
                      </div>
                      <p style={{ display: 'flex', alignItems: 'center' }}>
                        待入账
                        <Icon
                          name={getAssetsHomeFile('info-o.png')}
                          size="13"
                          style={{ paddingLeft: '3px' }}
                        />
                      </p>
                    </Col>
                    <Col
                      onClick={() => {
                        this.onTips(2)
                      }}
                    >
                      <div class={styles.price}>
                        {this.allAmount.recordedAmount}
                        <span>元</span>
                      </div>
                      <p style={{ display: 'flex', alignItems: 'center' }}>
                        已入账
                        <Icon
                          name={getAssetsHomeFile('info-o.png')}
                          size="13"
                          style={{ paddingLeft: '3px' }}
                        />
                      </p>
                    </Col>
                    <Col
                      onClick={() => {
                        this.onTips(3)
                      }}
                    >
                      <div class={styles.price}>
                        {this.allAmount.cancelAmount}
                        <span>元</span>
                      </div>
                      <p style={{ display: 'flex', alignItems: 'center' }}>
                        已退费
                        <Icon
                          name={getAssetsHomeFile('info-o.png')}
                          size="13"
                          style={{ paddingLeft: '3px' }}
                        />
                      </p>
                    </Col>
                  </Row>
                </div>
              ),
              label: () => (
                <div class={styles.label}>
                  <img src={fly} />
                  <span>累计推广学员 {this.allAmount.studentNum} 人</span>
                </div>
              )
            }}
          ></Cell>
        </div>

        <ColSearch
          background="transparent"
          inputBackground="white"
          placeholder="请输入学员姓名"
          onSearch={this.onSearchStr}
        />
        <div class={styles.search}>
          <div
            class={styles.search_item}
            onClick={() => (this.timeStatus = true)}
          >
            {dayjs(this.currentDate).format('YYYY年MM月')}{' '}
            <Icon name="arrow-down" size={12} />
          </div>
          <div
            class={styles.search_item}
            onClick={() => (this.actionType = true)}
          >
            {this.params.bizType
              ? this.actionsType[this.params.bizType]
              : '全部推广'}
            <Icon name="arrow-down" size={12} />
          </div>
        </div>

        {this.dataShow ? (
          <List
            v-model:loading={this.loading}
            finished={this.finished}
            finishedText=" "
            class={[styles.liveList, 'mb12']}
            onLoad={this.getList}
            immediateCheck={false}
          >
            {this.list.map((item: any) => (
              <CellGroup class={styles.cellGroup}>
                <Cell
                  v-slots={{
                    icon: () => (
                      <div class={styles.courseImg}>
                        <img src={getAssetsHomeFile(`${item.bizType}.png`)} />
                      </div>
                    ),
                    title: () => (
                      <div class={styles.crouseTitle}>
                        <div class={styles.title}>{item.bizName}</div>
                        <div class={styles.timer}>
                          <Image src={iconTime} />
                          <span>{item.updateTime}</span>
                        </div>
                      </div>
                    ),
                    value: () => (
                      <div class={styles.cursePrice}>￥{item.transAmount}</div>
                    )
                  }}
                />
                <Cell
                  v-slots={{
                    title: () => (
                      <div class={styles.userInfo}>
                        <Image
                          src={item.buyUserAvatar || iconStudent}
                          class={styles.userLogo}
                        />
                        <span>{item.buyUserName}</span>
                      </div>
                    ),
                    value: () => (
                      <div
                        class={[
                          styles.status,
                          item.postStatus && styles.active
                        ]}
                      >
                        {postStatus[item.postStatus]}
                      </div>
                    )
                  }}
                />
              </CellGroup>
            ))}
          </List>
        ) : (
          <ColResult btnStatus={false} classImgSize="SMALL" tips="暂无推广" />
        )}

        <ActionSheet
          v-model:show={this.actionType}
          actions={this.actions}
          onSelect={this.onSelect}
          cancel-text="取消"
          close-on-click-action
          onCancel={() => (this.actionType = false)}
        />

        <Popup
          v-model:show={this.timeStatus}
          position="bottom"
          round
          closeOnPopstate
        >
          <DatetimePicker
            type="year-month"
            v-model={this.currentDate}
            formatter={formatterDate}
            onCancel={() => {
              this.timeStatus = false
            }}
            onConfirm={this.onConfirm}
          />
        </Popup>
      </div>
    )
  }
})
