<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="属性模版名称" prop="keyword">
          <el-input v-model="queryParams.keyword" placeholder="输入属性模版名称" clearable style="width: 220px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['agri:seller:attrTemplate:add']">添加属性模版</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['agri:seller:attrTemplate:remove']">批量删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="属性模版名称" align="center" prop="templateName" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column label="名称列表" align="left" prop="nameList" min-width="260" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.nameList || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="140" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['agri:seller:attrTemplate:edit']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['agri:seller:attrTemplate:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogOpen" width="720px" append-to-body @close="cancelForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" class="template-form">
        <el-form-item label="属性模版名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入属性模版名称" maxlength="64" />
        </el-form-item>

        <div class="section-title">属性</div>
        <div v-for="(item, index) in form.attributes" :key="'attr-' + index" class="item-block">
          <div class="item-head">
            <span class="item-label">属性名：</span>
            <el-input v-model="item.itemName" placeholder="请输入属性项名称" maxlength="64" class="item-name-input" />
            <el-button v-if="form.attributes.length > 1 || form.specs.length > 0" type="text" icon="el-icon-delete" class="item-remove" @click="removeAttributeItem(index)">删除</el-button>
          </div>
          <div class="value-row">
            <span class="item-label">属性值：</span>
            <div class="value-list">
              <div v-for="(val, vIndex) in item.values" :key="'attr-val-' + index + '-' + vIndex" class="value-item">
                <el-input v-model="item.values[vIndex]" placeholder="属性值" maxlength="128" size="small" />
                <el-button v-if="item.values.length > 1" type="text" icon="el-icon-close" @click="removeAttributeValue(index, vIndex)" />
              </div>
              <el-button type="text" icon="el-icon-plus" @click="addAttributeValue(index)">增加属性值</el-button>
            </div>
          </div>
        </div>
        <el-button plain icon="el-icon-plus" class="add-item-btn" @click="addAttributeItem">添加属性项</el-button>

        <div class="section-title">规格</div>
        <div v-for="(item, index) in form.specs" :key="'spec-' + index" class="item-block">
          <div class="item-head">
            <span class="item-label">规格名：</span>
            <el-input v-model="item.itemName" placeholder="请输入规格项名称" maxlength="64" class="item-name-input" />
            <el-button v-if="form.specs.length > 1 || form.attributes.length > 0" type="text" icon="el-icon-delete" class="item-remove" @click="removeSpecItem(index)">删除</el-button>
          </div>
          <div class="value-row">
            <span class="item-label">规格值：</span>
            <div class="value-list">
              <div v-for="(val, vIndex) in item.values" :key="'spec-val-' + index + '-' + vIndex" class="value-item">
                <el-input v-model="item.values[vIndex]" placeholder="规格值" maxlength="128" size="small" />
                <el-button v-if="item.values.length > 1" type="text" icon="el-icon-close" @click="removeSpecValue(index, vIndex)" />
              </div>
              <el-button type="text" icon="el-icon-plus" @click="addSpecValue(index)">增加规格值</el-button>
            </div>
          </div>
        </div>
        <el-button plain icon="el-icon-plus" class="add-item-btn" @click="addSpecItem">添加规格项</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAttrTemplate,
  getAttrTemplate,
  addAttrTemplate,
  updateAttrTemplate,
  delAttrTemplate
} from "@/api/agri/seller/attrTemplate"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"

