<template>
    <div>
        <el-alert
          title="采集一个商品添加进草稿箱，将消耗20金币"
          type="success"
          :closable="false" style="margin-bottom: 10px;">
        </el-alert>
        <el-form class="ai-form" :model="form" label-width="150px" ref="form">
            <el-form-item v-if="!isMultiCopy" label="商品地址：" style="width: 100%;" prop="url" :rules="[{ required: true, message: '请输入商品地址', trigger: 'blur' }]">
              <el-input type="textarea" :rows="5" v-model="form.url"></el-input>
            </el-form-item>
            <el-form-item label="店铺：" style="width: 100%;" prop="targetMallId" :rules="[{ required: true, message: '请选择店铺', trigger: 'blur' }]">
            <el-select style="width: 380px" v-model="form.targetMallId" @change="onMallChange" placeholder="请选择">
                <el-option
                v-for="item in $store.state.mallList"
                :key="item.mallId"
                :label="item.mallName"
                :value="item.mallId">
                </el-option>
            </el-select>
            </el-form-item>
            <el-form-item v-if="form.isSemi" label="经营站点" style="width: 100%;" prop="siteId" :rules="[{ required: true, message: '请选择经营站点', trigger: 'blur' }]">
              <el-select style="width: 380px" multiple v-model="form.siteId" placeholder="请选择">
                <el-option
                  v-for="item in siteList"
                  :key="item.siteId"
                  :label="item.siteName"
                  :value="item.siteId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              prop="isSameCategory"
              label="是否保持相同类目："
              :rules="[{ required: true, message: '请选择是否保持相同类目', trigger: 'blur' }]">
              <el-radio-group v-model="form.isSameCategory" size="medium">
                <el-radio :label="false">否</el-radio>
                <el-radio :label="true">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="!form.isSameCategory" label="商品分类：" style="width: 100%;" prop="targetCatId" :rules="[{ required: true, message: '请选择商品分类', trigger: 'blur' }]">
            <ai-lazy-cascader 
              style="width: 380px" 
              v-model="form.targetCatId" 
              filterable
              :props="props"></ai-lazy-cascader>
            </el-form-item>
        </el-form>
        <div class="bottom flex-center">
            <el-button @click="$emit('onClose')">取 消</el-button>
            <el-button type="primary" @click="toAddToDraft" :loading="isCopying">确定</el-button>
        </div>
    </div>
</template>

<script>
import {sendChromeAPIMessage, sendTemuAPIMessage, sendChromeWebReqMessage} from '@/api/chromeApi'
import AiLazyCascader from "@/components/AiLazyCascader.vue"
import { Message } from 'element-ui'
import { MessageBox } from 'element-ui';

