<template>
  <div>
    <ai-list class="list" v-loading="isLoading" :element-loading-text="loadingText" 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="addGroup()">添加分组</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="280px" 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="toAddUrl(row)">添加商品</el-button>
                  <el-button type="text" @click="toDetail(row.id, row.name)">详情</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>
      <div class="dialog-footer" slot="footer">
        <el-button @click="isDlgShow = false">取 消</el-button>
        <el-button type="primary" @click="saveGroup">确定</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>
      <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="isAddUrlDlgShow"
      :close-on-click-modal="false"
      width="80%"
      customFooter
      @close="isDlgShow = false">
      <el-alert
          title="每成功添加一个商品，将消耗10金币"
          type="success"
          :closable="false" style="margin-bottom: 10px;">
        </el-alert>
      <el-form class="ai-form" style="margin-top: 20px" :model="addUrlForm" label-width="120px" ref="addUrlForm">
        <el-form-item
          prop="urls"
          label="商品地址"
          :rules="[{ required: true, message: '请输入TEMU商品地址，多个用英文,号或换行隔开', trigger: 'blur' }]">
          <el-input type="textarea" placeholder="请输入TEMU商品地址，多个用英文,号或换行隔开" :rows="20" v-model="addUrlForm.urls"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="isAddUrlDlgShow = false">取 消</el-button>
        <el-button type="primary" @click="addUrl">确定</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 style="width: 180px;" @click="isTipDlgShow = false, isLoading = true, currentIndex ++, beginCollect()">跳过</el-button>
        <el-button type="primary" @click="gotoValid">前往验证</el-button>
      </div>
    </ai-dialog>
  </div>
