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

    <card-table :del-prop="['createTime']" :loading="loading" :modalData="discountList" :searchParams="queryParams"
                :tableSearch="true" labelWidth="120px" @columnSearch="handleQuery" @pagination="getList"
                @resetList="resetQuery">


      <template #operations="{selections}">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['user:discount:add']">{{ $t('common.add') }}</el-button>
      </template>

      <template #default="{ list }">
        <el-table-column align="center" label="No" type="index" width="50"/>
        <!-- 角色 -->
        <Column :label="$t('discount.role')" :searchDict="allRoleOptions" labelProp="roleName" prop="roleIds"
                searchType="select" selectMore showSearch valueProp="roleId">
          <template #default="{ row }">
            <span>{{ row.roleName }}</span>
          </template>
        </Column>
        <!--<Column :showSearch="true" align="center" label="角色" prop="roleName"/>-->
        <!--折扣最小值-->
        <Column :label="$t('discount.minDiscount') + '(%)'" align="center" prop="minDiscount">
          <template #default="{ row }">
            {{ row.minDiscount ? row.minDiscount.toFixed(2) : '-' }}
          </template>
        </Column>
        <!--折扣最大值-->
        <Column :label="$t('discount.maxDiscount') + '(%)'" align="center" prop="maxDiscount">
          <template #default="{ row }">
            {{ row.maxDiscount ? row.maxDiscount.toFixed(2) : '-' }}
          </template>
        </Column>
        <!--录入人-->
        <Column :label="$t('discount.createUserNick')" align="center" prop="createUserNick" showSearch/>
        <!--录入日期-->
        <Column :label="$t('discount.createTime')" align="center" prop="createTime" search-type="dateRange" showSearch/>
        <!--备注-->
        <Column :label="$t('common.remark')" align="center" prop="remark"/>
        <!--操作-->
        <Column :label="$t('common.operate')" :min-width="150" :showSearch="true" align="center" fixed="right"
                search-type="operate">
          <template #default="{ row }">
            <!--查看-->
            <el-button v-hasPermi="['user:discount:detail']" icon="el-icon-view" size="mini" type="text"
                       @click="handleView(row)">{{ $t('common.view') }}
            </el-button>
            <!--编辑-->
            <el-button v-hasPermi="['user:discount:edit']" icon="el-icon-edit" size="mini" type="text"
                       @click="handleUpdate(row)">{{ $t('common.edit') }}
            </el-button>
            <!--删除-->
            <el-button v-hasPermi="['user:discount:remove']" icon="el-icon-delete" size="mini" type="text"
                       @click="handleDelete(row)">{{ $t('common.delete') }}
            </el-button>

          </template>
        </Column>

      </template>

    </card-table>

    <!-- 添加或修改销售折扣率对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="100px">
        <!--角色-->
        <Select v-model="form.roleId" :data="allRoleOptions" :disabled="!!form.id" :label="$t('discount.role')" label-prop="roleName"
                prop="roleId"
                required value-prop="roleId"/>
        <el-row :gutter="24">
          <el-col :span="12">
            <!--折扣最小值-->
            <InputNumber v-model="form.minDiscount" :disabled="!editAble" :label="$t('discount.minDiscount') + '(%)'"
                         :precision="2" clearable
                         :rules="minDiscountRules" prop="minDiscount" required width="100%"/>
          </el-col>
          <el-col :span="12">
            <!--折扣最大值-->
            <InputNumber v-model="form.maxDiscount" :disabled="!editAble" :label="$t('discount.maxDiscount') + '(%)'"
                         :precision="2" clearable
                         :rules="maxDiscountRules" prop="maxDiscount" required width="100%"/>
          </el-col>
        </el-row>

        <!--备注-->
        <Input v-model="form.remark" :disabled="!editAble" :label="$t('common.remark')" prop="remark" type="textarea"
               width="100%"/>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="editAble" icon="el-icon-circle-check" type="primary" @click="submitForm">
          {{ $t('common.confirm') }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addDiscount, delDiscount, getDiscount, listDiscount, updateDiscount} from "@/api/user/discount";
