<template>
  <div>
    <ai-list class="list" v-loading="isLoading" :element-loading-text="loadingText">
      <ai-title
        slot="title"
        title="上架新品"
        isShowBottomBorder>
        <template #rightBtn>
          <div class="title-right">
            <el-checkbox v-model="isMutiSelect">开启多选</el-checkbox>&nbsp;
            <el-button type="primary" round @click="toAddToGroup" v-if="isMutiSelect">加入分组</el-button>
            上次更新时间：{{ lastUpdateTime }}
            <div>
              <el-button type="button" :class="'el-button el-button--primary'" @click="beginSync">同步</el-button>
            </div>
          </div>
        </template>
      </ai-title>
      <template #left>
        <div class="categoryTree">
          <el-tree ref="tree" lazy :load="loadCategory" node-key="optId" :props="props"
             :default-expanded-keys="defaultExpanded" 
             :expand-on-click-node="false" 
             :check-on-click-node="true"
             :highlight-current="true"
             @node-click="handleNodeClick"/>
        </div>
      </template>
      <template slot="content">
        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr; gap: 16px;">
          <el-card v-for="item in tableData" :key="item.id" :body-style="{ padding: '0px', margin: '5px' }">
            <div :class="[{'img-background': item.isSelect}, 'img-box']" @click="onGoodsSelect(item)">
              <div>
                <el-image v-if="isMutiSelect" :src="item.imgUrl" :class="[{'mask': item.isSelect}, 'image']" />
                <el-image v-else :src="item.imgUrl" class="image" :preview-src-list="[item.imgUrl]" />
              </div>
              <span class="icon-box" v-if="item.isSelect && isMutiSelect">
                <img style="width: 20px; height: 20px" src="../../../../../assets/right.png">
              </span>
            </div>
            
            <div style="padding: 14px;">
              <div class="bottom clearfix">
                <div style="margin-bottom: 5px;">
                  <div style="display: inline; margin-left: 5px;">${{ item.price }}</div>
                  <ai-product-drop-down :params="item" :isShowGroup="true" :isShowDetail="false" :isShowAddFavorite="false" :isShowDelFavorite="false"   
                  style="float: right;"></ai-product-drop-down>
                </div>
              </div>
            </div>
          </el-card>
          <el-pagination
            layout="prev, pager, next"
            style="position: absolute; bottom: 0px; right: 40px;"
            :total="total"
            :page-size.sync="form.size"
            :current-page.sync="form.current"
            @current-change="getList">
            <div class="paginationPre-total">共<label class="color-primary">{{ total }}</label>条记录
            </div>
          </el-pagination>
        </div>
      </template>
    </ai-list>
    <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, toCollect()">已验证，继续采集</el-button>
        <el-button type="primary" @click="gotoValid">前往验证</el-button>
      </div>
    </ai-dialog>
    <ai-dialog
      title="添加到分组"
      :visible.sync="addGroupDlgShow"
      :close-on-click-modal="false"
      width="790px"
      customFooter
      :append-to-body="true"
      @close="addGroupDlgShow = false">
      <el-form class="ai-form" :model="addGroupForm" label-width="120px" ref="addGroupForm">
        <el-form-item label="分组" style="width: 100%;" prop="groupId" :rules="[{ required: true, message: '请选择分组', trigger: 'blur' }]">
          <el-select style="width: 380px" v-model="addGroupForm.groupId" placeholder="请选择分组">
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="addGroupDlgShow = false">取消</el-button>
        <el-button type="primary" @click="addToGroup">确定</el-button>
      </div>
    </ai-dialog>
  </div>
</template>

