<template>
  <div class="add-dialog-component">
    <el-tree
      class="tree-box" :data="dataGroup" :props="{ children: 'childs' }" node-key="id"
      default-expand-all draggable
      :expand-on-click-node="false"
    >
      <div slot-scope="{ node, data }" class="custom-tree-node">
        <div class="content">
          <template v-if="data.depth < 3">
            <el-input
              v-model="data.groupName" class="input nameInput" maxlength="10"
              size="mini"
              :placeholder="getDepth(data.depth, true)"
            />
            <el-input
              v-model="data.groupDescribe" class="input"
              size="mini"
              placeholder="请输入分组描述"
            />
          </template>
          <template v-else>
            <div class="content" :class="isCheck ? 'disabled' : ''">
              <el-input
                v-model="data.groupName" class="input nameInput" size="mini"
                maxlength="10"
                placeholder="输入三级分组名称（最大10个字符）"
              />
              <el-input
                v-model="data.groupDescribe" class="input"
                size="mini"
                placeholder="请输入分组描述"
              />
            </div>
          </template>
        </div>
        <div v-if="!isCheck" class="setting-box">
          <el-button type="text" size="mini">
            分组商品详情
          </el-button>
          <el-button type="text" size="mini" @click="manualAdd(node, data)">
            添加分组分组商品
          </el-button>
          <el-button type="text" size="mini" @click="append(data)">
            {{ getDepth(data.depth) }}
          </el-button>
          <el-button type="text" size="mini" @click="remove(node, data)">
            删除
          </el-button>
        </div>
      </div>
    </el-tree>
    <div class="add-btn-wrap">
      <template v-if="isCheck">
        <el-button class="add" type="primary" size="small">
          确定
        </el-button>
      </template>
      <template v-else>
        <!-- <el-button v-if="type === 'add'" class="add" type="primary" size="small" @click="addClassification">
          添加一级分组名称
          </el-button> -->
        <el-button type="primary" size="small" @click="addGroup('ruleForm')">
          保存
        </el-button>
        <el-button type="danger" size="small" @click="closeAddGroup">
          取消
        </el-button>
      </template>
    </div>
    <!-- 手动添加弹框 -->
    <el-dialog
      title="手动添加商品" :visible.sync="isShowManualAdd" width="65%" top="50px"
      class="group-dialog"
      :close-on-click-modal="false" :modal-append-to-body="false" :modal="false"
    >
      <!-- 搜索 -->
      <div class="formSearch">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="商品名称">
            <el-input v-model="formInline.search" maxlength="20" placeholder="搜索商品名称或商品ID" />
          </el-form-item>
          <el-form-item class="tagCustomer" label="库存数量">
            <el-input v-model="formInline.minStock" maxlength="9" /><span>至</span><el-input
              v-model="formInline.maxStock"
              maxlength="9"
            />
          </el-form-item>
          <el-form-item class="tagCustomer" label="价格">
            <el-input v-model="formInline.minPrice" maxlength="9" /><span>至</span><el-input
              v-model="formInline.maxPrice"
              maxlength="9"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="search">查询</el-button>
            <el-button plain @click="clearData">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="tableBox">
        <el-table
          ref="multipleTable" :data="shopListData" border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }" tooltip-effect="dark" style="width: 100%"
          max-height="550" @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="产品主图" width="220" align="center">
            <template slot-scope="scope">
              <img height="80" width="80" :src="scope.row.image" alt srcset>
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="产品名称" width="220" align="center" />
          <el-table-column prop="originalPrice" label="价格（元）" align="center" show-overflow-tooltip />
          <el-table-column prop="stockNumber" label="库存（件）" align="center" show-overflow-tooltip />
        </el-table>
        <div class="fenye">
          <el-pagination
            :current-page="formInline.page" :page-sizes="[10, 20, 50, 100]" :page-size="formInline.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="shopTotal" @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="saveIdList">确 定</el-button>
            <el-button @click="closeSelect">取 消</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
