<template>
  <div>
    <ai-list class="list" v-loading="isLoading" element-loading-text="正在采集中……" element-loading-spinner="el-icon-loading">
      <ai-title
        slot="title"
        title="关键字跟踪"
        isShowBottomBorder>
      </ai-title>
      <template slot="content">
        <div class="content">
          <ai-search-bar>
            <template #left>
              <el-button type="button" :icon="'el-icon-delete'" :class="'el-button el-button--primary'" @click="batchRemove()">删除</el-button>
              <el-button type="button" :class="'el-button el-button--primary'" @click="batchCollect()">批量采集</el-button>
              <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"
            @selection-change="onChooseChange"
            @getList="getList">
            <el-table-column slot="options" label="操作" width="240px" 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="toUpdateMonitor(row)">修改</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>
            <el-table-column slot="content" label="关键字" show-overflow-tooltip align="center">
              <template slot-scope="{ row }">
                <div><a class="el-link el-link--primary" :href="'https://www.temu.com/search_result.html?search_key='+row.content+'&search_method=user&filter_items='+row.orderType" target="_blank">{{ row.content }}</a></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-alert
        title="添加一个关键字跟踪，将消耗200金币"
        type="success"
        :closable="false">
      </el-alert>
      <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-item
          prop="orderType"
          label="排序方式"
          :rules="[{ required: true, message: '请选择排序方式', trigger: 'blur' }]">
          <ai-select :selectList="$dict.getDict('monitor_order_type')" v-model="form.orderType"></ai-select>
        </el-form-item>
        <el-form-item
          prop="remark"
          label="备注"
          :rules="[{ required: true, message: '请输入备注', trigger: 'blur' }]">
          <el-input placeholder="请输入备注" v-model="form.remark"></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>

    <ai-dialog
      title="修改店铺"
      :visible.sync="isUpdateDlgShow"
      :close-on-click-modal="false"
      width="790px"
      customFooter
      @close="isDlgShow = false">
      <el-form class="ai-form" :model="updateForm" label-width="120px" ref="updateForm">
        <el-form-item
          prop="mallId"
          label="店铺ID"
          :rules="[{ required: true, message: '请输入店铺ID', trigger: 'blur' }]">
          <el-input placeholder="请输入店铺ID" disabled v-model="updateForm.mallId"></el-input>
        </el-form-item>
        <el-form-item
          prop="remark"
          label="备注"
          :rules="[{ required: true, message: '请输入备注', trigger: 'blur' }]">
          <el-input placeholder="请输入备注" v-model="updateForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="isUpdateDlgShow = false">取 消</el-button>
        <el-button type="primary" @click="updateStore">确定</el-button>
      </div>
    </ai-dialog>
  </div>
</template>

<script>
import {sendChromeWebReqMessage} from '@/api/chromeApi'
import { Message } from 'element-ui'

  export default {
    name: 'List',

    data () {
      return {
        search: {
          current: 1,
          type: '0',
          size: 10
        },
        colConfigs: [
          { type: "selection", width: '70px', align: 'left' },
          { slot: 'content', label: '关键字', align: 'left' },
          { prop: 'orderType', label: '排序方式', align: 'left', format: v => this.$dict.getLabel('monitor_order_type', v) },
          { prop: 'remark', 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: '',
          orderType: '0:1',
          remark: ''
        },

        updateObj: {},
        isUpdateDlgShow: false,
        updateForm: {
          id: '',
          mallId: '',
          remark: ''
        },

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

        isLoading: false,

        selectRows: [],
        isBatchCollect: false
      }
    },

    created () {
      this.$dict.load('monitor_status', 'monitor_order_type');
      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
        })
      },
      onChooseChange (val) {
        this.selectRows = val;
      },
      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, remark: this.form.remark, orderType: this.form.orderType, type: this.search.type}).then(res => {
                  if (res.code == 0) {
                    this.$message.success('添加成功！')
                    this.$store.dispatch('getUserInfo')
                    this.getList()
                    this.isDlgShow = false
                  }
                })
              }
            })
          }
        })
      },
      toUpdateMonitor (obj) {
        this.updateObj = obj
        this.updateForm.mallId = obj.content
        this.updateForm.remark = obj.remark
        this.isUpdateDlgShow = true
      },
      updateStore () {
        this.$refs.updateForm.validate((valid) => {
          if (valid) {
            this.$http.post(`/api/monitor/update`, {id: this.updateObj.id, remark: this.updateForm.remark}).then(res => {
              if (res.code == 0) {
                this.$message.success('修改成功！')
                this.getList()
                this.isUpdateDlgShow = 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()
            }
          })
        })
      },
      batchRemove() {
        if (this.selectRows.length <= 0) {
          this.$message.error('请选择要删除的监测对象');
          return;
        }
        let ids = this.selectRows.map(item => {
          return item.id
        })

        this.$confirm('确定要删除？', '温馨提示', {
          type: 'warning'
        }).then(() => {
          this.$http.post('/api/monitor/delByIds', ids
          ).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功！')
              this.getList()
            }
          })
        })
      },
      batchCollect () {
        if (this.selectRows.length <= 0) {
          this.$message.error('请选择要采集的监测对象');
          return;
        }
        this.isBatchCollect = true
        this.isLoading = true
        this.selectRows.map((item, index) => {
          setTimeout(() => {
            this.pageNo = 1

            let data = {}
            data.monitorId = item.id
            data.details = []

            this.beginCollect(item, data, index)
          }, 1000*(index+1))
        })
      },
      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.isBatchCollect = false
        this.pageNo = 1
        this.isLoading = true

        let data = {}
        data.monitorId = row.id
        data.details = []

        this.beginCollect(row, data, 0)
      }, 
      beginCollect(row, reqData, index) {
        sendChromeWebReqMessage({
          type: 'temu',
          url: 'https://www.temu.com/search_result.html?search_key='+row.content+'&search_method=user&filter_items='+row.orderType
        }).then((res) => {
          if (this.isBatchCollect && (index+1) == this.selectRows.length) {
            this.isLoading = false
            this.isBatchCollect = false
          } else {
            this.isLoading = false
          }
          if (res.indexOf("rawData") == -1) {
            Message.error("请检查地址是否正确，或者“TEMU”网站是否出现图形验证码")
            return
          }
          let str = res.substring(res.indexOf("window.rawData"))
          str = str.substring(0, str.indexOf("<\/script>"))
          str = str.substring(str.indexOf("{"))
          str = str.substring(0, str.lastIndexOf("}"))
          str = str + "}"
          let obj = JSON.parse(str)
          let goodsList = obj.store.goodsList
          goodsList.map(t => {
            let item = t.data
            let total = 0
            if (item.salesNum) {
              total = item.salesNum
              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
              }
            }
            reqData.details.push({
              url: item.linkUrl,
              price: item.priceInfo.priceSchema,
              saleTotal: total,
              goodsId: item.goodsId,
              imgUrl: item.thumbUrl,
              mallId: item.mallId
            })
          })

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

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