<template>
  <TabActionItem
    show-text
    :direction="direction"
    class="download-project-doc"
    @click.native.stop="doAction"
  >
    <AppIcon slot="icon" name="xiazaixiangmubaogao" size="20" />
    <template #text>
      <EmailDialog
        v-model="dialog.show"
        :email.sync="dialog.email"
        title="发送邮箱地址"
        content-tip-text="项目报告文件将以邮件的形式发送至您的邮箱"
        :before-close="beforeEmailDialogClose"
      />
      <span>下载项目报告</span>
    </template>
  </TabActionItem>
</template>

<script>
import { mapGetters } from 'vuex'
import TabActionItem from '@/views/article/ui/TabActionItem.vue'
import { AppIcon } from '@/ui'
import { getProjectReport, sendProjectPdfFile } from '@/api/modules/'
import EmailDialog from '@/components/common/EmailDialog.vue'
import { emailRegExp } from '@/utils/constant/'
import downloadApp from '@/utils/mixins/modules/to-download-app'

export default {
  name: 'DownloadProjectReport',
  components: {
    TabActionItem,
    EmailDialog,
    AppIcon
  },
  mixins: [downloadApp],
  props: {
    id: {
      type: String,
      default: '',
      required: true
    },
    name: {
      type: String,
      default: '',
      required: true
    },
    direction: {
      type: String,
      default: 'row',
      validator(d) {
        return ['row', 'column'].includes(d)
      }
    },
    beforeAction: Function,
    beforeLeavePage: Function
  },
  data() {
    return {
      dialog: {
        show: false,
        email: ''
      },
      link: ''
    }
  },
  computed: {
    ...mapGetters('user', ['isFree'])
  },
  methods: {
    // 下载(下载前校验)
    async doAction() {
      if (this.beforeAction) {
        const r = await this.beforeAction()
        if (!r) {
          return
        }
      }
      if (this.isFree) {
        return this.goToSvipBuy()
      }

      if (this.$envs.inWxMini) {
        return this.toFollowGuidePage()
      }

      if (this.link) {
        return this.downFile(this.name, this.link)
      }

      const loading = this.$toast.loading({
        message: '报告正在生成，请稍后～'
      })
      try {
        const {
          data,
          error_code: code,
          error_msg: msg
        } = await getProjectReport({ sid: this.id })
        if (code === 0 && data) {
          this.link = data.path
          this.doDownload(this.name, this.link)
          loading.clear()
        } else {
          this.$toast(msg || '获取报告失败，请稍后再试')
        }
      } catch (error) {
        loading.clear()
        console.error(error)
      }
    },
    doDownload(name, link) {
      if (this.$envs.inIOS) {
        this.dialog.show = true
      } else {
        this.downFile(name, link)
      }
    },
    /**
     * 下载文件
     * @param name
     * @param url
     */
    downFile(name, url) {
      const a = document.createElement('a')
      const filename = name
      a.href = url
      a.target = '_blank'
      if (name) {
        a.download = filename
      }
      a.click()
    },
    async beforeEmailDialogClose(action, done) {
      if (action === 'cancel') {
        return done()
      }
      const { email } = this.dialog
      if (!emailRegExp.test(email)) {
        done(false)
        return this.$toast('邮箱地址格式错误')
      } else {
        await this.sendEmailConfirm(done)
      }
    },
    async sendEmailConfirm(done) {
      const { email } = this.dialog
      const fileUrl = this.link
      if (!email) {
        done(false)
        this.$toast('请输入邮箱地址')
      }
      if (!fileUrl) {
        done(false)
        this.$toast('报告附件异常')
      }
      const params = {
        downurl: fileUrl,
        email
      }
      const { error_msg: msg, error_code: code } =
        await sendProjectPdfFile(params)
      if (code === 0) {
        done && done()
        // this.$toast(`已发送至 ${email}`)
        this.$toast('邮件已发送，请注意查收')
      } else {
        done && done(false)
        this.$toast(msg || '发送失败')
      }
    },
    async goToSvipBuy() {
      if (this.beforeLeavePage) {
        await this.beforeLeavePage()
      }
      this.$router.push('/common/order/create/svip')
    }
  }
}
</script>

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