export default {
    name: 'AiCopyFromTemu',
    props: ['params', 'isMultiCopy'],
    components: {AiLazyCascader},
    data() {
        return {
            props: {
                value: 'catId',
                label: 'catName',
                lazy: true,
                lazyLoad (value, resolve) {
                    sendChromeAPIMessage({
                        url: 'bg-anniston-mms/category/children/list',
                        needMallId: true,
                        data: {
                            parentCatId: value || ''
                        }
                    }).then(res => {
                        if (res.errorCode === 1000000) {
                            resolve(res.result.categoryNodeVOS.map(v => {
                            return {
                                ...v,
                                leaf: v.isLeaf
                            }
                            }))
                        }
                    })
                },
                lazySearch(queryString, resolve) {
                  sendChromeAPIMessage({
                    url: 'bg-anniston-mms/category/search',
                    needMallId: true,
                    data: {
                      searchText: queryString || ''
                    }
                  }).then(res => {
                    if (res.errorCode === 1000000) {
                      resolve(res.result.categoryPaths.map(v => {
                        let value = []
                        let label = []
                        for (let i = 1; i <= 10; i++ ) {
                          if (v['cat'+i+'NodeVO']) {
                            value.push(v['cat'+i+'NodeVO'].catId)
                            label.push(v['cat'+i+'NodeVO'].catName)
                          }
                        }
                        return {
                          catId: value,
                          catName: label
                        }
                      }))
                    }
                  })
                }
            },
            form: {
                url: '',
                type: 1,  // 默认从temu复制
                targetMallId: '',
                targetCatId: [],
                isSameCategory: true,
                isSemi: false,
                siteId: []
            },
            goods: {},
            sku: {},
            productDetail: {},
            isCopying: false,
            goodsId: '',
            currentUrl: '',
            goodsProperty: [],
            catId: null,
            currentIndex: 0,
            successList: [],
            siteList: []
        }
    },
    created () {
      this.getSiteList()
      if (this.params?.url) {
        this.form.url = this.params.url
      }
    },
    methods: {
      onMallChange() {
        if (!this.form.targetMallId) {
          Message.error("请先选择店铺")
          return
        }
        let tempMall = this.$store.state.mallList.filter(item => {
          return item.mallId == this.form.targetMallId
        })
        if (null == tempMall || tempMall.length == 0) {
          Message.error("请先选择店铺")
          return
        } else {
          this.form.isSemi = tempMall[0].isSemiManagedMall
        }
      },
      getSiteList() {
        sendChromeAPIMessage({
          url: 'bg-visage-mms/config/common/site/query',
          needMallId: true,
          mallId: this.$store.state.mallList[0].mallId,
          data: {}}).then((res) => {
            if (res.success) {
              this.siteList = res.result.siteBaseList.filter(item => {
                return item.matchSemiManaged
              })
            }
        })
      },
      toAddToDraft() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.isMultiCopy) {
              this.successList = []
              this.currentIndex = 0
              this.currentUrl = this.params.urlList[this.currentIndex]
              this.execAddToDraft()
            } else {
              this.currentUrl = this.form.url
              this.execAddToDraft()
            }
          }
        })
      },
      execAddToDraft() {
        if (!this.currentUrl.startsWith("http")) {
          this.goodsId = this.currentUrl
          this.addToDraftNew()
        } else {
          let t = this.currentUrl
          let urlParams = this.parseURL(t)
          t = t.substring(0,t.indexOf(".html"))
          if (t.lastIndexOf("-g-") > 0) {
            t = t.substring(t.lastIndexOf("-g-"), t.length);
            t = t.substring(3, t.length);
            this.goodsId = t
            this.addToDraftNew()
          } else if(urlParams.params) {
            let goodsId = urlParams.params.goods_id
            if (!goodsId) {
              this.addToDraft()
            } else {
              this.goodsId = goodsId
              this.addToDraftNew()
            }
          } else {
            this.addToDraft()
          }
          
        }
      },
      async addToDraftNew() {
        this.isCopying = true
        sendTemuAPIMessage({
          url: 'api/oak/integration/render',
          anti: true,
          data: {
            goods_id: this.goodsId
          }}).then((res) => {
            if (!res.goods || !res.goods.productName) {
              //this.isCopying = false
              //Message.error("获取商品信息失败，采集失败")
              this.addToDraft()
              return
            }
            this.goods = res.goods
            this.sku = res.sku
            this.productDetail = res.product_detail
            this.catId = this.goods.cat_id
            this.goodsProperty = this.goods.goods_property
            let specIds = []
            this.sku.forEach(item => {
              item.specs.forEach(item1 => {
                let flag = false
                specIds.forEach(item2 => {
                  if (item2.spec_value == item1.spec_value) {
                    flag = true
                  }
                })
                /*if (!flag && (item1.specKeyId != 1001 && item1.specKeyId != 43404162)) {
                  specIds.push({spec_key_id: item1.spec_key_id, spec_value: item1.spec_value})
                }*/
              })
            })

            Promise.all(specIds.map(item => this.getSpecIdNew(item).then(res => {
              this.sku.forEach(item1 => {
                item1.specs.forEach(item2 => {
                  if (item2.spec_value == item.spec_value) {
                    item2.spec_value_id = res.result.specId
                  }
                })
              })
              return 0
            }))).then(() => {
              this.$http.post('/api/copyProduct/translateNew',{type: 1, goods: this.goods, sku: this.sku, productDetail: this.productDetail}).then(res => {
                if (res.code == 0) {
                  this.createDraft(res.data)
                }
              })
            })
          })
      },
      async addToDraft() {
        this.isCopying = true
        this.$http.post('/api/copyProduct/check',null, {params: {type: 0}}).then(res => {
          if (res.code == 0) {
            let source
            if (this.form.type == '1') {
              source = 'temu'
            } else if (this.form.type == '2') {
              source = 'aliexpress'
            }
            sendChromeWebReqMessage({
              type: source,
              url: this.currentUrl,
            }).then((res) => {
              if (this.form.type == '1') {
                if (res.indexOf("window.rawData") == -1) {
                  this.isCopying = false
                  Message.error("请检查地址是否正确，或者“TEMU”网站是否出现图形验证码")
                  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)
                this.goods = goodsObj.store.goods
                this.sku = goodsObj.store.sku
                this.catId = this.goods.catId
                this.goodsProperty = this.goods.goodsProperty
                this.productDetail = goodsObj.store.productDetail

                let specIds = []
                this.sku.forEach(item => {
                  item.specs.forEach(item1 => {
                    let flag = false
                    specIds.forEach(item2 => {
                      if (item2.specValue == item1.specValue) {
                        flag = true
                      }
                    })
                    /*if (!flag && (item1.specKeyId != 1001 && item1.specKeyId != 43404162)) {
                      specIds.push({specKeyId: item1.specKeyId, specValue: item1.specValue})
                    }*/
                  })
                })

                Promise.all(specIds.map(item => this.getSpecId(item).then(res => {
                  this.sku.forEach(item1 => {
                    item1.specs.forEach(item2 => {
                      if (item2.specValue == item.specValue) {
                        item2.specValueId = res.result.specId
                      }
                    })
                  })
                  return 0
                }))).then(() => {
                  this.$http.post('/api/copyProduct/translate',{type: 1, goods: this.goods, sku: this.sku, productDetail: this.productDetail}).then(res => {
                    if (res.code == 0) {
                      this.createDraft(res.data)
                    }
                  })
                })
              } else if (this.form.type == '2') {
                console.log(1)
              }
            })
          } else {
            this.isCopying = false
          }
        })
      },
      async createDraft(data) {
        let reqData = {}
        let catId = null;
        if (this.form.isSameCategory) {
          reqData.catId = this.catId; 
        } else {
          reqData.catId = this.form.targetCatId[this.form.targetCatId.length - 1]
        }
        if (this.form.isSemi) {
          reqData.productSemiManagedReq = {
            bindSiteIds: this.form.siteId
          }
        }
        let res = await sendChromeAPIMessage({
          url: 'bg-visage-mms/product/draft/add',
          needMallId: true,
          mallId: this.form.targetMallId,
          data: reqData})
        
        if (res.errorCode == 1000000) {
          let draftId = res.result.productDraftId
          let content = data
          let i = 0
          if (this.form.isSameCategory) {
            let res2 = await this.$http.post('/api/innerCategory/fullById',null , {
              params: {
                id: reqData.catId
              }
            })
            for (; i < res2.data.length; i++) {
              content['cat' + (i+1) + 'Id'] = res2.data[i]
            }

            let res3 = await sendChromeAPIMessage({
              url: 'bg-anniston-mms/category/template/query',
              needMallId: true,
              mallId: this.form.targetMallId,
              data: {
                catId: reqData.catId,
                productCreateTime: null,
                langList: [
                  "en"
                ]
            }})
            content.productPropertyReqs = []
            for (let j = 0; j < this.goodsProperty.length; j++) {
              let temp = {}

              for (let k = 0; k < res3.result.properties.length; k++) {
                if (this.goodsProperty[j].key == res3.result.properties[k].lang2Name.en) {
                  temp.templatePid = res3.result.properties[k].templatePid
                  temp.pid = res3.result.properties[k].pid
                  temp.refPid = res3.result.properties[k].refPid
                  temp.propName = res3.result.properties[k].name
                  for (let x = 0; x < this.goodsProperty[j].values.length; x++) {
                    if (null == res3.result.properties[k].values) break
                    for (let l = 0; l < res3.result.properties[k].values.length; l++) {
                      if (res3.result.properties[k].values[l].lang2Value.en == this.goodsProperty[j].values[x]) {
                        temp.vid = res3.result.properties[k].values[l].vid
                        temp.propValue = res3.result.properties[k].values[l].value
                        temp.valueUnit = ''
                        temp.valueExtendInfo = ''
                        temp.controlType = res3.result.properties[k].values[l].controlType

                        content.productPropertyReqs.push({...temp})
                        break
                      }
                    }
                  }

                }
              }
            }
          } else {
            for (; i < this.form.targetCatId.length; i++) {
              content['cat' + (i+1) + 'Id'] = this.form.targetCatId[i]
            }
          }
          for (; i < 10; i++) {
            content['cat' + (i+1) + 'Id'] = ''
          }

          content.productDraftId = draftId

          this.createProduct(content)
        } else {
          setTimeout(() => {
            this.createDraft(data)
          }, 500)
        }
      },
      createProduct(content) {
        if (this.form.isSemi) {
          content.productSemiManagedReq = {
            bindSiteIds: this.form.siteId
          }
        }
        sendChromeAPIMessage({
          url: 'bg-visage-mms/product/draft/save',
          needMallId: true,
          mallId: this.form.targetMallId,
          data: {
            ...content
        }}).then((res) => {
          if (res.errorCode == 1000000) {
            this.successList.push(this.currentUrl)
            this.saveInfo()
            if (this.isMultiCopy) {
              this.currentIndex ++
              if (this.currentIndex == this.params.urlList.length) {
                this.isCopying = false
                this.$emit('onSuccess')
                MessageBox.alert(`成功添加${this.successList.length}个商品进入草稿箱`)
              } else {
                this.currentUrl = this.params.urlList[this.currentIndex]
                this.execAddToDraft()
              }
            } else {
              this.isCopying = false
              Message.success("成功添加到草稿箱")
            }
            
          } else {
            setTimeout(() => {
              this.createProduct(content)
            }, 500)
          }
        })
      },
      getSpecIdNew(data) {
        return sendChromeAPIMessage({
          url: 'bg-anniston-mms/sku/spec/byName/queryOrAdd',
          needMallId: true,
          mallId: this.form.targetMallId,
          data: {
            parentSpecId: data.spec_key_id,
            specName: data.spec_value
        }}).then((res) => {
          if (res.errorCode == 1000000) {
            return res
          } else {
            this.getSpecIdNew(data)
          }
        })
      },
      getSpecId(data) {
        return sendChromeAPIMessage({
          url: 'bg-anniston-mms/sku/spec/byName/queryOrAdd',
          needMallId: true,
          mallId: this.form.targetMallId,
          data: {
            parentSpecId: data.specKeyId,
            specName: data.specValue
        }}).then((res) => {
          if (res.errorCode == 1000000) {
            return res
          } else {
            this.getSpecId(data)
          }
        })
      },
      saveInfo() {
        let mallInfo = this.$store.state.mallList.filter(item => {
          return item.mallId == this.form.targetMallId
        })
        this.$http.post('/api/copyProduct/add', {
            mallId: mallInfo[0].mallId,
            mallName: mallInfo[0].mallName,
            url: this.currentUrl,
            type: this.form.type
          }).then(res1 => {
          if (res1.code == 0) {
            this.$store.dispatch('getUserInfo')
            if (!this.isMultiCopy) {
              this.$emit('onSuccess')
            }
          }
        })
      },
      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">
.bottom {
    justify-content: center;
  }
</style>