import CardTable from "@/components/element/table/CardTable.vue";
import {getUser} from "@/api/system/user";
import Column from "@/components/element/table/Column.vue";
import InputNumber from "@/components/element/form/items/InputNumber.vue";

export default {
  name: "Discount",
  components: {InputNumber, Column, CardTable},
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售折扣率表格数据
      discountList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleId: null,
        roleIds: null,
        minDiscount: null,
        maxDiscount: null,
        createUserNick: null,
        createTime: null,
        remark: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      validatingMin: false,
      validatingMax: false,
      minDiscountRules: [
        { validator: this.validateMinV, trigger: 'blur' }
      ],
      maxDiscountRules: [
        { validator: this.validateMaxV, trigger: 'blur' }
      ],
      // 是否可编辑
      editAble: false,

      // 角色
      allRoleOptions: [],

    };
  },
  created() {
    this.getList();
    this.getAllRoleOptions();
  },
  methods: {

    validateMinV(rule, value, callback) {
      // 添加标志位控制是否触发最大值校验
      if (!this.validatingMax) {
        this.validatingMax = true; // 设置标志位为真
        if (this.form.maxDiscount !== '' && this.form.maxDiscount <= value) {
          callback(new Error(this.$t('discount.minDiscount') + this.$t('common.cannotBeGe') + this.$t('discount.maxDiscount')));
        } else {
          // 触发最大值校验
          this.$refs.form.validateField('maxDiscount');
        }
        this.validatingMax = false; // 重置标志位为假
      }
      callback();
    },
    validateMaxV(rule, value, callback) {
      // 添加标志位控制是否触发最小值校验
      if (!this.validatingMin) {
        this.validatingMin = true; // 设置标志位为真
        if (this.form.minDiscount !== '' && value <= this.form.minDiscount) {
          callback(new Error(this.$t('discount.maxDiscount') + this.$t('common.cannotBeLe') + this.$t('discount.minDiscount')));
        } else {
          // 触发最小值校验
          this.$refs.form.validateField('minDiscount');
        }
        this.validatingMin = false; // 重置标志位为假
      }
      callback();
    },

    /** 查询销售折扣率列表 */
    async getList() {
      this.loading = true;
      try {
        const {createTime, ...params} = this.queryParams;
        const response = await listDiscount(params);
        this.discountList = response.rows;
        // this.total = response.total;
        this.queryParams.total = response.total;
      } finally {
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roleId: null,
        minDiscount: null,
        maxDiscount: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.roleId = null;
      this.queryParams.roleIds = null;
      this.queryParams.minDiscount = null;
      this.queryParams.maxDiscount = null;
      this.queryParams.createUserNick = null;
      this.queryParams.createTime = null;
      this.queryParams.remark = null;
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;

      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleView(row) {
      this.reset();
      this.open = true;
      this.title = this.$t('common.view') + this.$t('discount.discountRate')
      this.editAble = false
      this.form = { ...row };
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        default:
          break;
      }
    },


    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      this.editAble = true;
      await this.getAllRoleOptions();
      this.open = true;
      this.title = this.$t('common.add') + this.$t('discount.discountRate')
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      await this.getAllRoleOptions();
      getDiscount(id).then(response => {
        this.form = response.data;
        this.editAble = true;
        this.open = true;
        this.title = this.$t('common.edit') + this.$t('discount.discountRate')
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDiscount(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDiscount(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 delDiscount(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('user/discount/export', {
        ...this.queryParams
      }, `discount_${new Date().getTime()}.xlsx`)
    },


    async getAllRoleOptions() {
      const response = await getUser();
      this.allRoleOptions = response.roles;
    },
  }
};
</script>

<style lang="scss" scoped>

/* 更多 按钮 样式 start */
@import "@/assets/styles/element-variables.scss";

.el-dropdown-menu {
  padding: 8px 0;

  .el-dropdown-menu__item {
    padding: 0 20px;
    color: $--color-primary;
  }

  .el-dropdown-menu__item + .el-dropdown-menu__item {
    margin-top: 5px;
  }
}

::v-deep .el-dropdown-menu__item i {
  margin-right: 12px !important;
}

/* 更多 按钮 样式 end */
</style>
