<template>
  <el-dialog :visible.sync="visible" v-bind="modalOptions" append-to-body>
    <div class="tree-container">
      <el-tree
        :data="[ formData ]" :props="{ children: 'childs' }" node-key="shopGroupId" default-expand-all
        draggable
        :expand-on-click-node="false"
      >
        <div slot-scope="{ node, data }">
          <div style="display: flex;align-items: center;justify-content: space-between;padding: 10px 0;">
            <div v-if="data.depth <= 3" style="margin-right: 14px;">
              <el-input
                v-model="data.groupName" maxlength="10" size="mini" style="width: 280px;"
                :placeholder="{ 1: '输入一级分组名称（最大6个字符）', 2: '输入二级分组名称（最大6个字符）', 2: '输入三级分组名称（最大10个字符）' }[data.depth]"
              />
              <el-input v-model="data.groupDescribe" size="mini" style="width: 340px;" placeholder="请输入分组描述" />
            </div>
            <div>
              <el-button type="text" size="mini">
                分组商品详情
              </el-button>
              <el-button type="text" size="mini" @click="handleAddProduct(data, node)">
                添加分组商品
              </el-button>
              <el-button v-if="data.depth < 3" type="text" size="mini" @click="handleAppend(data)">
                {{ { 1: '添加二级分组名称', 2: '添加三级分组名称' }[data.depth] }}
              </el-button>
              <el-button type="text" size="mini" @click="handleDelete(data, node)">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </el-tree>
      <div>
        <el-button type="primary" size="small" @click="handleSubmit">
          保存
        </el-button>
        <el-button type="danger" size="small" @click="handleClose">
          取消
        </el-button>
      </div>

      <el-dialog title="手动添加商品" :visible.sync="isShowManualAdd" width="900px" top="50px" append-to-body>
        <div class="filter-container" style="display: flex;align-items: center;flex-wrap: wrap;">
          <el-input
            v-model="listQuery.search" clearable size="mini" class="filter-item"
            style="width: 200px;"
            placeholder="搜索商品名称或商品ID"
          />
          <div style="margin-left: 10px;">
            <span>库存数量：</span>
            <el-input
              v-model="listQuery.minStock" size="mini" class="filter-item" style="width: 200px;"
              maxlength="9"
            />
            <span> 至 </span>
            <el-input
              v-model="listQuery.maxStock" size="mini" class="filter-item" style="width: 200px;"
              maxlength="9"
            />
          </div>
          <div style="margin-left: 10px;">
            <span>价格：</span>
            <el-input
              v-model="listQuery.minPrice" size="mini" class="filter-item" style="width: 200px;"
              maxlength="9"
            />
            <span> 至 </span>
            <el-input
              v-model="listQuery.maxPrice" size="mini" class="filter-item" style="width: 200px;"
              maxlength="9"
            />
          </div>
          <el-button
            size="mini" class="filter-item" type="primary" icon="el-icon-search"
            style="margin-left: 10px;"
            @click="getInfo(formData.shopGroupId)"
          >
            查找
          </el-button>
          <el-button
            size="mini" class="filter-item" type="info" plain
            style="margin-left: 10px; padding: 7px 22px; border: 0" @click="clearData"
          >
            重置
          </el-button>
        </div>
        <div>
          <el-table
            ref="multipleTable" :data="productDataList" border
            :header-cell-style="{ background: '#EEF3FF', color: '#333333' }" tooltip-effect="dark" style="width: 100%"
            max-height="550" @selection-change="(e) => multipleSelection = e"
          >
            <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>
            <el-pagination
              :current-page="listQuery.page" :page-sizes="[10, 20, 50, 100]"
              :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="productTotal"
              @size-change="(val) => ((listQuery.pageSize = val) && getInfo(formData.shopGroupId))"
              @current-change="(val) => ((listQuery.page = val) && getInfo(formData.shopGroupId))"
            />
            <span slot="footer">
              <el-button type="primary" @click="handleSaveIdList">确 定</el-button>
              <el-button @click="isShowManualAdd = false">取 消</el-button>
            </span>
          </div>
        </div>
      </el-dialog>

    </div>
  </el-dialog>
</template>

<script>
import { commodityListAdd, commodityListUpdate, getGroupList, commodityListGetById, commodityListDelete } from '@/api/commodity'
import XeUtils from 'xe-utils'