<script>
import AiProductDropDown from '@/components/AiProductDropDown.vue'
import {sendTemuAPIMessage, sendChromeWebReqMessage} from '@/api/chromeApi'
import { Message } from 'element-ui'

  export default {
    name: 'DetailPage',
    props: ['params'],
    components: {AiProductDropDown},
    data () {
      return {
        props: {
          label: 'name',
          isLeaf: data => data.parentId != 0
        },
        search: {
          current: 1,
          size: 120
        },
        form: {
          current: 1,
          size: 120,
          category: null
        },
        defaultExpanded: [],
        tableData: [],
        total: 0,
        offset: 0,
        pageSize: 120,
        currentData: null,

        isLoading: false,
        isOptApi: true,

        goodsList: [],
        currentIndex: 0,
        errorUrl: '',
        isTipDlgShow: false,

        lastUpdateTime: '',

        treeNode: null,
        treeResolve: null,
        loadingText: '拼命加载中',
        isMutiSelect: false,

        addGroupDlgShow: false,
        addGroupForm: {
          groupId: '',
          goodsId: ''
        },
        groupList: []
      }
    },

    created () {
      this.getList()
      this.getLastUpdateTime()
    },

    methods: {
      loadCategory(node, resolve) {
        this.$http.post('/api/category/listByParent_newProduct',null,{
          params: {
            parentId: node.data?.optId || "0"
          }
        }).then(res => {
          if (res?.data) {
            if (!node.data) {
              this.treeNode = node
              this.treeResolve = resolve
            }
            let data = res.data.map(item => {
              return {
                name: item.name + '(' + item.total + ')',
                optId: item.optId,
                parentId: item.parentId
              }
            })
            data = data.filter(item => {
              return item.optId != -13
            })
            resolve(data)
          } else {
            resolve([])
          }
        })
      },
      getLastUpdateTime() {
        this.$http.post('/api/newProduct/getLastUpdateTime').then(res => {
          if (res?.data) {
            this.lastUpdateTime = res.data
          }
        })
      },
      beginSync() {
        this.loadingText = '拼命加载中'
        this.isLoading = true
        this.offset = 0
        this.getNewProductData()
      },
      async getNewProductData() {
        let res = await sendTemuAPIMessage({
          url: 'api/poppy/v1/title_bar_recommend?scene=home_title_bar_new_in',
          anti: true,
          data: {
            scene: "home_title_bar_new_in",
            offset: this.offset,
            pageSize: this.pageSize,
            filterItems: null
          }})
        
        if (res.success) {
          let arr = []
          for (let i = 0;i < res.result.data.goods_list.length; i++) {
            let item = res.result.data.goods_list[i]

            let data = {
              goodsId: item.goods_id, 
              price: item.price_info.price_schema,
              saleTotal: 0,
              url: 'https://www.temu.com/goods.html?goods_id=' + item.goods_id,
              imgUrl: item.thumb_url,
              mallId: item.mall_id
            }

            arr.push(data)
          }

          let res2 = await this.$http.post('/api/newProduct/addBatch', arr)

          if (res2.code == 0 && res2.data != 1) {
            if (res.result.data.goods_list.length == this.pageSize) {
              this.offset = this.offset + this.pageSize
              this.getNewProductData()
            } else {
              this.updateCategory()
            }
          } else {
            this.updateCategory()
          }
        } else {
          this.isLoading = false
          Message.error("同步新上架商品失败")
        }
      },
      async updateCategory() {
        let res = await this.$http.post('/api/newProduct/getAllGoodsNoCategory')
        if (res.code == 0) {
          this.goodsList = res.data
          this.currentIndex = 0
          this.toCollect()
        } else {
          Message.error("采集失败")
        }
      },
      async toCollect() {
        if (this.currentIndex == this.goodsList.length) {
          this.isLoading = false
          Message.success("采集成功")
          this.treeNode.childNodes = []
          this.loadCategory(this.treeNode,this.treeResolve)
          this.getLastUpdateTime()
          return
        }
        this.loadingText = `正在采集第（${this.currentIndex}/${this.goodsList.length}）个商品的分类信息`
        let res1 = null
        let opts = null
        if (this.isOptApi) {
          res1 = await sendTemuAPIMessage({
            url: 'api/poppy/v1/opt',
            anti: true,
            data: {
              offset: 0,
              page_size: -1,
              mainGoodsId: this.goodsList[this.currentIndex].goods_id,
              scene: "pc_crumb_list"
            }
          })

          if (res1.success && res1.result.data.crumb_opt_list) {
            opts = res1.result.data.crumb_opt_list.map(item1 => {
              return item1.opt_id
            })
          } else {
            this.isOptApi = false
          }

        }
        if (!this.isOptApi) {
          res1 = await sendChromeWebReqMessage({
            type: 'temu',
            url: 'https://www.temu.com/goods.html?goods_id=' + this.goodsList[this.currentIndex].goods_id,
          })
          if (res1.indexOf("window.rawData") == -1) {
            this.isLoading = false
            this.errorUrl = 'https://www.temu.com/goods.html?goods_id=' + this.goodsList[this.currentIndex].goods_id
            this.isTipDlgShow = true
            return
          }
          let str = res1.substring(res1.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 crumbOptList = goodsObj.store.crumbOptList

          opts = crumbOptList.map(item1 => {
            return item1.optId
          })
        }

        if (opts) {
          this.$http.post('/api/newProduct/updateGoodsCategory', null, {params: {goodsId: this.goodsList[this.currentIndex].goods_id,category: opts.join(',')}})
        } else {
          this.isLoading = false
          Message.error("同步类目失败")
          return
        }

        this.currentIndex ++
        this.toCollect()
      },
      getList() {
        this.$http.post('/api/newProduct/page',null,{
          params: {
            category: this.currentData?.optId || '',
            current: this.form.current,
            size: this.form.size
          }
        }).then(res => {
          res.data.records.map(item => {
            item.isSelect = false
          })
          this.tableData = res.data.records
          this.total = res.data.total
        })
      },
      handleNodeClick(data) {
        this.currentData = data
        this.form.current = 1
        this.getList()
      },
      gotoValid() {
        window.open(this.errorUrl, '_blank');
      },
      onGoodsSelect(item) {
        item.isSelect = !item.isSelect
      },
      toAddToGroup() {
        let goodsObj = this.tableData.filter(item => {
          return item.isSelect
        })
        if (goodsObj.length > 0) {
          let goodsIds = goodsObj.map(i => {
            return i.goodsId
          })
          this.$http.post('/api/newProductGroup/myPage?size=1000').then(res => {
            if (res.code == 0) {
              this.addGroupDlgShow = true
              this.addGroupForm.goodsId = goodsIds.join(',')
              this.groupList = res.data.records
            }
          })
        } else {
          Message.error("请选择商品")
        }
      },
      addToGroup() {
      this.$refs.addGroupForm.validate((valid) => {
        if (valid) {
          this.$http.post('/api/newProductGroupDetail/add', {...this.addGroupForm}).then(res => {
            if (res.code == 0) {
              this.addGroupDlgShow = false
              Message.success("商品成功添加到分组")
            }
          })
        }
      })
    }
    }
  }
</script>

<style scoped lang="scss">
.list {
  .title-right {
    display: flex;
    align-items: center;

    & > div:first-child {
      margin-right: 20px;
    }
  }
}
.categoryTree {
  .gap {
    width: 100%;
    height: 17px;
  }

  :deep( .el-tree ) {
    background: #fff;

    .el-tree-node__expand-icon.is-leaf {
      color: transparent !important;
    }

    .el-tree-node__content {
      display: inline-flex;
      min-width: 100%;
    }

    .el-tree-node__content > .el-tree-node__expand-icon {
      padding: 4px;
    }

    .el-tree-node__content {
      height: 32px;
    }

    .el-tree__empty-text {
      color: #222;
      font-size: 14px;
    }

    .el-tree-node__children .el-tree-node__content {
      height: 32px;
    }

    .el-tree-node__content:hover {
      background: #E8EFFF;
      color: #222222;
      border-radius: 2px;
    }

    .is-current > .el-tree-node__content {
      &:hover {
        background: #000;
        color: #fff;
      }

      background: #000;

      span {
        color: #fff;
        font-weight: bold;
      }
    }
  }
}

.time {
    font-size: 13px;
    color: #999;
  }
  
  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
      display: table;
      content: "";
  }
  
  .clearfix:after {
      clear: both
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }


.img-box {
  display: flex;
  justify-content: center;
  align-items: center;
  //父级设置 相对定位，让 icon设置绝对定位时能够以该父级为准。
  position: relative;
  // icon 设置 绝对定位 让其固定在你想要的合适位置。 样式可调整，自己定位即可。
  .icon-box {
    position: absolute;
    top: 35%;
  }
}

.mask {
  background-color: #000;
  opacity: 0.6;

  .el-image__inner {
    opacity: 0.6;
  }
}

::v-deep .mask > img {
  opacity: 0.6;
}

::v-deep .el-loading-spinner {
  top: 200px;
}

.el-icon {
  display: inline-block;
}
</style>
