<template>
  <div>
    <el-drawer title="新增关联商品" v-if="drawer" :wrapperClosable="false" :visible.sync="drawer" :before-close="handleClose" destroy-on-close
      direction="rtl" size="70%">
      <div class="shop_drawer_box demo-drawer__content">
        <div class="addFormBox">
          <el-form ref="addForm" label-width="80px" :model="dataForm">
            <el-form-item label="商品名称" prop="keywords" class="form_item">
              <el-input size="small" placeholder="请输入商品名称" style="width: 100%" v-model="dataForm.keywords" clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="商品类型" prop="type" class="form_item">
              <el-select size="small" v-model="dataForm.type" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in goodsTypeList" :key="item.dictType" :label="item.dictValue"
                  :value="item.dictType">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="" class="form_item" label-width="20px" style="width: 160px !important">
              <el-button type="primary" plain @click="
      pageIndex = 1;
    getDataList(bookMarketId);
    " size="small">查询</el-button>
              <el-button @click="handleReset()" size="small" plain>重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table ref="table" height="80%" :data="dataList" :row-key="getRowKeys" border size="mini"
          v-loading="dataListLoading" @selection-change="handleSelectionChange" style="width: 100%">
          <!-- <el-table-column :reserve-selection="true" type="selection" header-align="center" align="center" width="50">
          </el-table-column> -->
          <!--  -->
          <el-table-column label="商品ID" width="70" align="center" prop="productId">
            <!-- <template slot-scope="scope">
            {{ (pageIndex - 1) * pageSize + scope.$index + 1 }}
          </template> -->
          </el-table-column>
          <el-table-column prop="productName" header-align="center" align="center" label="商品名称">
          </el-table-column>
          <el-table-column prop="price" width="120" header-align="center" align="center" sortable label="价格">
          </el-table-column>
          <el-table-column prop="activityPrice" width="120" header-align="center" align="center" sortable label="活动价">
          </el-table-column>
          <el-table-column prop="productStock" width="120" header-align="center" align="center" sortable label="库存">
          </el-table-column>
          <el-table-column header-align="center" align="center" label="商品图" width="120">
            <template slot-scope="scope">
              <img v-if="scope.row.productImages != ''" :src="scope.row.productImages" width="25" height="35"
                class="tableImg" />
            </template>
          </el-table-column>
          <el-table-column prop="productStock" width="120" header-align="center" align="center" sortable label="操作">
            <template slot-scope="scope">
              <el-button type="primary"  plain size="mini" @click="addLink(scope.row, scope.$index)">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>

        <!-- <div class="demo-drawer__footer">
          <div style="float: right; margin-top: 20px">
            <el-button @click="close" size="small">取 消</el-button>
            <el-button type="primary" @click="submit" :loading="loading" size="small">{{ loading ? "提交中 ..." : "确 定"
              }}</el-button>
          </div>
        </div> -->
        <!-- 弹窗, 新增 / 修改 -->
        <!-- <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList" @showchooseBookf = "showchooseBookf"></add-or-update>
      <choose-book v-if="chooseBookVisible" :bookIds = bookIds ref="chooseBook" :chooseBookVisible = chooseBookVisible @closeBookf = "closeBookf"></choose-book>   -->
      </div>
    </el-drawer>
  </div>
</template>