export default {
  name: 'EditModal',
  props: {
    groupId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: '1120px',
        title: ''
      },
      visible: false,
      formData: {
        shopGroupId: '',
        shopId: '',
        groupName: '',
        groupImage: '',
        groupDescribe: '',
        groupLevel: '',
        depth: 1,
        groupPid: 0,
        childs: []
      },

      isShowManualAdd: false, // 手动添加商品模态框
      selectedGroupId: '',
      productDataList: [],
      productTotal: 0,
      listQuery: {
        maxPrice: null, // 价格最大值
        maxStock: null, // 库存数量最大值
        minPrice: null, // 价格最小值
        minStock: null, // 库存数量最小值
        page: 1, // 当前页
        pageSize: 10, // 每页记录数
        search: '' // 搜索字段
      },
      multipleSelection: []
    }
  },
  methods: {
    handleClose() {
      this.visible = false
    },
    async initList() {
      const res = await getGroupList(this.listQuery)
      this.productTotal = res.data.total
      this.productDataList = res.data.list
    },
    handleOpen(params = {}) {
      this.modalOptions.title = params.shopGroupId ? '编辑分组' : '添加分组'
      this.visible = true
      this.initList()
      if (params.shopGroupId) {
        this.getInfo(params.shopGroupId)
      } else {
        this.formData = {
          shopGroupId: '',
          shopId: '',
          groupName: '',
          groupImage: '',
          groupDescribe: '',
          groupLevel: '',
          depth: 1,
          groupPid: 0,
          products: [],
          childs: [],
          ids: [] // 自设
        }
      }
    },
    async getInfo(id) {
      const loading = this.$loading({ text: '加载中' })
      try {
        const res = await commodityListGetById({ shopGroupId: id })
        this.formData = Object.assign(this.$options.data().formData, res.data, {
          shopGroupId: res.data.shopGroupId || '',
          shopId: res.data.shopId || '',
          groupName: res.data.groupName || '',
          groupImage: res.data.groupImage || '',
          groupDescribe: res.data.groupDescribe || '',
          groupLevel: res.data.groupLevel || '',
          depth: res.data.depth || 1,
          groupPid: res.data.groupPid || 0,
          products: res.data.products || [],
          childs: res.data.childs || [],
          ids: res.data.ids || []
        })
        XeUtils.eachTree([ this.formData ], (item) => {
          item.ids = item.products.map((i) => i.productId)
        }, { children: 'childs' })
      } finally {
        loading.close()
      }
    },
    handleAppend(data) {
      if (data.depth < 3) {
        data.childs.push({
          shopGroupId: '',
          shopId: '',
          groupName: '',
          groupImage: '',
          groupDescribe: '',
          groupLevel: '',
          depth: data.depth + 1,
          groupPid: 0,
          childs: [],
          ids: []
        })
      }
    },
    handleDelete(data, node) {
      this.$confirm('选中数据将被永久删除, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await commodityListDelete({ shopGroupId: data.shopGroupId })
          this.$message({ message: '删除成功！', type: 'success' })
          this.getInfo(this.formData.shopGroupId)
          this.$emit('success')
        })
    },
    handleAddProduct(data, node) {
      this.multipleSelection = []
      this.selectedGroupId = data.shopGroupId
      this.isShowManualAdd = true
    },
    clearData() {
      this.listQuery = {
        maxPrice: null, // 价格最大值
        maxStock: null, // 库存数量最大值
        minPrice: null, // 价格最小值
        minStock: null, // 库存数量最小值
        page: 1, // 当前页
        pageSize: 10, // 每页记录数
        search: '' // 搜索字段
      }
      this.getInfo(this.formData.shopGroupId)
    },

    handleSaveIdList() {
      XeUtils.eachTree([ this.formData ], (item) => {
        if (item.shopGroupId === this.selectedGroupId) {
          if (this.multipleSelection.length) {
            item.ids = this.multipleSelection.map((i) => i.productId)
          } else {
            item.ids = []
          }
        }
      }, { children: 'childs' })
      this.isShowManualAdd = false
    },
    // 保存提交
    async handleSubmit() {
      let isGroupNameEmpty = false
      XeUtils.eachTree([ this.formData ], (item) => {
        if (!item.groupName) isGroupNameEmpty = true
      }, { children: 'childs' })
      if (isGroupNameEmpty) return this.$message({ message: '分组名称不能为空', type: 'warning' })
      this.formData.conditions = []
      this.formData.condition = null
      const loading = this.$loading({ text: '提交中，请稍候……' })
      try {
        const { ...otps } = this.formData
        const params = {
          ...otps
        }
        this.formData.shopGroupId ? await commodityListUpdate(params) : await commodityListAdd(params)
        loading.close()
        this.$message({ message: `${this.formData.shopGroupId ? '编辑' : '添加'}成功!`, type: 'success' })
        this.$emit('success')
        this.visible = false
      } catch (e) {
        loading.close()
      } finally {
        loading.close()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-container {
	::v-deep .el-tree-node__content {
		height: auto;
	}

	.filter-container {
		.filter-item {
			display: inline-block;
			vertical-align: middle;
			margin-bottom: 10px;
		}
	}
}
</style>
