<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['store:storeProductRule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:storeProductRule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:storeProductRule:remove']"
        >删除</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table  height="500" border v-loading="loading" :data="storeProductRuleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="规格名称" align="center" prop="ruleName" />
      <el-table-column  prop="ruleValue" label="规格值" >
        <template slot-scope="scope">
          <div v-for="(item, index) in JSON.parse(scope.row.ruleValue)">
            {{ item.value }} : {{ item.detail.join(',')}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:storeProductRule:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:storeProductRule: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-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="规格名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规格名称" />
        </el-form-item>
        <el-col :span="23" class="noForm" v-for="(item, index) in form.ruleValue" :key="index">
          <el-form-item label=" ">
            <div class="acea-row row-middle"><span class="mr5">{{item.value}}</span>
              <i class="el-icon-circle-close"  @click="handleRemove(index)"></i>
            </div>
            <div class="rulesBox">
              <el-tag   class="mb5" style="margin: 2px 4px 2px 0;" closable
              v-for="(j, subIndex) in item.detail" :key="subIndex"
              :name="j" @close="handleRemove2(item.detail,subIndex)">{{j}}
              </el-tag>
              <el-input placeholder="请输入属性名"  v-model="item.detail.attrsVal"
                        style="width: 200px">
                <el-button slot="append" type="primary"  @click="createAttr(item.detail.attrsVal,index)">添加</el-button>
              </el-input>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="isAdd">
          <el-col :span="8" class="mr15">
            <el-form-item label="规格：">
              <el-input placeholder="请输入规格" v-model="attrsName"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="mr20">
            <el-form-item label="规格值：">
              <el-input v-model="attrsVal" placeholder="请输入规格值"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button  type="primary" @click="createAttrName">确定</el-button>
             <el-button @click="cancelAttr">取消</el-button>
          </el-col>
          
        </el-col>
         <el-button type="primary" icon="md-add"  size="small" @click="addBtn" v-if="!isAdd" class="ml95 mt10">添加新规格</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStoreProductRule, getStoreProductRule, delStoreProductRule, addStoreProductRule, updateStoreProductRule, exportStoreProductRule } from "@/api/store/storeProductRule";

export default {
  name: "StoreProductRule",
  data() {
    return {
      attrsName: '',
      attrsVal: '',
      isAdd:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品规则值(规格)表格数据
      storeProductRuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        ruleValue: null,
        isDel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ruleName: [
          { required: true, message: "规格名称不能为空", trigger: "blur" }
        ],
        ruleValue: [
          { required: true, message: "规格值不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
      cancelAttr(){
        this.isAdd=false;
      },
      // 添加规则名称
      createAttrName () {
        if (this.attrsName && this.attrsVal) {
          let data = {
            value: this.attrsName,
            detail: [
              this.attrsVal
            ]
          };
          this.form.ruleValue.push(data);
          var hash = {};
          this.form.ruleValue = this.form.ruleValue.reduce(function (item, next) {
            /* eslint-disable */
            hash[next.value] ? '' : hash[next.value] = true && item.push(next);
            return item
          }, [])
          this.attrsName = '';
          this.attrsVal = '';
          this.isAdd = false;
        } else {
          return this.$message.warning('请添加规格名称！');
        }
      },
    // 添加属性
    createAttr (val, idx) {
      if (val) {
        this.form.ruleValue[idx].detail.push(val);
        var hash = {};
        this.form.ruleValue[idx].detail = this.form.ruleValue[idx].detail.reduce(function (item, next) {
          hash[next] ? '' : hash[next] = true && item.push(next);
          return item
        }, [])
      } else {
        return this.$message.warning('请添加属性！');
      }
    },
     // 删除
    handleRemove (index) {
      this.form.ruleValue.splice(index, 1);
    },
    // 删除属性
    handleRemove2 (item, index) {
      item.splice(index, 1);
    },
    // 添加按钮
    addBtn () {
      this.isAdd = true;
    },
    /** 查询商品规则值(规格)列表 */
    getList() {
      this.loading = true;
      listStoreProductRule(this.queryParams).then(response => {
        this.storeProductRuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ruleName: null,
        ruleValue: [],
        createTime: null,
        updateTime: null,
        isDel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加SKU规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStoreProductRule(id).then(response => {
        this.form = response.data;
        this.form.ruleValue=JSON.parse(this.form.ruleValue)
        this.open = true;
        this.title = "修改SKU规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStoreProductRule(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addStoreProductRule(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品规则值(规格)编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStoreProductRule(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品规则值(规格)数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStoreProductRule(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
