<template>
  <div>
    <ai-list class="list" v-loading="isLoading" :element-loading-text="'数据正在加载中……'">
      <ai-title
        slot="title"
        title="商品模板"
        tips="请先在当前浏览器登录“速卖通跨境卖家中心”，期间保持登录状态"
        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="remove()">删除</el-button>
              <el-button type="button" :class="'el-button el-button--primary'" @click="toAddTemplate()">添加商品模板</el-button>
              <el-button type="button" :class="'el-button el-button--primary'" @click="beforeAddToDraft">添加到草稿箱</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="handleSelectionChange"
            @getList="getList">
          </ai-table>
        </div>
      </template>
    </ai-list>

    <el-dialog
      title="商品列表"
      :visible.sync="dlgShow"
      :close-on-click-modal="false"
      width="80%"
      :before-close="handleClose">
      <ai-list class="list">
        <template slot="content">
          <div class="content">
            <ai-search-bar>
              <template #left>
                <div class="search-item">
                  <label style="width:90px">模板来源：</label>
                  <el-select v-model="productPage.from" @change="productTableData = [], productPage.total = 0, productPage.page =1, getProductOrDraftList()" placeholder="请选择">
                    <el-option
                      key="0"
                      label="商品列表"
                      value="0">
                    </el-option>
                    <el-option
                      key="1"
                      label="草稿箱列表"
                      value="1">
                    </el-option>
                  </el-select>
                </div>
                <div class="search-item">
                  <label style="width:90px">商品名称：</label>
                  <el-input size="small" placeholder="请输入商品名称" v-model="productPage.productName" @keyup.enter.native="productPage.page =1, getProductList()"></el-input>
                </div>
              </template>
              <template #right>
                <el-button @click="productPage= {
                      page: 1,
                      pageSize: 10,
                      from: '0',
                      productName: '',
                      productSkcIds: ''
                    }, getProductOrDraftList()">重置</el-button>
                <el-button type="primary" @click="productPage.page =1, getProductOrDraftList()">查询</el-button>
              </template>
            </ai-search-bar>
            <ai-table
              :tableData="productTableData"
              :col-configs="productColConfigs"
              :total="productPage.total"
              :current.sync="productPage.page" :size.sync="productPage.pageSize"
              style="margin-top: 8px;"
              @selection-change="productHandleSelectionChange"
              @getList="getProductOrDraftList">
              <el-table-column slot="imageUrl" width="120px" label="图片" align="center">
                <template slot-scope="scope">
                  <div>
                    <el-image :src="scope.row.imageUrl" class="image" :preview-src-list="[scope.row.imageUrl]" />
                  </div>
                </template>
              </el-table-column>
            </ai-table>
          </div>
        </template>
      </ai-list>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dlgShow = false">取 消</el-button>
        <el-button type="primary" @click="saveProduct">添加到模板</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {sendChromeAPIMessage, sendAliexpressAPIMessage} from '@/api/chromeApi'
