<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规格名称">
        <el-input v-model="queryParams.name" placeholder="请输入规格名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.state" placeholder="请选择" clearable @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" v-hasPermi="['system:spec:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <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="['system:spec:add']">新增</el-button>
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <el-table v-loading="loading" :data="specsList">
      <el-table-column label="规格名称" width="300" align="center" prop="name">
        <template slot-scope="scope">
          <a @click="handleUpdate(scope.row)" style="color: blue">{{ scope.row.name }}</a>
        </template>
      </el-table-column>
      <el-table-column label="规格编码" width="180" align="center" prop="code" />
      <el-table-column label="选项" align="center" prop="specRules">
        <template slot-scope="scope">
          <el-tag style="margin-right:10px;" v-for="item in scope.row.specRules" :key="item.id">
            {{ item.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="180" align="center" prop="state">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1">启用</span>
          <span v-else>停用</span>
        </template>
      </el-table-column>
      <el-table-column label="原料备注" width="180" align="center" prop="materialRemark"/>
      <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
           <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:spec:remove']">删除</el-button>
          <el-button v-show="scope.row.state == 2" size="mini" type="text" icon="el-icon-edit" @click="handleStatus(scope.row,'1')"
              v-hasPermi="['system:spec:restart']">启用</el-button>
          <el-button v-show="scope.row.state == 1" size="mini" type="text" icon="el-icon-edit" @click="handleStatus(scope.row,'2')"
            v-hasPermi="['system:spec:stop']">停用</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="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规格名称" maxlength="100"/>
        </el-form-item>
        <el-form-item label="必须原料">
          <el-switch v-model="form.isNeccessary" :active-value="2" :inactive-value="1">
          </el-switch>
        </el-form-item>
        <el-form-item label="选项" prop="specRules">
          <SpecsSelect :initData="form.specRules" ref="specsSelect" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="500" show-word-limit/>
        </el-form-item>
        <el-form-item label="原料备注" prop="materialRemark">
          <el-input v-model="form.materialRemark" type="textarea" placeholder="请输入内容" maxlength="500" show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-hasPermi="['system:spec:edit']">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSpecs,
  getSpecs,
  delSpecs,
  addSpecs,
  updateSpecs,
} from "@/api/system/spec";
import SpecsSelect from "./SpecsSelect.vue";
export default {
  name: "Specs",
  components: { SpecsSelect },
  data() {
    var validateSpecRules = (rule, value, callback) => {
      if (value.length==0) {        
        callback(new Error('请添加选项'));
      }else if(value.length<1){
        callback(new Error('请最少添加1个选项'));
      }else {
        callback();
      }
    }; 
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规格表格数据
      specsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        state: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "规格名称不能为空", trigger: "blur" },
        ],
        specRules:[{ required: true, validator: validateSpecRules, trigger: 'blur' }],
      },
      options: [{
          value: null,
          label: '全部'
        }, {
          value: '1',
          label: '启用'
        }, {
          value: '2',
          label: '停用'
        }],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询规格列表 */
    getList() {
      this.loading = true;
      listSpecs(this.queryParams).then((response) => {
        this.specsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        specCode: null,
        createDate: null,
        specRules: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加规格";
    },
     /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSpecs(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改规格";
      });
    },
    /** 启用、禁用按钮操作 */
    handleStatus(row,tag) {
      let mess="";
      let sta="";
      if(tag=='1'){
        mess="启用";
        sta="1";
      }else if(tag=='2'){
        mess="停用";
        sta="2";
      } 
      this.$modal
        .confirm('是否确认' + mess + '该数据项?')
        .then(function () {
          return updateSpecs({id:row.id,state:sta});
        })
        .then((response) => {
          if(response.code="200"){
            this.getList();
            this.$modal.msgSuccess('' + mess + '成功');
          }          
        })
        .catch(() => { });
    },
    /** 提交按钮 */
    submitForm() {
      let regular=/(^[+]{0,1}([0-9]+)$)|(^[+]{0,1}([0-9]+)[\.]{1}[0-9]{1}$)/; //正数 ,小数可有可无,最多2位
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let specsSelectList = this.$refs.specsSelect.list;
          for(let i=0;i<specsSelectList.length;i++){
            let index=i+1;
            if(specsSelectList[i].name==""){
              this.$modal.msgSuccess('选项列表中的第' + index + '行名称不能为空');
              return;
            }  
            if(!regular.test(specsSelectList[i].amount)){
              this.$modal.msgSuccess('选项列表中的第' + index + '行价格不是大于等于0的数字,最多保留1位小数');
              return;
            }
            if(!specsSelectList[i].isRecommend){
              specsSelectList[i].isRecommend = "0";
            }
            if(!specsSelectList[i].isDefault){
              specsSelectList[i].isDefault = "0";
            }
          }
          this.form.specRules = specsSelectList;
          if (this.form.id != null) {
            if(this.form.state == 1){
              this.$message.error("停用之后才可以修改");
              return;
            }
            updateSpecs(this.form).then((response) => {
              if(response.code=="200"){
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addSpecs(this.form).then((response) => {
              if(response.code=="200"){
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }              
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if(row.state==1){
        this.$message.error("停用状态才能删除!");
        return;
      }
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除规格编码为' + row.code + '的数据项?')
        .then(function () {
          return delSpecs(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/spec/export",
        {
          ...this.queryParams,
        },
        `specs_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>