<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;"
            @selection-change="onChooseChange"
            :current.sync="search.current" :size.sync="search.size"
            @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="店铺ID" show-overflow-tooltip align="center">
              <template slot-scope="{ row }">
                <div><a class="el-link el-link--primary" :href="'https://www.temu.com/mall.html?mall_id=' + row.content" 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="添加一个店铺跟踪，将消耗300金币"
        type="success"
        :closable="false">
      </el-alert>
      <el-form class="ai-form" :model="form" label-width="120px" ref="form">
        <el-form-item
          prop="mallId"
          label="店铺ID"
          :rules="[{ required: true, message: '请输入店铺ID', trigger: 'blur' }]">
          <el-input placeholder="请输入店铺ID" v-model="form.mallId"></el-input>
        </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 {sendTemuAPIMessage} from '@/api/chromeApi'

  export default {
    name: 'List',

    data () {
      return {
        search: {
          current: 1,
          type: '1',
          size: 10
        },
        colConfigs: [
          { type: "selection", width: '70px', align: 'left' },
          { slot: 'content', label: '店铺ID', align: 'left' },
          { 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: {
          mallId: '',
          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');
      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: 1}}).then(res => {
              if (res.code == 0) {
                this.$http.post(`/api/monitor/add`, {content: this.form.mallId, remark: this.form.remark, 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
              }
            })
          }
        })
      },
      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))
        })
      },
      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.mallId = ''
        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) {
        sendTemuAPIMessage({
          url: 'api/bg/circle/c/mall/newGoodsList',
          anti: true,
          data: {
            "mall_id": row.content,
            "filter_items": "0:1",
            "page_number": this.pageNo,
            "page_size": this.pageSize
          }}).then((res) => {
            if (this.isBatchCollect && (index+1) == this.selectRows.length) {
              this.isLoading = false
              this.isBatchCollect = false
            } else {
              this.isLoading = false
            }
            if (res.errorCode == 1000000) {
              res.result.data.goods_list.map(item => {
                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
                  }
                }
                reqData.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
                })
              })

              if (res.result.data.goods_list.length == this.pageSize) {
                this.pageNo = this.pageNo + 1
                this.beginCollect(row, reqData, index)
              } else {
                this.isLoading = false
                this.$http.post('/api/monitorDetail/addDetails', reqData
                ).then(res => {
                  if (res.code == 0) {
                    this.$message.success('店铺ID【' + row.content + '】数据采集成功！')
                    this.getList()
                  }
                })
              }
            } else {
              this.isLoading = false
              this.$message.error("采集失败，请检查网络情况")
            }
          })
      }
    }
  }
</script>

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