import { analysis, tasksearch, polishScript, createTask } from "../../utils/request"

const sampleText = '解析中...'
const checkinStorageKey = 'lastCheckinDate'

function getTodayKey() {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

Component({
  data: {
    parsed: false,
    videoLink: '',
    scriptText: sampleText,
    showCheckinPopup: false,
    taskId: '',
    parseId: '',
    polishing: false
  },
  lifetimes: {
    attached() {
      const today = getTodayKey()
      const lastCheckinDate = wx.getStorageSync(checkinStorageKey)

      if (lastCheckinDate !== today) {
        this.setData({ showCheckinPopup: true })
      }
    },
  },
  methods: {
    handleInput(e: any) {
      this.setData({
        videoLink: e.detail.value,
      })
    },
    onUnload() {
      this.setData({ videoLink: '', parsed: false, scriptText: '' })
    },
    handlePaste() {
      wx.getClipboardData({
        success: (res) => {
          this.setData({
            videoLink: res.data || '0.58 J@i.cN 08/24 :0pm ULw:/ # 新到 # 国五排放 # 货车出售转让  https://v.douyin.com/tHoCmTcQT2Q/ 复制此链接，打开Dou音搜索，直接观看视频！',
          })
        },
        fail: () => {
          this.setData({
            videoLink: '0.58 J@i.cN 08/24 :0pm ULw:/ # 新到 # 国五排放 # 货车出售转让  https://v.douyin.com/tHoCmTcQT2Q/ 复制此链接，打开Dou音搜索，直接观看视频！',
          })
        },
      })
    },
    handleParse() {
      if (this.data.videoLink == '') {
        wx.showModal({
          title: '温馨提示',
          content: '解析链接不能为空',
          showCancel: false
        })
        return;
      }
      wx.showLoading({ title: '解析中.' });
      analysis(this.data.videoLink).then((res: any) => {
        console.log(res);
        wx.hideLoading();
        if (!res.code) {
          this.setData({
            parsed: true,
            taskId: '',
            parseId: String(res.data.parseId || res.data.taskId || '')
          })
          wx.showLoading({ title: '等待结果中...', mask: true });
          this.tasksearch(String(res.data.parseId || res.data.taskId || ''))
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '解析失败，请确认链接的有效性',
            showCancel: false
          })
        }
      }).catch((err) => {
        console.log(err)
        wx.hideLoading();
        wx.showModal({
          title: '温馨提示',
          content: '解析失败，请重试',
          showCancel: false
        })
      })
    },

    tasksearch(taskId: string) {
      let that = this;
      tasksearch(taskId).then((res: any) => {
        if (!res.code) {
          wx.hideLoading();

          this.setData({ scriptText: (res.data && res.data.scriptText) || '' })
        } else {
          setTimeout(() => that.tasksearch(taskId), 500);
        }
      })
    },

    handleReset() {
      this.setData({
        parsed: false,
        scriptText: '',
      })
      this.handleParse();
    },
    handleCopy() {
      wx.setClipboardData({
        data: this.data.scriptText,
        fail(err) {
          console.log(err);
          wx.showModal({
            title: '温馨提示',
            content: '您还未授于剪切板权限'
          })
        }
      })
    },
    handlePolish() {
      if (!(this.data.parseId || this.data.taskId) || !this.data.scriptText) {
        wx.showToast({ title: '暂无可润色文案', icon: 'none' })
        return
      }
      if (this.data.polishing) return

      this.setData({ polishing: true })
      wx.showLoading({ title: '润色中...', mask: true })
      polishScript(this.data.parseId || this.data.taskId, this.data.scriptText, 'optimize').then((res: any) => {
        wx.hideLoading()
        this.setData({ polishing: false })
        if (!res.code) {
          this.setData({ scriptText: res.data.scriptText })
          wx.showToast({ title: '已润色', icon: 'success' })
          return
        }
        wx.showModal({ title: '温馨提示', content: res.message || '润色失败，请稍后再试', showCancel: false })
      }).catch((err) => {
        console.log(err)
        wx.hideLoading()
        this.setData({ polishing: false })
        wx.showModal({ title: '温馨提示', content: '润色失败，请稍后再试', showCancel: false })
      })
    },
    handleGoCreate() {
      const parseId = this.data.parseId || this.data.taskId
      if (!parseId || !this.data.scriptText) {
        wx.showToast({ title: '请先完成文案提取', icon: 'none' })
        return
      }

      wx.showLoading({ title: '创建任务中', mask: true })
      createTask(parseId, this.data.scriptText).then((res: any) => {
        wx.hideLoading()
        if (!res.code && res.data && res.data.taskId) {
          this.setData({ taskId: res.data.taskId })
          wx.navigateTo({
            url: '/pages/aiPackage/preview/index?taskId=' + res.data.taskId,
          })
          return
        }
        wx.showModal({ title: '温馨提示', content: res.message || '创建任务失败，请稍后再试', showCancel: false })
      }).catch(() => {
        wx.hideLoading()
        wx.showModal({ title: '温馨提示', content: '网络异常，请稍后再试', showCancel: false })
      })
    },
    handleExperience() {
      this.setData({
        videoLink: 'https://v.douyin.com/example/',
        parsed: true,
      })
    },
    handleCheckinClose() {
      wx.setStorageSync(checkinStorageKey, getTodayKey())
      this.setData({ showCheckinPopup: false })
    },
    handleCheckinRule() {
      wx.showToast({ title: '每日签到可领取金币', icon: 'none' })
    },
  },
})







