import { Checkbox, Icon, Popup } from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import activeButtonIcon from '@common/images/icon_checkbox.png'
import inactiveButtonIcon from '@common/images/icon_checkbox_default.png'
import ColHeader from '../col-header'
import { state } from '@/state'
import request from '@/helpers/request'

export default defineComponent({
  name: 'protocol',
  props: {
    showHeader: {
      type: Boolean,
      default: false
    },
    modelValue: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: ''
    },
    musicGroupId: {
      type: String,
      default: ''
    },
    courseView: {
      type: String,
      default: ''
    },
    protocolTitle: {
      type: String,
      default: '产品及服务协议'
    }
  },
  data() {
    return {
      exists: true,
      checked: this.modelValue,
      popupStatus: false,
      protocolHTML: '',
      protocolPopup: null as any,
      isProtocol: true
    }
  },
  async mounted() {
    try {
      console.log('getContractDetail')
      // 判断是否有协议内容
      if (!this.protocolHTML) {
        const res = await request.get(
          state.platformApi + '/contracts/queryProduceContract',
          {
            params: {
              userId: this.userId ? this.userId : null,
              musicGroupId: this.musicGroupId ? this.musicGroupId : null,
              courseViewType: this.courseView
            }
          }
        )
        this.protocolHTML = res.data.productContract || ''
        console.log(res)

        this.exists = res.data.exists
        this.checked = this.checked || this.exists
        this.$emit('update:modelValue', this.checked || this.exists)
      }

      // 如果没有协议内容则不 显示协议
      if (!this.protocolHTML) {
        this.isProtocol = this.protocolHTML ? true : false
        this.checked = true // 默认选中，学生端则不用默认选中
        this.$emit('input', this.checked || this.exists)
      }
    } catch {}
    this.checked = this.modelValue
    window.addEventListener('hashchange', this.onHash, false)
  },
  unmounted() {
    window.removeEventListener('hashchange', this.onHash, false)
  },
  watch: {
    checked(val) {
      this.$emit('update:modelValue', val)
    }
  },
  methods: {
    async getContractDetail() {
      try {
        console.log('getContractDetail')
        // 判断是否有协议内容
        if (!this.protocolHTML) {
          const res = await request.get(
            state.platformApi + '/contracts/queryProduceContract',
            {
              params: {
                contractType: 'BUY_ORDER'
              }
            }
          )
          this.protocolHTML = res.data
          console.log(res)
        }
        this.onPopupClose()
      } catch {}
    },
    onHash() {
      this.popupStatus = false
    },
    onPopupClose() {
      this.popupStatus = !this.popupStatus

      // 打开弹窗
      if (this.popupStatus) {
        const route = this.$route
        let times = 0
        for (let i in route.query) {
          times += 1
        }
        const origin = window.location.href
        const url = times > 0 ? '&pto=' + +new Date() : '?pto=' + +new Date()
        history.pushState('', '', `${origin}${url}`)
      } else {
        window.history.go(-1)
      }
      if (this.protocolPopup) {
        ;(this.protocolPopup as any).scrollTop = 0
      }
    }
  },
  render() {
    return (
      <div class={this.isProtocol && styles.colProtocol}>
        {/* 判断是否显示协议 */}
        {this.isProtocol && (
          <>
            {!this.exists && (
              <Checkbox
                v-model={this.checked}
                v-slots={{
                  icon: (props: any) => (
                    <Icon
                      class={styles.boxStyle}
                      name={
                        props.checked ? activeButtonIcon : inactiveButtonIcon
                      }
                      size="15"
                    />
                  )
                }}
              >
                我已阅读并同意
              </Checkbox>
            )}
            {this.exists && <>查看</>}
            <span onClick={this.onPopupClose} class={styles.protocolText}>
              《{this.protocolTitle}》
            </span>
          </>
        )}

        <Popup
          ref={this.protocolPopup}
          show={this.popupStatus}
          position="bottom"
          style={{ height: '100%' }}
        >
          {this.showHeader && <ColHeader title={this.protocolTitle} />}
          {this.popupStatus && (
            <div class={styles.protocolContent} id="mProtocol">
              <div
                class={styles.protocolContent}
                v-html={this.protocolHTML}
              ></div>
            </div>
          )}
        </Popup>
      </div>
    )
  }
})
