<!--  -->
<template>
  <div style="padding: 0 10px;background-color:#f7f7f7;">
    <div class="pending" v-if ="ontype == '1'">
      <!-- 搜索 -->
      <div class="formSearch" style="margin-bottom:10px">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="商品名称">
            <el-input v-model="formInline.search" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="上架状态">
            <el-select v-model="formInline.shelveState" placeholder="请选择上架状态">
              <el-option label="全部" :value="null" />
              <el-option label="上架" value="1" />
              <el-option label="下架" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="官方分类">
            <el-cascader v-model="formInline.classifyId" :options="categoryList" clearable :props="{
                checkStrictly: true,
                expandTrigger: 'hover',
                label:'categoryName',
                value:'id',
                children:'childs'
              }" />
          </el-form-item>
        </el-form>
        <div>
          <el-button style="background-color: #3F9B6A;color: #fff" @click="search">查询</el-button>
          <el-button @click="clear" class="buttonHover"
            style="color: #606266;border: 1px solid #dddfe5;background-color: #fff;">重置</el-button>
        </div>

      </div>
      <div style="margin-bottom:20px;">
        <!-- <el-button style="background-color: #3F9B6A;color: #fff" @click="rukdengji"  >入库登记</el-button> -->
        <el-button style="background-color: #3F9B6A;color: #fff" @click="rukdengji">补货</el-button>
        <el-button style="background-color: #3F9B6A;color: #fff" @click="shopzuhe">商品组合</el-button>
        <el-button style="background-color: #3F9B6A;color: #fff" @click="productDataExport">导出商品</el-button>
      </div>
      <!-- 表格 -->
      <div class="tableBox">
        <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange"
          :header-cell-style="{fontSize: '14px',color:'#0009',fontWeight: 'normal',backgroundColor:'#F2F3F5'}">
          <el-table-column type="selection" v-if="teble_sel" min-width="4%">
          </el-table-column>
          <el-table-column prop="productId" label="商品id" show-overflow-tooltip />
          <el-table-column label="商品主图" width="150" align="center">
            <template slot-scope="scope">
              <img height="80" width="80" :src="$baseURL+msgList(scope.row.productImage)" alt srcset>
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" width="220" />
          <el-table-column prop="section" label="售价区间" show-overflow-tooltip />
          <el-table-column prop="memberSection" label="会员价" show-overflow-tooltip />
          <el-table-column prop="ifCredit" label="积分兑换" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.ifCredit == 1">允许</span>
              <span v-if="scope.row.ifCredit == 0">不允许</span>
            </template>
          </el-table-column>
          <el-table-column prop="stockNumber" label="库存" show-overflow-tooltip />
          <el-table-column prop="volume" label="销量" show-overflow-tooltip />
          <el-table-column prop="volume" label="上架状态" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.shelveState==0">未上架</span>
              <span v-if="scope.row.shelveState==1">已上架</span>
              <span v-if="scope.row.shelveState==2">待审核</span>
              <span v-if="scope.row.shelveState==3">审核失败</span>
            </template>
          </el-table-column>
          <el-table-column prop="reject" label="驳回原因" show-overflow-tooltip />
          <el-table-column prop="registrationStatus" label="登记状态" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.registrationStatus==''">未入库</span>
              <span v-if="scope.row.registrationStatus==1">已入库</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <div class="btnList">
                <div class="tableBtn greens" @click="edit(scope.row)">编辑</div>
                <div v-if="scope.row.shelveState==0" class="tableBtn greens" @click="down(scope.row)">上架</div>
                <div v-if="scope.row.shelveState==1" class="tableBtn greens" @click="down(scope.row)">下架</div>
                <div v-if="scope.row.combinationId != '' && scope.row.stockNumber != 0" class="tableBtn greens"
                  @click="chaiFen(scope.row)">拆分</div>
                <div @click="setVipPrice(scope.row)" v-if="scope.row.shelveState==1" class="tableBtn greens">设置会员价</div>
                <div v-if="scope.row.shelveState!=1" class="tableBtn greens" @click="del(scope.row)">删除</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="fenye">
          <el-pagination :current-page="formInline.page" :page-sizes="[10, 20, 50, 100]" :page-size="10" background
            small layout="prev, pager, next,total" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
        <div
          style="padding: 5px 10px 5px 20px;border:1px solid #EBEEF5;display: flex;justify-content: space-between;margin-top: 10px;"
          v-if="teble_sel">
          <div style="font-size: 14px;">
            <span>已选择{{zuheNum}}项</span>
            <div class="tableBtn greens" style="color: #3F9B6A;font-size: 14px;margin-left: 10px;"
              @click="toggleSelection">清楚选项</div>
          </div>
          <div>
            <el-button @click="zuheShop(index)"
              style="background-color: #3F9B6A;color: #fff;">{{index==1?'确定登记':'确定组合'}}</el-button>
            <el-button @click="selClose" class="buttonHover"
              style="color: #606266;border: 1px solid #dddfe5;background-color: #fff;">取消</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/修改商品弹窗 -->
    <!-- <el-dialog :title="!commId ? '新增商品' : '登记商品'" :visible.sync="commidyVisible" width="70%" center
      custom-class="bian_css" top="6vh" :close-on-click-modal="false" @before-close="closeModal" @close="closeModal">
      <CommAdd ref="child" :show-tinymce="showTinymce" :product-id="commId" @cancel="cancelForm"
        :message="parentMessage" />
    </el-dialog> -->
    <div v-if ="ontype == '2'" class="pending">
     
     <CommAdd v-if ="ontype == '2'" ref="child" :show-tinymce="showTinymce" :product-id="commId" @cancel="cancelForm"  :message="parentMessage"/>
   </div>
    <!-- 设置会员价弹窗 -->
    <el-dialog title="设置会员价" :visible.sync="vipPriceVisible" width="50%" class="vipDialog">
      <el-form ref="form" label-width="80px">
        <el-form-item label="优惠方式">
          <el-radio-group v-model="mode">
            <el-radio :label="1">折扣</el-radio>
            <!-- <el-radio :label="2">指定价格</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <div class="priceTable">
          <table>
            <tr>
              <th>规格</th>
              <th>售价</th>
              <th v-for="(item,index) in gradeList" :key="index">
                {{ item }}
              </th>
            </tr>
            <tr v-for="(item,index) in productData" :key="index">
              <td>
                {{ item.value }}
              </td>
              <td>
                {{ item.price }}
              </td>
              <td v-for="(itemJ,indexJ) in item.memberPrices" :key="indexJ" class="td-input">
                <el-input v-model="itemJ.price" oninput="value=value.replace(/([^\d|\.])/g, '')" />
                {{ mode==1?'折':'元' }}
              </td>
            </tr>
          </table>
        </div>
        <el-button style="background-color: #3F9B6A;color: #fff;" class="clearBtn"
          @click="clearProductMember">清除所有旧会员价</el-button>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="vipPriceVisible = false" class="buttonHover"
          style="color: #606266;border: 1px solid #dddfe5;background-color: #fff;">取 消</el-button>
        <el-button style="background-color: #3F9B6A;color: #fff;" @click="vipPriceSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <el-dialog title="入库登记" :visible.sync="rukuShow" width="60%" class="vipDialog">
      <el-form ref="form" label-width="80px">
        <el-form-item label="商品名称">
          <el-select v-model="shopId" filterable placeholder="请选择">
            <el-option v-for="item in tableData" :key="item.productId" :label="item.productName"
              :value="item.productId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否登记">
          <el-radio-group v-model="dengjiMsg">
            <el-radio label="1">是</el-radio>
            <el-radio label="">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rukuShow = false" class="buttonHover"
          style="color: #606266;border: 1px solid #dddfe5;background-color: #fff;">取 消</el-button>
        <el-button type="primary" @click="rukuCheck">确 定</el-button>
      </span>
    </el-dialog> -->
    <el-dialog title="补货" :visible.sync="rukuShow" width="60%" class="vipDialog">
      <el-form ref="form" label-width="80px">
        <el-form-item label="商品名称">
          <el-select v-model="shopId" filterable placeholder="请选择" @change="getShopData">
            <el-option v-for="item in tableData" :key="item.productId" :label="item.productName"
              :value="item.productId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="num" :min="0" :max="9999" ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rukuShow = false" class="buttonHover"
          style="color: #606266;border: 1px solid #dddfe5;background-color: #fff;">取 消</el-button>
        <el-button type="primary" @click="rukuCheck">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import CommAdd from './addCommodity.vue'
  import {
    getBtnList,
    getToken
  } from '@/utils/auth'
  import {
    uploadUrl
  } from '@/utils/request'
  import {
    getClassifyGetAll,
    getClassifyDelete,
    getClassifyStart,
    downloadTemplate,
    importProduct,
    getClassify,
    getProductMembers,
    setProductMember,
    productExport,
    getBrandList,
    chFen,
    getClassifyUpdate,
    getClassifyGetById
  } from '@/api/commodity'
  export default {
    components: {
      CommAdd
    },
    data() {
      // 这里存放数据
      return {
        ontype:'1',
        num:0,
        showTinymce: false,
        btnList: '',
        activeName: 'first',
        formInline: {
          search: '', // 搜索字段
          shelveState: '', // 上架状态 1-上架 0-不上架 null-全部
          stock: '', // 库存状态 1-有库存 0-无库存 null-全部
          classifyId: '', // 最下级分类id
          page: 1, // 当前页
          pageSize: 10
        },
        batchAdd: false,
        total: 1,
        tableData: [],
        categoryList: [],
        UploadUrl: uploadUrl,
        headers: {
          'Authorization-business': getToken()
        },
        productId: 0,
        commidyVisible: false,
        commId: 0,
        brandList: [],
        zuheNum: 0,

        parentMessage: '这是父组件传递给子组件的消息',
        canst: '', //组合商品ID
        index: 1,
        dengji: [],
        vipPriceVisible: false,
        mode: 1,
        productData: [],
        gradeList: [],
        teble_sel: false,
        rukuShow: false,
        dengjiMsg: '',
        shopId: ''
      }
    },
    computed: {},
    mounted() {
      this.getBrandList()
      this.getAll(this.formInline)
      this.queryAllCategory()
      this.btnList = getBtnList()
    },
    // 方法集合
    methods: {
      getShopData(e){
        const targetProduct = this.tableData.find(item => item.productId === e)
        console.log(targetProduct)
        this.num = 0
      },
      msgList(list) {
        if (list && list != '') {
          let strin = list.split(',')
          return strin[0]
        }
      },
      async getBrandList() {
        const {
          data
        } = await getBrandList()
        this.brandList = data
      },
      cancelForm() {
        this.commidyVisible = false
        this.ontype = '1'
        this.formInline = {
          search: '',
          shelveState: '',
          stock: '',
          classifyId: '',
          page: 1,
          pageSize: 10
        }
        this.getAll(this.formInline)
        this.closeModal()
      },
      closeModal() {
        this.showTinymce = false
        this.$refs.child.last()
        this.$refs.child.reset()
      },
      btnClick(id) {
        if (id.permissionName === '新增商品') {
          this.add()
        }
      },
      handleSizeChange(val) {
        this.formInline.pageSize = val
        this.getAll(this.formInline)
      },
      handleCurrentChange(val) {
        this.formInline.page = val
        this.getAll(this.formInline)
      },
      //  查询
      search() {
        this.total = 1
        this.formInline.page = 1
        this.getAll(this.formInline)
      },
      // 重置
      clear() {
        this.formInline = {
          search: '', // 搜索字段
          shelveState: '', // 上架状态 1-上架 0-不上架 null-全部
          stock: '', // 库存状态 1-有库存 0-无库存 null-全部
          classifyId: '', // 最下级分类id
          page: 1, // 当前页
          pageSize: 10
        }
        this.getAll(this.formInline)
      },
      // 新增商品
      add() {
        this.showTinymce = true
        if (this.commId) {
          this.$refs.child.reset()
        }
        this.commidyVisible = true
        this.ontype = '2'
        this.commId = 0
        // this.$router.push({ name: 'addCommodity', params: { id: '1' }})
      },
      // 导出商品
      async productDataExport() {
        this.$message({
          message: '数据导出中，请勿重复操作！',
          type: 'success'
        })
        const res = await productExport(this.formInline)
        if (!res) {
          return
        }
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel'
        })
        const fileName = '商品数据明细表.xls'
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.href = URL.createObjectURL(blob)
          elink.style.display = 'none'
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      },
      // 编辑商品
      edit(row) {
        console.log(row)
        this.showTinymce = true
        this.commidyVisible = true
        this.ontype = '2'
        this.commId = row.productId
        this.$nextTick(() => {
          this.$refs.child?.details()
        })
      },

      // 删除商品
      del(row) {
        this.$confirm('选中数据将被永久删除, 是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            getClassifyDelete({
              productId: row.productId
            }).then(res => {
              if (res.code === '') {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.getAll(this.formInline)
              }
            })
          })
          .catch(() => {})
      },
      // 商品上下架
      async down(row) {
        console.log(row.shelveState)
        if (row.shelveState) {
          console.log(111)
          const res = await getClassifyStart({
            productId: row.productId,
            shelveState: 0
          })
          if (res.code === '') {
            this.$message({
              type: 'success',
              message: '下架成功!'
            })
            this.getAll(this.formInline)
          }
        } else {
          const res = await getClassifyStart({
            productId: row.productId,
            shelveState: 1
          })
          if (res.code === '') {
            this.$message({
              type: 'success',
              message: '上架成功!'
            })
            this.getAll(this.formInline)
          }
        }
      },
      // 初始化查询所有数据
      async getAll(formInline) {
        this.formInline.classifyId =
          this.formInline.classifyId[2] ||
          this.formInline.classifyId[1] ||
          this.formInline.classifyId[0] ||
          this.formInline.classifyId
        const res = await getClassifyGetAll(formInline)
        this.total = res.data.total
        this.tableData = res.data.list
        console.log(this.tableData)
      },
      // 初始化查询所有分类
      async queryAllCategory() {
        const res = await getClassify()
        this.categoryList = res.data
        this.handleRemoveEmptyChild(this.categoryList)
      },
      handleRemoveEmptyChild(arr) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].childs && Array.isArray(arr[i].childs)) {
            this.handleRemoveEmptyChild(arr[i].childs)
          }
          if (arr[i].childs && Array.isArray(arr[i].childs) && arr[i].childs.length === 0) {
            delete arr[i].childs
          }
        }
      },
      handleSelectionChange(val) {
        // console.log(val)
        if (this.index == 1) {
          if (val.length > 1) {
            // 清除之前的选择
            this.$refs.multipleTable.clearSelection();
            // 保留最后一个选中的项目
            if (val.length > 0) {
              this.$refs.multipleTable.toggleRowSelection(val[val.length - 1], true);

            }
          }
          this.dengji = val
        } else {
          let zuheId = ''
          for (let i = 0; i < val.length; i++) {
            zuheId += val[i].productId + ','
          }
          this.canst = zuheId
          this.zuheNum = val.length
        }
      },
      //清除选项
      toggleSelection() {
        this.$refs.multipleTable.clearSelection();
		this.zuheNum = 0
      },
      selClose() {
        this.teble_sel = false
      },
      //商品组合
      shopzuhe() {
        this.index = 2
        this.teble_sel = true
      },
      //确定组合
      zuheShop(val) {
		  console.log(this.canst.slice(0, -1))
        if (this.index == 1) {
          this.edit(this.dengji[0])
        } else {
          this.parentMessage = this.canst.slice(0, -1)
          this.add()
        }
      },
      //拆分
      chaiFen(row) {
        let _ = this
        this.$confirm('是否拆分组合的商品', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            const formData = new FormData();
            formData.append('id', row.productId);
            chFen(formData).then(res => {
              this.getAll(this.formInline)
            })

          })
          .catch(() => {})

      },
      //入库登记
      rukdengji() {
        this.shopId = null;
        this.num = 0
        this.rukuShow = true

      },
      // 设置会员价
      setVipPrice(row) {
        var _ = this
        this.productId = row.productId
        getProductMembers({
          productId: row.productId
        }).then(res => {
          if (res.code === '') {
            _.productData = res.data
            if (_.productData && _.productData.length > 0) {
              _.gradeList = []
              const _memberPrices = _.productData[0].memberPrices
              _memberPrices.forEach(function(item, i) {
                _.gradeList.push(item.memberLevelName)
              })
              _.mode = _.productData[0].mode ? _.productData[0].mode : 1
              _.vipPriceVisible = true
            }
          }
        })
      },
      // 设置会员价提交
      vipPriceSubmit() {
        for (let i = 0; i < this.productData.length; i++) {
          this.productData[i].mode = this.mode
          for (let j = 0; j < this.productData[i].memberPrices.length; j++) {
            this.productData[i].memberPrices[j].mode = this.mode
            var _price = this.productData[i].memberPrices[j].price
            if (!_price) {
              this.$message({
                type: 'warning',
                message: '会员价格不能为空！'
              })
              return false
            } else if (this.productData[i].mode === 1) {
              if (_price <= 0 || _price >= 10) {
                this.$message({
                  type: 'warning',
                  message: '会员折数必须大于0小于10！'
                })
                return false
              }
            } else if (this.productData[i].mode === 2) {
              if (_price > this.productData[i].price) {
                this.$message({
                  type: 'warning',
                  message: '会员价格不能大于原价！'
                })
                return false
              }
            }
          }
        }
        setProductMember({
          productId: this.productId,
          members: this.productData
        }).then(res => {
          if (res.code === '') {
            this.$message({
              type: 'success',
              message: '设置成功!'
            })
            this.getAll(this.formInline)
            this.vipPriceVisible = false
          }
        })
      },
      // 清空会员价
      clearProductMember() {
        console.log(this.productData, 'this.productData')
        this.$confirm('该商品所有旧设置的会员价将被清除, 是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          clearProductMember({
            productId: this.productId
          }).then(res => {
            if (res.code === '') {
              this.productData.map(item => {
                item.memberPrices.map(itemChild => {
                  itemChild.price = null
                })
              })
              this.$message.success('清除成功')
              // this.vipPriceVisible = false
            }
          })
        })
      },
      async rukuCheck() {
        const res = await getClassifyGetById({ productId: this.shopId })
        const form = res.data
        const params = {}
        if (res.data.names.length !== 0) {
          params.skuAttrList = res.data.names
        }
        params.skuList = form.skus
        params.attrStyle = res.data.skus[0].style
        params.imgs = res.data.images

        form.names = params.skuAttrList
        params.skuList.forEach(element => {
          element.style = params.attrStyle
        })
        form.skus = params.skuList
        form.images = params.imgs
        form.deletes = params.deletes
        form.classifyId = Array.isArray(form.classifyId) ? form.classifyId[form.classifyId.length - 1] : form.classifyId
        form.productId = this.shopId  
        console.log(form, 'form')
        if(form.skus.length>0) {
          form.skus[0].stockNumber =Number(form.skus[0].stockNumber)+ this.num
        }
        await getClassifyUpdate(form)
        this.$message.success('保存成功')
        this.rukuShow = false
        this.getAll(this.formInline)
        return

        const targetProduct = this.tableData.find(item => item.productId === this.shopId)
        // targetProduct.registrationStatus = this.dengjiMsg
       
        
        await getClassifyUpdate(targetProduct)
        this.$message.success('保存成功')
        this.rukuShow = false
        this.getAll(this.formInline)
      }
    }
  }
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
  @import url("../../../styles/elDialog.scss");

  .pending {
    padding: 0 20px 20px 20px;
    background-color: #fff;

  }

  .fenye {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    position: relative;
  }

  ::v-deep .el-pagination__total {
    position: absolute;
    left: 10px;
  }

  .formSearch {
    display: flex;
    width: 100%;
    font-size: 14px;
    justify-content: space-between;
  }

  .clickMe {
    color: #3F9B6A;
    cursor: pointer;
  }

  .uploadDialog {

    // display: flex;
    // flex-direction: column;
    // justify-content: center;
    >>>.el-upload__tip {
      display: inline-block;
      width: 360px;
      margin: auto;
    }
  }

  .vipDialog {
    .priceTable {
      table {
        width: 100%;
        text-align: center;
        border-left: 1px solid #EBEEF5;
        border-bottom: 1px solid #EBEEF5;
        font-size: 14px;
        color: #606266;
        border-collapse: collapse;

        tr {
          border-top: 1px solid #EBEEF5;

          th {
            padding: 12px 0;
            background: #F2F3F5;
            color: #0009;
            border-right: 1px solid #F2F3F5;
          }

          td {
            padding: 12px 0;
            border-right: 1px solid #EBEEF5;

            &.td-input {
              .el-input {
                width: 80px;
                margin-right: 0;
              }
            }

            &:nth-child(1),
            &:nth-child(2) {
              width: 80px;
            }

            .el-input {
              width: 100px;
              margin-right: 10px;
            }
          }
        }
      }
    }

    .clearBtn {
      margin-top: 20px;
    }
  }

  ::v-deep .bian_css {
    margin: auto;
    max-height: 840px;
    overflow-y: auto;

    .el-dialog__body {
      padding: 0px;
      background-color: #fff;
    }

    .el-dialog__header {
      background-color: #fff;
      padding: 10px 20px 10px 20px;
      border-bottom: 1px solid #EFEFEF;
    }

    .el-dialog__title {
      font-size: 14px;
      color: #000000e6;
    }

    .el-date-table td.available:hover {
      background-color: #3F9B6A;
    }

    .el-date-table td.start-date span {
      background-color: #3F9B6A;
    }
  }
</style>
