<template>
  <div>
    <ai-list class="list">
      <ai-title
        slot="title"
        title="关键字跟踪"
        isShowBottomBorder>
      </ai-title>
      <template slot="content">
        <div class="content">
          <ai-search-bar>
            <template #left>
              <el-button type="button" :class="'el-button el-button--primary'" @click="addStore()">添加关键字</el-button>
            </template>
            <template #right>
              <el-button size="small" circle icon="el-icon-refresh-right" @click="getList()"></el-button>
            </template>
          </ai-search-bar>
          <ai-table
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="total"
            style="margin-top: 8px;"
            :current.sync="search.current" :size.sync="search.size"
            @getList="getList">
            <el-table-column slot="options" label="操作" width="200px" show-overflow-tooltip align="center" fixed="right">
              <template slot-scope="{ row }">
                <div class="table-options">
                  <el-button type="text" @click="deleteMonitor(row.id)">删除</el-button>
                  <el-button type="text" @click="renew(row.id)">续费</el-button>
                  <el-button type="text" @click="toDetail(row.id)">详情</el-button>
                  <el-button type="text" @click="toBegin(row)">采集数据</el-button>
                </div>
              </template>
            </el-table-column>
          </ai-table>
        </div>
      </template>
    </ai-list>

    <ai-dialog
      title="添加店铺"
      :visible.sync="isDlgShow"
      :close-on-click-modal="false"
      width="790px"
      customFooter
      @close="isDlgShow = false">
      <el-form class="ai-form" :model="form" label-width="120px" ref="form">
        <el-form-item
          prop="content"
          label="关键字"
          :rules="[{ required: true, message: '请输入关键字', trigger: 'blur' }]">
          <el-input placeholder="请输入关键字" v-model="form.content"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="isDlgShow = false">取 消</el-button>
        <el-button type="primary" @click="saveStore">确定</el-button>
      </div>
    </ai-dialog>
  </div>
</template>

<script>
import {sendTemuAPIMessage} from '@/api/chromeApi'

  export default {
    name: 'List',

    data () {
      return {
        search: {
          current: 1,
          type: '0',
          size: 10
        },
        colConfigs: [
          { prop: 'content', label: '关键字', align: 'left' },
          { prop: 'lastUpdateTime', label: '最后一次更新时间', align: 'left' },
          { prop: 'status', label: '状态', align: 'left', format: v => this.$dict.getLabel('monitor_status', v), },
          { prop: 'expireTime', label: '失效时间', align: 'left' },
          { prop: 'createTime', label: '添加时间', width: '180px', fixed: 'right'}
        ],
        tableData: [],
        total: 0,

        form: {
          content: ''
        },

        isDlgShow: false,
        detailsVo: {},
        pageNo: 1,
        pageSize: 120
      }
    },

    created () {
      this.$dict.load('monitor_status');
      this.getList()
    },

    methods: {
      getList () {
        this.$http.post('/api/monitor/myPage',null,{
            params: {
                ...this.search
            }
        }).then(res => {
            this.tableData = res.data.records
            this.total = res.data.total
        })
      },
      saveStore () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$http.post('/api/monitor/check',null, {params: {type: 0}}).then(res => {
              if (res.code == 0) {
                this.$http.post(`/api/monitor/add`, {content: this.form.content, type: this.search.type}).then(res => {
                  if (res.code == 0) {
                    this.$message.success('添加成功！')
                    this.$store.dispatch('getUserInfo')
                    this.getList()
                    this.isDlgShow = false
                  }
                })
              }
            })
          }
        })
      },
      renew(id) {
        this.$confirm('确定要续费？', '温馨提示', {
          type: 'warning'
        }).then(() => {
          this.$http.post('/api/monitor/renew',null, {
            params: {
              id: id
            }
          }
          ).then(res => {
            if (res.code == 0) {
              this.$message.success('续费成功！')
              this.$store.dispatch('getUserInfo')
              this.getList()
            }
          })
        })
      },
      deleteMonitor(id) {
        this.$confirm('确定要删除？', '温馨提示', {
          type: 'warning'
        }).then(() => {
          this.$http.post('/api/monitor/del',null, {
            params: {
              id: id
            }
          }
          ).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功！')
              this.getList()
            }
          })
        })
      },
      toDetail (id) {
        this.$emit('change', {
          type: 'Detail',
          params: {
            id: id || ''
          }
        })
      },
      addStore() {
        this.form.content = ''
        this.isDlgShow = true
      },
      toBegin(row) {
        this.detailsVo = {}
        this.detailsVo.monitorId = row.id
        this.detailsVo.details = []
        this.pageNo = 1

        this.beginCollect(row)
      }, 
      beginCollect(row) {
        sendTemuAPIMessage({
          url: 'api/poppy/v1/search?scene=search',
          anti: true,
          data: 
          {
            "scene": "search",
            "offset": (this.pageNo-1) * this.pageSize,
            "pageSize": 120,
            "query": row.content,
            "filterItems": "0:1",
            "searchMethod": "suggest"
          }}).then((res) => {
            if (res.success) {
              res.result.data.goods_list.map(item => {
                console.log(item.sales_tip_text[0])
                let total = 0
                if (item.sales_tip_text[0]) {
                  total = item.sales_tip_text[0]
                  total = total.replace('+', '')
                  if (total.indexOf('K') != -1) {
                    total = total.replace('K', '')
                    total = total * 1000
                  } else if (total.indexOf('M') != -1) {
                    total = total.replace('M', '')
                    total = total * 1000000
                  }
                }
                this.detailsVo.details.push({
                  url: item.link_url,
                  price: item.price_info.price_schema,
                  saleTotal: total,
                  goodsId: item.goods_id,
                  imgUrl: item.thumb_url,
                  mallId: item.mall_id
                })
              })
              console.log(this.detailsVo)

              this.$http.post('/api/monitorDetail/addDetails',this.detailsVo
              ).then(res => {
                if (res.code == 0) {
                  this.$message.success('关键字【' + row.content + '】数据采集成功！')
                  this.getList()
                }
              })
            }
          })
      }
    }
  }
</script>

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