import {timestampToTime} from '@/utils/date'
import {transformShein} from '@/utils/product'
import { Message } from 'element-ui'
import AiLazyCascader from "@/components/AiLazyCascader.vue"

  export default {
    name: 'CopyProduct',
    components: {AiLazyCascader},
    data () {
      return {
        search: {
          current: 1,
          size: 10,
          productName: '',
          mallName: '',
          startDate: '',
          endDate: ''
        },
        colConfigs: [
          { type: "selection", width: '70px', align: 'left', fixed: 'left'},
          { prop: 'productSpu', label: 'SPU', width: 180, align: 'left' },
          { prop: 'productName', label: '商品名称', align: 'left' },
          { prop: 'createTime', label: '添加时间', width: '180px', fixed: 'right'}
        ],
        tableData: [],
        total: 0,
        ids: [],

        dlgShow: false,
        productTableData: [],
        productPage: {page: 1, pageSize: 10, mallId: '', from: '0', productName: '', productSkcIds: '', total: 0},
        productColConfigs: [
          { type: "selection", width: '70px', align: 'left', fixed: 'left'},
          { prop: 'productSpu', label: 'SPU ID', width: 180, align: 'left' },
          { slot: 'imageUrl', label: '图片', align: 'left' },
          { prop: 'productName', label: '商品名称', align: 'left' },
          { prop: 'createTime', label: '创建时间', width: 180, align: 'left' }
        ],

        productIds: [],
        siteList: [],
        isLoading: false
      }
    },

    created () {
      this.getList()
    },

    methods: {
      getList () {
        this.$http.post('/api/product/myPage?type=1',null,{
            params: {
                ...this.search
            }
        }).then(res => {
            this.tableData = res.data.records
            this.total = res.data.total
        })
      },
      remove () {
        if (this.ids.length <= 0) {
          alert('请选择要删除的商品');
          return;
        }
        this.$confirm('确定要删除？', '温馨提示', {
          type: 'warning'
        }).then(() => {
          this.$http.post('/api/product/delByIds',this.ids
          ).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功！')
              this.getList()
            }
          })
        })
      },
      handleSelectionChange(val) {
        this.ids = [];
        val.forEach(e => {
          this.ids.push(e.id);
        });
      },

      // 添加模板
      handleClose() {
        this.productTableData = []
        this.productPage = {page: 1, pageSize: 10, from: '0', total: 0}
        this.dlgShow = false
      },
      toAddTemplate() {
        this.$http.post('/api/malluser/info').then(res => {
          if (res.code == 0) {
            this.$store.commit('setUserInfo', res.data)
            if (res.data.flag != 1) {
              Message.error('您的账号未激活或已失效，请激活后使用')
              this.$store.commit('setActiveDlgShow', true)
              return;
            }
            this.dlgShow = true
            this.getProductOrDraftList()
          }
        })
      },
      getProductOrDraftList() {
        if (this.productPage.from == '0') {
          this.getProductList()
        } else {
          this.getDraftList()
        }
      },
      getDraftList() {
        let params = {};
        params.page = this.productPage.page;
        params.pageSize = this.productPage.pageSize;
        if (this.productPage.productName) {
          params.productName = this.productPage.productName
        }
        sendChromeAPIMessage({
          url: 'bg-visage-mms/product/draft/pageQuery',
          needMallId: true,
          mallId: this.productPage.mallId,
          data: {
            ...params
        }}).then((res) => {
          if (res.errorCode == 1000000) {
            this.productPage.total = res.result.total
            this.productTableData = res.result.pageItems.map((item) => {
              return {
                productSpu: item.productDraftId,
                productSkc: '',
                productName: item.productName,
                createTime: timestampToTime(item.updatedAt)
              };
            })
          } else {
            this.getDraftList()
          }
        });
      },
      async getProductList() {
        this.isLoading = true
        let url = "https://seller-acs.aliexpress.com/h5/mtop.global.merchant.self.product.manager.render.list/1.0/?jsv=2.7.2&appKey=30267743&t=1713978403051&sign=ba2bda69b4a2695c7279d4bc05f51741&v=1.0&timeout=15000&H5Request=true&url=mtop.global.merchant.self.product.manager.render.list&__channel-id__=701301&api=mtop.global.merchant.self.product.manager.render.list&type=originaljson&dataType=json&valueType=original&x-i18n-regionID=AE"
        url = url + "&data=" + encodeURIComponent(
          JSON.stringify({
            "channelId": "701301",
            "jsonBody": JSON.stringify({
              "tab": "online_product",
              "sort": {},
              "filter": {
                "queryCategory": null,
                "lowerPrice": null,
                "upperPrice": null,
                "status": "0",
                "productId": null,
                "pagination": {
                  "pageSize": this.productPage.page,
                  "current": this.productPage.pageSize
                }
              }
            }),
            "from":"SELF",
            "bizParam":"{\"version\":\"simple\"}"
          })
        )
        let res = await sendAliexpressAPIMessage({
          url: url
        })
        res = JSON.parse(res)
        this.isLoading = false
        if (res.ret.indexOf('SUCCESS::调用成功') >= 0) {
          this.productPage.total = res.data.data.pagination.total
          this.productTableData = res.data.data.table.dataSource.map((item) => {
            return {
              productSpu: item.productId,
              productName: item.itemDesc.title,
              imageUrl: item.itemDesc.imageUrl,
              createTime: timestampToTime(item.selfCreateDesc)
            };
          })
        }
      },
      productHandleSelectionChange(val) {
        this.productIds = [];
        val.forEach(e => {
          this.productIds.push(e.productSpu);
        });
      },
      saveProduct() {
        if (this.productIds.length <= 0) {
          Message.error('请选择商品');
          return;
        }
        this.productIds.map((productSpu, index) => {
          setTimeout(() => {
            if (this.productPage.from == '0') {
              this.saveProductTemplate(productSpu, index)
            } else {
              this.saveDraftTemplate(productSpu, index)
            }
          }, 200 * index)
        })
      },
      saveProductTemplate(spu, index) {
        sendGeiwohuoAPIMessage({
          url: 'spmp-api-prefix/spmp/product/get_product_detail',
          data: {
            spu_name: spu
        }}).then((res) => {
          if (res.code == 0) {
            let content = transformShein(res.info)
            let productName = res.info.multi_language_name_list.filter(item => {
              return item.language == 'zh-cn'
            })
            console.log(productName)
            this.$http.post('/api/product/add', {
                productSpu: res.info.spu_name,
                productName: productName[0].name,
                type: 2,
                content: content
              }).then(res1 => {
              if (res1.code == 0) {
                Message.success("商品【" + productName[0].name + "】成功添加为商品模板")
                if (index == this.productIds.length - 1) {
                  this.getList()
                }
              }
            })
          } else {
            this.saveProductTemplate(spu, index)
          }
        })
      },
      saveDraftTemplate(spu, index) {
        sendChromeAPIMessage({
          url: 'bg-visage-mms/product/draft/query',
          needMallId: true,
          mallId: this.productPage.mallId,
          data: {
            productDraftId: spu
        }}).then((res) => {
          if (res.errorCode == 1000000) {
            let content = transformShein(res.info)
            let productName = res.info.multi_language_name_list.filter(item => {
              return item.language == 'zh-cn'
            })
            this.$http.post('/api/product/add', {
                productSpu: spu,
                productName: productName[0].name,
                content: content,
                type: 2
              }).then(res1 => {
              if (res1.code == 0) {
                Message.success("商品【" + productName[0].name + "】成功添加为商品模板")
                if (index == this.productIds.length - 1) {
                  this.getList()
                }
              }
            })
          } else {
            this.saveDraftTemplate(spu, index)
          }
        })
      },
      beforeAddToDraft() {
        if (this.ids.length <= 0) {
          Message.error('请选择商品模板');
          return;
        }
        this.addToDraft()
      },
      addToDraft() {
        this.ids.map((id, index) => {
          let product = this.tableData.filter((item) => {
            return item.id == id
          })
          let content = JSON.parse(product[0].content)
          setTimeout(() => {
            sendGeiwohuoAPIMessage({
              url: 'spmp-api-prefix/spmp/product/save_draft',
              data: content
            }).then((res) => {
              if (res.code == 0) {
                Message.success("商品【" + product[0].productName + "】成功添加到草稿箱")
              } else {
                Message.error(res.errorMsg)
              }
            })
          }, 1000*index)
        })
      }
    }
  }
</script>

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