</template>

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

  export default {
    name: 'List',

    data () {
      return {
        search: {
          current: 1,
          type: '1',
          size: 10
        },
        colConfigs: [
          { type: "selection", width: '70px', align: 'left' },
          { prop: 'name', label: '分组名称', align: 'left' },
          { prop: 'total', label: '商品个数', align: 'left' },
          { prop: 'lastUpdateTime', label: '上一次更新时间', align: 'left' },
          { prop: 'createTime', label: '添加时间', width: '180px', fixed: 'right'}
        ],
        tableData: [],
        total: 0,

        form: {
          name: ''
        },

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

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

        isLoading: false,

        selectRows: [],
        isBatchCollect: false,

        isAddUrlDlgShow: false,
        addUrlForm: {
          groupId: '',
          urls: ''
        },

        loadingText: '正在采集中……',
        isTipDlgShow: false,
        errorUrl: '',
        collectList: [],
        currentIndex: 0,
        collectData: {
          groupId: ''
        }
      }
    },

    created () {
      this.getList()
    },

    methods: {
      getList () {
        this.$http.post('/api/singleGroup/myPage',null,{
            params: {
                ...this.search
            }
        }).then(res => {
            this.tableData = res.data.records
            this.total = res.data.total
        })
      },
      onChooseChange (val) {
        this.selectRows = val;
      },
      saveGroup () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$http.post(`/api/singleGroup/add`, this.form).then(res => {
              if (res.code == 0) {
                this.$message.success('添加成功！')
                this.getList()
                this.isDlgShow = false
              }
            })
          }
        })
      },
      toUpdateGroup (obj) {
        this.updateObj = obj
        this.updateForm.name = obj.name
        this.isUpdateDlgShow = true
      },
      updateGroup () {
        this.$refs.updateForm.validate((valid) => {
          if (valid) {
            this.$http.post(`/api/singleGroup/update`, {id: this.updateObj.id, name: this.updateForm.name}).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/singleGroup/delByIds', ids
          ).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功！')
              this.getList()
            }
          })
        })
      },
      deleteGroup(id) {
        this.$confirm('确定要删除？', '温馨提示', {
          type: 'warning'
        }).then(() => {
          this.$http.post('/api/singleGroup/del',null, {
            params: {
              id: id
            }
          }
          ).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功！')
              this.getList()
            }
          })
        })
      },
      toDetail (id, content) {
        this.$emit('change', {
          type: 'Detail',
          params: {
            id: id || '',
            content: content
          }
        })
      },
      addGroup() {
        this.form.mallId = ''
        this.isDlgShow = true
      },
      toAddUrl(row) {
        this.isAddUrlDlgShow = true
        this.addUrlForm.groupId = row.id
        this.addUrlForm.urls = ''
      },
      addUrl() {
        this.$refs.addUrlForm.validate((valid) => {
          if (valid) {
            let params = []
            let arr = this.addUrlForm.urls.split(/[\n,]/).map((value) => value.trim());
            arr.map(url => {
              let urlParams = this.parseURL(url)
              let tmpUrl = url.substring(0,url.indexOf(".html"))

              if (tmpUrl.lastIndexOf("-g-") > 0) {
                tmpUrl = tmpUrl.substring(tmpUrl.lastIndexOf("-g-"), tmpUrl.length);
                tmpUrl = tmpUrl.substring(3, tmpUrl.length);
                params.push({
                  groupId: this.addUrlForm.groupId,
                  goodsUrl: url,
                  goodsId: tmpUrl
                })
              } else {
                let urlParams = this.parseURL(url)
                if (urlParams.params) {
                  let goodsId = urlParams.params.goods_id
                  if (goodsId) {
                    params.push({
                      groupId: this.addUrlForm.groupId,
                      goodsUrl: url,
                      goodsId: goodsId
                    })
                  }
                }
              }
            })
            this.$http.post(`/api/singleGroup/saveGoods`, params).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.getList()
                this.isAddUrlDlgShow = false
              }
            })
          }
        })
      },
      toBegin(row) {
        this.isLoading = true

        this.collectData.groupId = row.id
        this.collectData.details = []

        this.$http.post(`/api/singleGroup/getGoodsList`, null, {params: {
          id: row.id
        }}).then(res => {
          if (res.code == 0) {
            this.collectList = res.data
            this.currentIndex = 0

            this.beginCollect()
          }
        })

        
      }, 
      async beginCollect() {
        this.loadingText = `正在采集第（${this.currentIndex}/${this.collectList.length}）个商品的商品信息`
        if (this.currentIndex == this.collectList.length) {
          let res = await this.$http.post(`/api/singleGoodsDetail/addDetails`, this.collectData)
          if (res.code == 0) {
            this.getList()
          }
          this.isLoading = false
          this.$message.success('采集成功')
          return
        }
        let res = await sendTemuAPIMessage({
          url: 'api/oak/integration/render',
          anti: true,
          data: {
            goods_id: this.collectList[this.currentIndex].goodsId
          }})
        
        if (!res.goods || !res.goods.productName) {
          res = await sendChromeWebReqMessage({
            type: 'temu',
            url: this.collectList[this.currentIndex].goodsUrl,
          })

          if (res.indexOf("window.rawData") == -1) {
            this.$message.error("请检查地址是否正确，或者“TEMU”网站是否出现图形验证码")

            this.isLoading = false
            this.errorUrl = this.collectList[this.currentIndex].goodsUrl
            this.isTipDlgShow = true
            return
          } else {
            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 goods = goodsObj.store.goods

            this.collectData.details.push({
              groupId: this.collectData.groupId,
              price: goods.minOnSalePrice / 100,
              saleTotal: goods.soldQuantity,
              goodsId: goods.goodsId,
              url: 'https://www.temu.com/goods.html?goods_id=' +goods.goodsId,
              imgUrl: goods.hdThumbUrl,
              mallId: goods.mallId
            })

            this.currentIndex ++
            this.beginCollect()
          }
        } else {
          this.collectData.details.push({
            groupId: this.collectData.groupId,
            price: res.goods.min_on_sale_price / 100,
            saleTotal: res.goods.sold_quantity,
            goodsId: res.goods.goods_id,
            url: 'https://www.temu.com/goods.html?goods_id=' + res.goods.goods_id,
            imgUrl: res.goods.hd_thumb_url,
            mallId: res.goods.mall_id
          })

          this.currentIndex ++
          this.beginCollect()
        }
        
      },
      gotoValid() {
        window.open(this.errorUrl, '_blank');
      },
      parseURL(url) { 
        let a = document.createElement('a'); 
        a.href = url; 
        return { 
          source: url, 
          protocol: a.protocol.replace(':',''), 
          host: a.hostname, 
          port: a.port, 
          query: a.search, 
          params: (function(){ 
            var ret = {}, 
            seg = a.search.replace(/^\?/,'').split('&'), 
            len = seg.length, i = 0, s; 
            for (;i<len;i++) { 
                if (!seg[i]) { continue; } 
                 s = seg[i].split('='); 
                 ret[s[0]] = s[1]; 
             } 
             return ret; 
          })(), 
          file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1], 
          hash: a.hash.replace('#',''), 
          path: a.pathname.replace(/^([^\/])/,'/$1'), 
          relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1], 
          segments: a.pathname.replace(/^\//,'').split('/') 
        }; 
      }
    }
  }
</script>

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