<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="商家名称" prop="merchantsName">
          <el-select  filterable style="width: 100%;" v-model="queryParams.merchantsId" placeholder="请选择商户名称">
                      <el-option
                        v-for="dict in merchantsNameList"
                        :key="dict.businessId"
                        :label="dict.businessName"
                        :value="dict.businessId"
                        @click.native="optionClicks(dict.businessName)"
                      ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权益等级" prop="interestsLevel ">
          <el-select :multiple="true"  style="width: 100%;" v-model="queryParams.interestsLevel " placeholder="请选择权益等级">
                      <el-option
                        v-for="dict in dict.type.credit_level"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权益次数" prop="interestsNumber">
          <el-input v-model="queryParams.interestsNumber" type="number" placeholder="请输入权益次数" />
        </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-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:table:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:table:edit']"
        >修改</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="['system:table:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:table:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="商户名称" align="center" prop="merchantsName" />
      <el-table-column label="权益等级" align="center" prop="interestsLevel" />
      <el-table-column label="权益次数" align="center" prop="interestsNumber" />
      <el-table-column label="权益描述" align="center" prop="account" />
      <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="['system:table:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:table: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-row>
          <el-col :span="24">
            <el-form-item label="类别名称" prop="interestsPolicyId">
              <treeselect v-model="form.interestsPolicyId" :options="deptOptions" :normalizer="normalizer"  placeholder="请选择上级类别" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商户名称" prop="merchantsId">
              <el-select  filterable style="width: 100%;" v-model="form.merchantsId" placeholder="请选择商户名称">
                          <el-option
                            v-for="dict in merchantsNameList"
                            :key="dict.businessId"
                            :label="dict.businessName"
                            :value="dict.businessId"
                            @click.native="optionClick(dict.businessName)"
                          ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-for="(item, index) in form.interestsNumberTableList">
            <el-col :span="11">
              <el-form-item label="权益等级" prop="rightsRank">
                <el-select  style="width: 100%;" v-model="item.rightsRank" placeholder="请选择权益等级">
                            <el-option
                              v-for="dict in dict.type.credit_level"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
            <el-form-item label="权益次数" prop="number">
              <el-input v-model="item.number" type="number" placeholder="请输入权益次数" />
            </el-form-item>
            </el-col>
            <el-col :span="2">
              <div class="hyeoa" style="margin-top: 10px;">
              	 <el-tooltip class="item" effect="dark" content="新增信息,请慎重操作" placement="top-start">
              	      <img src="../../../assets/images/icon_tc_add.png" alt="" class="hueyde" @click="tijea(index)" />
              	    </el-tooltip>
              		<el-tooltip class="item" effect="dark" content="删除无法恢复,请慎重操作" placement="top-start">
              		     <img src="../../../assets/images/delei.png" alt="" class="hueydele" @click="naeyrfakjf(index, item)" />
              		   </el-tooltip>
              </div>
            </el-col>
          </el-col>

          <el-col :span="24">
            <el-form-item label="权益描述" prop="account">
              <editor v-model="form.account" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>

      </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 { listTable, mersList, getTable, delTable, addTable, updateTable, delseeu } from "@/api/system/table";
import { listMenu } from "@/api/settlement/menutwo";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  dicts: ['credit_level', 'sys_user_sex'],
  components: { Treeselect },
  name: "Table",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商户权益记录表格数据
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        merchantsName: null,
        account: null,
        isDel: null
      },
      // 表单参数
      form: {
        interestsNumberTableList:[{rightsRank:'',number:""}]
      },
      // 表单校验
      rules: {
        merchantsId: [
          { required: true, message: "商户id不能为空", trigger: "blur" }
        ],
        merchantsName: [
          { required: true, message: "商户名称不能为空", trigger: "change" }
        ],
        parentId: [
          { required: true, message: "类别名称不能为空", trigger: "change" }
        ]

      },
      merchantsNameList:[],
      nske:null
    };
  },
  created() {
    listMenu().then(response => {
      // this.menuList = response.rows;
      this.deptOptions = this.handleTree(response.data, "menuId")
      console.log(this.deptOptions)
      // this.total = response.total;
    });
    this.getList();
    this.mersNameList()
  },
  methods: {
    /** 查询商户权益记录列表 */
    getList() {
      this.loading = true;
      listTable(this.queryParams).then(response => {
        this.tableList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 查询商户名称信息
    mersNameList(){
     this.loading = true;
     mersList().then(response => {
       this.merchantsNameList = response.rows;
       this.loading = false;
     });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        merchantsId: null,
        merchantsName: null,
        account: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null,
        interestsNumberTableList:[{rightsRank:'',number:''}]
      };
      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 = "添加商户权益记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTable(id).then(response => {
        this.form = response.data;
        if(this.form.interestsNumberTableList == null){
          this.form.interestsNumberTableList = [{rightsRank:'',number:''}]
        }
        this.open = true;
        this.title = "修改商户权益记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.interestsNumberTableList[0].rightsRank == ''){
            this.$message({
                      message: '权益等级，权益次数必填',
                      type: 'warning'
                    });
             return false;
          }
          if (this.form.id != null) {
            updateTable(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTable(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商户权益记录编号为"' + ids + '"的数据项？').then(function() {
        return delTable(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/table/export', {
        ...this.queryParams
      }, `table_${new Date().getTime()}.xlsx`)
    },
    // 点击新增
    tijea(index) {
    	console.log(index+ 1)
    	this.form.interestsNumberTableList.push({
    		rightsRank: '',
    		rightsRank: '',
        plaed:'请选择权益等级',
    	});
      // this.nhyeojd = true
    },
    // 点击删除
    naeyrfakjf(index, item) {
      // console.log(this.form.czrkJzdzList.length,347)

      var that = this
      this.$confirm('是否确认删除信息?', '警告', {
      	confirmButtonText: '确定',
      	cancelButtonText: '取消',
      	type: 'warning'
      })
      	.then(function() {
      		return that.delseeug(index,item)
      	})
      	.then(() => {

      	});

    },
    delseeug(index,item){
    	console.log(234)
    	if (this.form.interestsNumberTableList.length == 1) {
        this.$message({
                  message: '只剩一条数据，无法删除',
                  type: 'warning'
                });
    		return false;
    	}
    	if (this.title == '添加商户权益记录') {
    		// 新增
        this.$modal.msgSuccess("操作成功");
    		this.form.interestsNumberTableList.splice(index, 1);
    	} else if(this.title == '修改商户权益记录') {
    		// 修改
    		// ()
        delseeu(item.numberId).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.form.interestsNumberTableList.splice(index, 1);
        });

    	}
      // this.msgSuccess('删除成功');
    },
    // 新增修改 商品名称
    optionClick(data){
       this.form.merchantsName = data
    },
    // 搜索 商品名称
    optionClicks(data){
       this.queryParams.merchantsName = data
    },

  }
};
</script>
<style>
  .hueyde {
  	width: 18px;
  	height: 18px;
  	margin: 0 5px;
  	margin-right: 10px;
  }
  .hueydele {
  	width: 15px;
  	height: 18px;
  }
</style>
