<template>
    <GuipDialog :dialogVisible="dialogVisible" :showFooterButton="showFooterButton"
                title="搜索商品" @confirm="handleConfirm" @cancel="handleCancel" @close="handleCancel">
        <div class="domain-wrap">
            <el-form class="el-row demo-ruleForm" ref="formRef">
                <div class="flex flex-between">
                    <GuipInput width="420px" v-model="keywords">
                        <GuipToolTip  slot="suffix">
                            <img src="@/assets/site/input_search.svg"/>
                        </GuipToolTip>
                    </GuipInput>
                    <GuipButton type="primary" @click="handleSearch()">搜索</GuipButton>
                </div>

                <div class="goods-list">
                    <div class="goods-item" v-for="(row) in list" :key="row.num_iid">
                        <img src="@/assets/site/kefuTem.png" alt="">
                        <div class="goods-info">
                            <p>{{row.title}}</p>
                            <p>¥{{row.price}}</p>
                            <GuipSelect v-if="row.skus" v-model="row.skuid" width="200px" placeholder="选择SKU" :options="row.skus"  @change="handleSelectSku(row)"/>
                            <div v-else style="height: 40px"></div>
                        </div>
                        <el-checkbox v-model="row.selected" @change="handleSelectGood(row)"></el-checkbox>
                    </div>
                </div>
            </el-form>
        </div>
    </GuipDialog>
</template>
<script>

import GuipDialog from "@/components/GuipDialog.vue";
import GuipToolTip from "@/components/GuipToolTip.vue";
import GuipInput from "@/components/GuipInput.vue";
import GuipButton from "@/components/GuipButton.vue";
import GuipSelect from "@/components/GuipSelect.vue";

export default {
  name: '',
  props:['uid','type','isPdd'],
  components: {
      GuipSelect,
      GuipButton,
      GuipInput,
      GuipToolTip,
      GuipDialog
  },
  data(){
    return {
        dialogVisible: true,
        showFooterButton: false,
        keywords: '',
        pati: '',
        pageCode: '',
        list: [],
        empty_text: '',
        bindData: {}
    }
  },
  mounted() {
      if(this.isPdd) this.initPddSdk()
  },
  methods:{
      handleConfirm(){
          this.dialogVisible = false;
      },
      handleCancel(){
          this.dialogVisible = false;
          this.$emit('handleBind', this.bindData)
      },
      handleSearch(){
          const that = this
          this.$http('POST', '/agentnew/ajax_get_goods_list', {
              uid: that.uid,
              type: that.type,
              keywords: that.keywords,
              pdd_pati: that.pdd_pati,
              pdd_pagecode: that.pdd_pagecode,
          }, {
              headers: {
                  'Auth': this.token
              }
          }).then(response => {
              if(response.status){
                  if(response.data.length>0){
                      response.data.forEach((item) => {
                          item.skuid = ''
                          item.selected = false
                          if(item.skus){
                              Object.entries(item.skus).forEach(([key, val]) => {
                                  item.skus[key] = `${val.title} ￥${val.price}`;
                              });
                          }
                      });
                      that.$nextTick(() => {
                          that.list = response.data
                          that.showFooterButton = true
                      })
                  } else {
                      that.empty_text = '未查询到相关商品'
                  }
                  return true
              }
              that.empty_text = response.info
          }).catch(error => {
              console.error(error, 'error')
          })
      },
      handleSelectGood(row){
          if(row.selected) {
             if(row.skus && !row.skuid) {
                 this.$nextTick(() => {
                     row.selected = false;
                 });
                 this.$message.warning('请选择SKU');
                 return false
             }
             this.bindData[row.num_iid] = row.skuid
          }else{
             this.$delete(this.bindData, row.num_iid);
          }
      },
      handleSelectSku(row){
          if(row.selected) {
              this.bindData[row.num_iid] = row.skuid
          }
      },
      async getPddPageCode(){
          const that = this
          this.$http('POST', '/agentnew/ajax_get_pdd_page_code', {
              uid: that.uid,
          }, {
              headers: {
                  'Auth': this.token
              }
          }).then(response => {
              return response.data
          }).catch(error => {
              console.error(error, 'error')
          })
      },
      async initPddSdk() {
          const that = this
          this.pageCode = await this.getPddPageCode()

          const script = document.createElement('script');
          script.src = 'https://pfile.pddpic.com/galerie-go/open_sdk/pc.202102201613.js';
          script.onload = () => {
              if (typeof window.PDD_OPEN_init === 'function') {
                  window.PDD_OPEN_init({
                      code: that.pageCode
                      // 对于获取 code 接口或未登录态，可不传 code：PDD_OPEN_init({}, function () { ... })
                  }, function () {
                      // 初始化已完成
                      window.PDD_OPEN_getPati().then(function (pati) {
                          that.pati = pati
                      }).catch(error => console.log(error))
                  });
              } else {
                  console.error('PDD_OPEN_init 不存在，SDK 未正确加载');
              }
          };
          script.onerror = () => {
              console.error('拼多多 SDK 加载失败');
          };
          document.head.appendChild(script);
      }
  }
}
</script>
<style lang="scss">
.el-form-item{
    margin: 0;
}
.el-dialog{
  min-height: 0;
}

.goods-list{
  max-height: 400px;
  overflow-y: scroll;
  .goods-item{
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 8px;
    background: #FAFAFA;
    padding: 16px;
    margin-top: 16px;
    letter-spacing: 0.08em;

    img{
      width: 80px;
      height: 80px;
    }

    .goods-info{
      width: 100%;
      margin: 0 22px;

      p{
        font-size: 14px;
        color: #1E2226;
      }
      p:nth-child(2){
        margin: 12px 0;
        color: #626573;
      }
    }
  }
}
</style>