let idx = 1000
function GroupData(data) {
  this.condition = null // 满足条件 1-全部满足 2-任意满足
  this.depth = data.depth
  this.idx = idx++
  this.conditions = [ // 筛选条件数组
    // {
    //   calculation: 1, // 运算符 1-大于 2-等于 3-小于
    //   ids: [], // 已满足部分条件的商品id数组
    //   number: null, // 数值
    //   type: 1 // 类型 1-库存 2-价格 3-重量 4-销量
    // }
  ]
  this.childs = [] // 子集分组
  this.groupDescribe = '' // 分组描述
  this.groupImage = '' // 分组封面图片地址
  this.groupName = '' // 分组名称
  this.ids = [] // 商品id数组
  this.shopGroupId = null // 商品分组id
}
import { commodityListAdd, commodityListUpdate, getGroupList, commodityListGetById } from '@/api/commodity'
export default {
  // eslint-disable-next-line vue/component-definition-name-casing, vue/match-component-file-name
  name: 'commodityGroup',
  props: {
    type: {
      type: String,
      default: 'create'
    },
    groupId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      // isVisible: false,
      // title: ['新增分组', '编辑分组'],
      dataGroup: [ new GroupData({ depth: 1 }) ],
      isCheck: false,
      deleteArr: [],
      selectGroup: 1,
      isShowManualAdd: false, // 手动添加商品模态框
      formInline: {
        maxPrice: null, // 价格最大值
        maxStock: null, // 库存数量最大值
        minPrice: null, // 价格最小值
        minStock: null, // 库存数量最小值
        page: 1, // 当前页
        pageSize: 10, // 每页记录数
        search: '' // 搜索字段
      },
      multipleSelection: [],
      products: [], // 已确认商品
      shopTotal: 1,
      shopListData: [],
      idsData: null
    }
  },
  watch: {
    groupId: {
      handler(nVal, oVal) {
        // console.log(nVal, oVal)
        if (!nVal) {
          this.$set(this.dataGroup, '0', new GroupData({ depth: 1 }))
          // this.dataGroup[0] = new GroupData({ depth: 1 })
          this.products = []
          this.multipleSelection = []
        } else {
          this.dataGroup[0].shopGroupId = nVal
          this.getDetailFn()
        }
      }
    }
  },
  mounted() {
    // if (this.$route.query.shopGroupId) {
    //   this.groupData.shopGroupId = this.$route.query.shopGroupId
    //   this.getDetailFn()
    // }
    if (this.groupId) {
      this.dataGroup[0].shopGroupId = this.groupId
      this.getDetailFn()
    }
    this.getAll(this.formInline)
  },
  methods: {
    // 初始化查询所有数据
    async getAll(formInline) {
      const res = await getGroupList(formInline)
      this.shopTotal = res.data.total
      this.shopListData = res.data.list
    },
    getDetailFn() {
      commodityListGetById({ shopGroupId: this.dataGroup[0].shopGroupId }).then((res) => {
        if (res.code === '') {
          // this.dataGroup[0].groupDescribe = res.data.groupDescribe
          // this.dataGroup[0].groupName = res.data.groupName
          this.multipleSelection = res.data.products
          this.products = res.data.products
          const shopList = []
          this.products.forEach((i) => {
            shopList.push(i.productId)
          })
          // this.dataGroup[0].ids = shopList
          // this.dataGroup[0].shopGroupId = res.data.shopGroupId
          this.$set(this.dataGroup, '0', res.data)
          console.log(this.dataGroup)
        } else {
          this.$message({
            message: res.message,
            type: 'error'
          })
        }
      })
    },
    getDepth(depth, isPlaceholder = false) {
      // depth = depth + ''
      const tipsMp = {
        1: '添加二级分组名称',
        2: '添加三级分组名称'
      }
      const tipsPlaceholder = {
        1: '输入一级分组名称（最大6个字符）',
        2: '输入二级分组名称（最大6个字符）'
      }
      if (isPlaceholder) {
        return tipsPlaceholder[depth]
      }
      return tipsMp[depth]
    },
    addClassification() {
      this.dataGroup.push(new GroupData({ depth: 1 }))
      // console.log(this.dataGroup)
    },
    append(data) {
      console.log(data)
      const depth = data.depth + 1
      let newChild
      if (!data.childs) {
        this.$set(data, 'childs', [])
      }
      if (depth < 3) {
        newChild = new GroupData({ depth })
      } else {
        newChild = new GroupData({ depth: 3 })
      }
      data.childs.push(newChild)
      console.log(this.dataGroup)
    },
    remove(node, data) {
      // console.log(node, data)
      const parent = node.parent
      const children = parent.data.childs || parent.data
      const index = children.findIndex((d) => d.idx === data.idx)
      if (index !== -1) {
        children.splice(index, 1)
        this.deleteArr.push(data.id || '')
      } else {
        this.$message.warning('数据错误，请重试')
      }
    },
    manualAdd(node, data) {
      // console.log(node)
      // console.log(data)
      this.idsData = data
      this.selectGroup = '1'
      // this.groupData.conditions = []
      // this.groupData.condition = null
      this.isShowManualAdd = true
    },
    // 手动查询商品
    search() {
      this.getAll(this.formInline)
    },
    clearData() {
      this.formInline = {
        maxPrice: null, // 价格最大值
        maxStock: null, // 库存数量最大值
        minPrice: null, // 价格最小值
        minStock: null, // 库存数量最小值
        page: 1, // 当前页
        pageSize: 10, // 每页记录数
        search: '' // 搜索字段
      }
      this.getAll(this.formInline)
    },
    // 商品表格多选
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.dataGroup[0].ids = []
    },
    // 分页大小
    handleSizeChange(val) {
      this.formInline.pageSize = val
      this.getAll(this.formInline)
    },
    // 分页
    handleCurrentChange(val) {
      this.formInline.page = val
      this.getAll(this.formInline)
    },
    // 保存手动选择商品
    saveIdList() {
      if (this.multipleSelection.length === 0) {
        this.idsData.ids = []
      }
      const shopList = []
      this.products = this.multipleSelection
      this.multipleSelection.forEach((i) => {
        shopList.push(i.productId)
      })
      this.idsData.ids = shopList
      this.isShowManualAdd = false
      console.log(this.dataGroup)
    },
    // 取消手动选择商品
    closeSelect() {
      this.isShowManualAdd = false
    },
    // 保存提交
    addGroup() {
      var self = this
      if (self.dataGroup[0].groupName === '') {
        self.$message({
          message: '分组名称不能为空',
          type: 'warning'
        })
        return false
      }
      // if (self.selectGroup === '1') {
      //   if (self.groupData.ids.length === 0) {
      //     self.$message({
      //       message: '请选择手动添加分组商品',
      //       type: 'warning'
      //     })
      //     return false
      //   }
      // }
      // if (self.selectGroup === '2') {
      //   if (self.groupData.conditions.length === 0) {
      //     self.$message({
      //       message: '请添加智能筛选条件',
      //       type: 'warning'
      //     })
      //   }
      // }
      if (self.selectGroup === '1') {
        self.dataGroup[0].conditions = []
        self.dataGroup[0].condition = null
      } else {
        self.dataGroup[0].ids = []
        self.products = []
        self.multipleSelection = []
      }
      if (self.dataGroup[0].shopGroupId !== '' && self.dataGroup[0].shopGroupId !== null) {
        // 修改人群
        commodityListUpdate(self.dataGroup[0]).then((res) => {
          if (res.code === '') {
            this.closeAddGroup()
            self.$message({
              message: '修改成功',
              type: 'success'
            })
            self.$emit('reload')
          } else {
            self.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      } else {
        // 新增人群
        commodityListAdd(self.dataGroup[0]).then((res) => {
          if (res.code === '') {
            this.closeAddGroup()
            self.$message({
              message: '添加成功',
              type: 'success'
            })
            self.$emit('reload')
          } else {
            self.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      }
    },
    // 取消提交
    closeAddGroup() {
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="scss">
.add-dialog-component {
	.tree-box {
		.el-tree-node__content {
			margin-bottom: 15px;
			height: auto;
		}
	}
}
</style>

<style lang="scss" scoped>
@import url("../../../styles/elDialog.scss");

.group-dialog {
	.el-dialog {
		min-width: 500px;
		max-width: 600px;
	}
}

.add-dialog-component {
	padding: 15px 20px;
	max-height: 60vh;
	overflow: auto;

	.el-tree-node__content {
		&:hover {
			background-color: #fff;
		}
	}

	.tree-box {
		margin: 15px 0;

		.custom-tree-node {
			display: flex;
			width: 100%;
			text-align: left;

			.content {
				flex: 1;
				display: flex;
				align-items: center;

				.input {
					width: 60%;
					margin-right: 20px;
				}
        .nameInput {
          width: 30%;
        }

				.textarea-input {
					width: 100%;
					margin-left: 15px;

					textarea {
						height: 80px;
					}
				}
			}

			.level-3-wrap {
				display: flex;
				width: 300px;

				.upload-wrap {
					position: relative;

					&.disabled::after {
						content: "";
						position: absolute;
						left: 0;
						right: 0;
						top: 0;
						bottom: 0;
						z-index: 999;
						background-color: #f5f7fa;
						opacity: 0.5;
					}

					.el-upload {
						border: 1px dashed #d9d9d9;
					}

					i {}

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

	.add-btn-wrap {
		text-align: center;
	}
}

.upload-uploader {
	margin-left: 30px;
}
</style>

<style scoped>
.newGroupBox /deep/ .formBox {
	width: 500px;
}

/*.group-dialog /deep/ .el-dialog__headerbtn .el-dialog__close {*/
/*  color: #FFFFFF;*/
/*}*/
.fenye {
	margin-top: 30px;
}

.fenye /deep/ .dialog-footer {
	margin: 30px auto 0 auto;
	display: flex;
	justify-content: center;
}

.znAddBox /deep/ .conditionBox {
	display: flex;
	align-items: center;
}

.znAddBox /deep/ .conditionBox .anAddTit {
	margin-right: 20px;
}

.tagCustomer /deep/ .el-form-item__content {
	display: flex;
	width: 260px;
}

.tagCustomer {
	display: flex !important;
}

.tagCustomer /deep/ .el-form-item__content span {
	margin: 0 5px;
}

.formSearch /deep/ .el-form {
	display: flex;
	flex-wrap: wrap;
}

.btnBox /deep/ .el-radio {
	margin-right: 8px;
}

.btnBox /deep/ .el-radio__label {
	display: none;
}
</style>