<script>
// import chooseBook from './chooseBook.vue'
// import AddOrUpdate from './shopproduct-add-or-update'
export default {
  props: ["currentType", "currentId"],
  data() {
    return {
      timer: null,
      drawer: false,
      loading: false,
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      idKey: "productId", // 标识列表数据中每一行的唯一键的名称(需要按自己的数据改一下)
      dataForm: {       
        type:'00'
      },
      bookMarketId: null,
      dataList: [],
      publishStatus: false,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      chooseBookVisible: false,
      bookIds: [],
      goodsTypeList: [],
      linkList:[]
    };
  },
  components: {
    // AddOrUpdate,
    // chooseBook
  },
  activated() {
    this.getDataList();
  },
  methods: {   
    addLink(row,i){    
      // 添加商品绑定
      this.linkList.push(row)
      console.log('linkList',this.linkList)
      this.dataList.splice(i,1)
      // this.getDataList()
    },
    handleReset() {
      this.dataForm = {
        type:'00'
      };
      this.pageIndex = 1;
      this.getDataList();
    },
    submit() {
      // var ids = this.multipleSelection.map((e) => e.productId).toString(",");
      // this.$emit("submit", ids);
      // console.log(
      //   "🚀 ~ submit ~ this.multipleSelection:",
      //   this.multipleSelection
      // );
      // this.drawer = false;
    },

    // 获取商品类型
    getGoodsTypeList() {
      this.$http({
        url: this.$http.adornUrl("/book/sysdictdata/selectByType/goodsType"),
        method: "get",
      }).then(({ data }) => {        
        // console.log(data.dataList) 
        this.goodsTypeList = data.dataList;
      });
    },
    handleClose(done) {  
      
       this.$bus.$emit("linkList",  this.linkList );   
       this.linkList = []
      // this.$emit("linkList", this.linkList)
      done();     
    },
    async open() {
      this.drawer = true;
      this.dataForm = {
        type:'00'
      };
      this.pageIndex = 1;
      await this.getGoodsTypeList();
      await this.getDataList();
    },
    close() {
      this.drawer = false;
      
    },
    getRowKeys(row) {
      return row.productId;
    },
    handleSelectionChange(val) {
      console.log("🚀 ~ handleSelectionChange ~ val:", val);
      // table组件选中事件,记得加上@selection-change="handleSelectionChange"
      this.multipleSelection = val;
      // this.changePageCoreRecordData();
    },

    closeBookf() {
      this.chooseBookVisible = false;
    },
    showchooseBookf(e) {
      // 显示图书列表
      this.chooseBookVisible = true;
      // console.log(this.bookIds,'this.bookIds')
      // this.$nextTick(() => {
      //   this.$refs.chooseBook.getBookList()
      //   this.bookIds = e.bookIds
      //   })
    },
    // 获取数据列表
    async getDataList() {
      var form = {
        ...this.dataForm,
        keywords:this.dataForm.keywords ? this.dataForm.keywords : '',
        page: this.pageIndex,
        limit: this.pageSize,
        id: this.currentId      
        // productId: "",
      };      
      this.dataListLoading = true;
      this.clear();   
      // let _url = "/master/shopProduct/listByPage"     
     
    //   await this.$http({
    //         url: this.$http.adornUrl(_url),
    //         method: "post",
    //         data: {
    //           "current": form.page,
    // "limit": form.limit,
    // "productName": form.keywords,
    // "goodsType": form.type
    //         },
    //         header: {
    //           //默认 无 说明：请求头
    //           "Content-Type": "application/json"
    //         }
    //       })
      await this.$http({
        url: this.$http.adornUrl(`/master/course/getProductListForCourse`),
        method: "post",
        data: this.$http.adornData({
          "page": form.page,
    "limit": form.limit,
    "productName": form.keywords,
    "goodsType": form.type,
    "courseId": form.id
        }),
      })
      .then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.shopProductListhopProducts.records;
          this.totalPage = data.shopProductListhopProducts.total;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }       
        this.dataListLoading = false;
      });
    },
    clear() {
      // this.$refs.table.clearSelection();
      this.multipleSelection = [];
    },

    // 每页数
    sizeChangeHandle(val) {
      // this.changePageCoreRecordData();
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      // 改变页的时候调用一次
      // this.changePageCoreRecordData();
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
          return item.productId;
        });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/book/shopproduct/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              },
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
    SwitchChange(event) {
      /*点击时他会自动把你绑定的值变更，直接去请求数据就可以了*/
      var parms = {
        publishStatus: event.publishStatus,
        productId: event.productId,
      };
      // console.log(parms)
      this.$http({
        url: this.$http.adornUrl("/book/shopproduct/update"),
        method: "post",
        data: parms,
      })
        .then((res) => {
          this.$message({
            message: "成功",
            type: "success",
          });
          this.loading = false;
          this.getDataList();
        })
        .catch((error) => {
          this.loading = false;
          console.log(error);
        });
      console.log(event);
    },
  },
};
</script>
<style lang="less" scoped>
.shop_drawer_box {
  padding: 20px !important;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
}

.addFormBox {
  width: 100%;

  // overflow: hidden;
  .form_item {
    width: 33%;
    float: left;
  }
}

::v-deep.el-drawer__header {
  margin-bottom: 10px !important;
}
</style>