export default {
  name: "AgriSellerAttrTemplate",
  data() {
    return {
      loading: true,
      ids: [],
      multiple: true,
      showSearch: true,
      total: 0,
      templateList: [],
      dialogOpen: false,
      dialogTitle: "",
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        keyword: undefined
      },
      form: {
        templateId: undefined,
        templateName: undefined,
        attributes: [],
        specs: []
      },
      rules: {
        templateName: [{ required: true, message: "请输入属性模版名称", trigger: "blur" }]
      }
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    /** 初始化页面 */
    initPage() {
      this.loadShopContext().then(() => {
        this.getList()
      }).catch(() => {
        this.getList()
      })
    },
    /** 写入 X-Shop-Id 缓存 */
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      listAttrTemplate(this.queryParams).then(response => {
        this.templateList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 创建空项 */
    createEmptyItem() {
      return {
        itemName: "",
        values: [""]
      }
    },
    /** 将详情项转为表单结构 */
    mapDetailItems(items) {
      const list = items || []
      if (!list.length) {
        return []
      }
      return list.map(item => ({
        itemName: item.itemName || "",
        values: (item.values && item.values.length) ? [...item.values] : [""]
      }))
    },
    resetFormData() {
      this.form = {
        templateId: undefined,
        templateName: undefined,
        attributes: [],
        specs: []
      }
      this.resetForm("form")
    },
    cancelForm() {
      this.dialogOpen = false
      this.resetFormData()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId)
      this.multiple = !selection.length
    },
    /** 添加属性项 */
    addAttributeItem() {
      this.form.attributes.push(this.createEmptyItem())
    },
    /** 删除属性项 */
    removeAttributeItem(index) {
      this.form.attributes.splice(index, 1)
    },
    /** 增加属性值 */
    addAttributeValue(index) {
      this.form.attributes[index].values.push("")
    },
    /** 删除属性值 */
    removeAttributeValue(itemIndex, valueIndex) {
      this.form.attributes[itemIndex].values.splice(valueIndex, 1)
    },
    /** 添加规格项 */
    addSpecItem() {
      this.form.specs.push(this.createEmptyItem())
    },
    /** 删除规格项 */
    removeSpecItem(index) {
      this.form.specs.splice(index, 1)
    },
    /** 增加规格值 */
    addSpecValue(index) {
      this.form.specs[index].values.push("")
    },
    /** 删除规格值 */
    removeSpecValue(itemIndex, valueIndex) {
      this.form.specs[itemIndex].values.splice(valueIndex, 1)
    },
    /** 打开添加弹窗 */
    handleAdd() {
      this.resetFormData()
      this.dialogOpen = true
      this.dialogTitle = "添加属性模版"
    },
    /** 打开编辑弹窗 */
    handleUpdate(row) {
      this.resetFormData()
      getAttrTemplate(row.templateId).then(response => {
        const data = response.data || {}
        this.form = {
          templateId: data.templateId,
          templateName: data.templateName,
          attributes: this.mapDetailItems(data.attributes),
          specs: this.mapDetailItems(data.specs)
        }
        this.dialogOpen = true
        this.dialogTitle = "编辑属性模版"
      })
    },
    /** 组装并校验提交体 */
    buildSubmitPayload() {
      const attributes = this.normalizeItems(this.form.attributes)
      const specs = this.normalizeItems(this.form.specs)
      if (!attributes.length && !specs.length) {
        this.$modal.msgWarning("请至少添加一个属性项或规格项")
        return null
      }
      const attrNames = attributes.map(item => item.itemName)
      const specNames = specs.map(item => item.itemName)
      if (new Set(attrNames).size !== attrNames.length || new Set(specNames).size !== specNames.length) {
        this.$modal.msgWarning("属性项/规格项名称不可重复")
        return null
      }
      const cross = [...attrNames, ...specNames]
      if (new Set(cross).size !== cross.length) {
        this.$modal.msgWarning("属性项与规格项名称不可相同")
        return null
      }
      for (let i = 0; i < attributes.length; i++) {
        if (!this.validateItemValues(attributes[i], "属性")) {
          return null
        }
      }
      for (let i = 0; i < specs.length; i++) {
        if (!this.validateItemValues(specs[i], "规格")) {
          return null
        }
      }
      return {
        templateId: this.form.templateId,
        templateName: (this.form.templateName || "").trim(),
        attributes: attributes,
        specs: specs
      }
    },
    /** 规范化项与值 */
    normalizeItems(items) {
      const result = []
      ;(items || []).forEach(item => {
        const name = (item.itemName || "").trim()
        if (!name) {
          return
        }
        const values = (item.values || [])
          .map(val => (val || "").trim())
          .filter(val => val)
        result.push({
          itemName: name,
          values: values
        })
      })
      return result
    },
    /** 校验单项至少一个非重复值 */
    validateItemValues(item, label) {
      if (!item.itemName) {
        this.$modal.msgWarning("请输入" + label + "项名称")
        return false
      }
      if (!item.values || !item.values.length) {
        this.$modal.msgWarning("请为每项至少添加一个" + label + "值")
        return false
      }
      if (new Set(item.values).size !== item.values.length) {
        this.$modal.msgWarning("同一项下" + label + "值不可重复")
        return false
      }
      return true
    },
    /** 提交保存 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        const payload = this.buildSubmitPayload()
        if (!payload) {
          return
        }
        const submitFn = payload.templateId != null ? updateAttrTemplate : addAttrTemplate
        submitFn(payload).then(() => {
          this.$modal.msgSuccess(payload.templateId != null ? "修改成功" : "添加成功")
          this.dialogOpen = false
          this.getList()
        })
      })
    },
    /** 删除（单条/批量） */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids
      const msg = row.templateId
        ? "确认删除属性模版「" + row.templateName + "」？"
        : "确认批量删除所选 " + this.ids.length + " 个属性模版？"
      this.$modal.confirm(msg).then(() => {
        return delAttrTemplate(templateIds)
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.getList()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 0;
}
.template-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 8px;
}
.section-title {
  margin: 16px 0 10px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}
.item-block {
  margin-bottom: 12px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}
.item-head,
.value-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
}
.item-head:last-child,
.value-row:last-child {
  margin-bottom: 0;
}
.item-label {
  flex-shrink: 0;
  width: 56px;
  line-height: 32px;
  color: #606266;
  font-size: 13px;
}
.item-name-input {
  flex: 1;
  max-width: 320px;
}
.item-remove {
  margin-left: 8px;
  color: #F56C6C;
}
.value-list {
  flex: 1;
}
.value-item {
  display: inline-flex;
  align-items: center;
  margin: 0 8px 8px 0;
  width: 140px;
}
.value-item .el-input {
  flex: 1;
}
.add-item-btn {
  width: 100%;
  margin-bottom: 8px;
}
</style>
