<template>
  <el-row>
    <el-col :span="10">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="关键词" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="数据来源" prop="resource">
          <el-radio-group v-model="ruleForm.resource">
            <el-radio label="淘宝"></el-radio>
            <el-radio label="天猫"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">一键淘词</el-button>
          <el-button @click="exportExcel('my-table2')">数据导出</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col :span="10" :offset="2">
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        id="my-table2"
        style="width: 100%">
        <el-table-column
          prop="value"
          header-align="center"
          align="center"
          label="关键词">
        </el-table-column>
        <el-table-column
          prop="resource"
          header-align="center"
          align="center"
          label="类型">
        </el-table-column>
      </el-table>
      <p class="TT-total">共获取{{ dataList.length }}条数据</p>
    </el-col>
  </el-row>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'

export default {
  name: 'tools-starkeysearch',
  data () {
    return {
      ruleForm: {
        name: '', // apple
        resource: '淘宝'
      },
      rules: {
        name: [
          { required: true, message: '请输入关键词', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择数据来源', trigger: 'change' }
        ]
      },
      dataList: [],
      dataListLoading: false
    }
  },
  methods: {
    submitForm (formName) {
      const { name, resource } = this.ruleForm
      const ts = new Date().getTime()
      const api = resource === '天猫' ? `https://suggest.taobao.com/sug?code=utf-8&q=${name}&_ksTS=${ts}_1105&callback=jsonp1106&area=b2c&code=utf-8&k=1&bucketid=19&src=tmall_pc` : `https://suggest.taobao.com/sug?code=utf-8&q=${name}&_ksTS=${ts}_512&callback=jsonp513&k=1&area=c2c&bucketid=10`
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return
        }
        this.dataListLoading = true
        this.$jsonp(api, {}).then((res) => {
          if (res && Array.isArray(res.result)) {
            this.funPayment(res.result, resource)
          } else {
            this.$message.error('出错了，请联系客服')
          }
          this.dataListLoading = false
        })
      })
    },
    // 扣费接口
    funPayment (result = [], resource = '') {
      this.$http({
        url: this.$http.adornUrl('/user/apicut'),
        method: 'get',
        params: this.$http.adornParams({
          path: 'tb/suggest'
        })
      }).then(({ data }) => {
        if (data.status) {
          this.dataList = result.map(item => ({
            value: item[0],
            resource: resource
          }))
          return
        }
        this.$message.error(data.msg)
      }).catch(() => {
      })
    },
    // 导出表格所用
    exportExcel (id) {
      var wb = XLSX.utils.table_to_book(document.querySelector('#' + id))
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${this.ruleForm.resource}下拉框选词` + '.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    }
  }
}
</script>

<style lang="scss" scoped>
.TT-total {
  width: 100%;
  margin-top: 10px;
  text-align: center;
}
</style>
