<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" :class="'el-button el-button--primary'" @click="addStore()">添加分组</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="240px" show-overflow-tooltip align="center" fixed="right">
              <template slot-scope="{ row }">
                <div class="table-options">
                  <el-button type="text" @click="deleteGroup(row.id)">删除</el-button>
                  <el-button type="text" @click="toUpdateGroup(row)">修改</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" style="margin-top: 20px" :model="form" label-width="120px" ref="form">
        <el-form-item
          prop="name"
          label="分组名称"
          :rules="[{ required: true, message: '请输入分组名称', trigger: 'blur' }]">
          <el-input placeholder="请输入分组名称" v-model="form.name"></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="name"
          label="分组名称"
          :rules="[{ required: true, message: '请输入分组名称', trigger: 'blur' }]">
          <el-input placeholder="请输入分组名称" v-model="updateForm.name"></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="updateGroup">确定</el-button>
      </div>
    </ai-dialog>

    <ai-dialog
      title="提示"
      :visible.sync="isTipDlgShow"
      :close-on-click-modal="false"
      width="790px"
      customFooter
      @close="isDlgShow = false">
      <div style="display: block;height: 30px;">商品链接可能出现图形验证码，导致采集失败，是否前往验证？</div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="isTipDlgShow = false">取消</el-button>
        <el-button style="width: 180px;" @click="isTipDlgShow = false, isLoading = true, beginCollect()">已验证，继续采集</el-button>
        <el-button type="primary" @click="gotoValid">前往验证</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,
          size: 10
        },
        colConfigs: [
          { prop: 'name', label: '分组名称', align: 'left' },
          { prop: 'remark', label: '备注', align: 'left'},
          { prop: 'lastUpdateTime', label: '最后一次更新时间', align: 'left' },
          { prop: 'createTime', label: '添加时间', width: '180px', fixed: 'right'}
        ],
        tableData: [],
        total: 0,

        form: {
          name: '',
          remark: ''
        },

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

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

        isLoading: false,

        currentRow: {},
        goodsList: [],
        currentIndex: 0,

        isTipDlgShow: false
      }
    },

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

    methods: {
      getList () {
        this.$http.post('/api/newProductGroup/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/newProductGroup/add`, {name: this.form.name, remark: this.form.remark}).then(res => {
              if (res.code == 0) {
                this.$message.success('添加成功！')
                this.$store.dispatch('getUserInfo')
                this.getList()
                this.isDlgShow = false
              }
            })
          }
        })
      },
      toUpdateGroup (obj) {
        this.updateObj = obj
        this.updateForm.name = obj.name
        this.updateForm.remark = obj.remark
        this.isUpdateDlgShow = true
      },
      updateGroup () {
        this.$refs.updateForm.validate((valid) => {
          if (valid) {
            this.$http.post(`/api/newProductGroup/update`, {id: this.updateObj.id, name: this.updateForm.name, 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/newProductGroup/renew',null, {
            params: {
              id: id
            }
          }
          ).then(res => {
            if (res.code == 0) {
              this.$message.success('续费成功！')
              this.$store.dispatch('getUserInfo')
              this.getList()
            }
          })
        })
      },
      deleteGroup(id) {
        this.$confirm('确定要删除？', '温馨提示', {
          type: 'warning'
        }).then(() => {
          this.$http.post('/api/newProductGroup/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.name = ''
        this.form.remark = ''
        this.isDlgShow = true
      },
      toBegin(row) {
        this.currentRow = row
        this.isLoading = true

        this.$http.post('/api/newProductGroupDetail/getGoodsList',null,{
            params: {
              groupId: row.id
            }
        }).then(res => {
            this.goodsList = res.data
            this.currentIndex = 0
            this.beginCollect()
        })
      }, 
      async beginCollect() {
        if (this.currentIndex >= this.goodsList.length) {
          Message.success("采集成功")
          this.isLoading = false
          this.getList()
          return
        }
        let res = await sendChromeWebReqMessage({
          type: 'temu',
          url: 'https://www.temu.com/goods.html?goods_id=' + this.goodsList[this.currentIndex].goodsId,
        })
        if (res.indexOf("window.rawData") == -1) {
          this.isLoading = false
          this.errorUrl = 'https://www.temu.com/goods.html?goods_id=' + this.goodsList[this.currentIndex].goodsId
          this.isTipDlgShow = true
          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 goodsObj = JSON.parse(str)
        let sku = goodsObj.store.sku[0]

        await this.$http.post('/api/newProductDetail/addDetail',null,{
          params: {
            groupId: this.goodsList[this.currentIndex].groupId,
            goodsId: this.goodsList[this.currentIndex].goodsId,
            price: sku.normalPrice/100,
            saleTotal: goodsObj.store.goods.soldQuantity || 0
          }
        })

        this.currentIndex ++
        this.beginCollect()
      },
      gotoValid() {
        window.open(this.errorUrl, '_blank')
      }
    }
  }
</script>

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