<template>
  <div :v-loading="pageLoading" class="app-container">

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

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

      <template #default="{ list }">
        <el-table-column align="center" label="No" type="index" width="50"/>
        <!--币种-->
        <Column :label="$t('currency.currencyName')" :showSearch="true" align="center" prop="currencyName"/>
        <!--汇率-->
        <Column :label="$t('currency.exchangeRate')" :showSearch="true" align="center" prop="exchangeRate"/>
        <!--有效日期-->
        <Column :label="$t('currency.expiration')" align="center" width="300px">
          <template #default="{ row }">
            {{ row.effectiveDate }} - {{ row.expirationDate }}
          </template>
        </Column>
        <!--录入人-->
        <Column :label="$t('currency.inputer')" :showSearch="true" align="center" prop="createUserNick"/>
        <!--录入日期-->
        <Column :label="$t('currency.inputDate')" :showSearch="true" align="center" prop="createTime"
                search-type="dateRange"/>
        <!--备注-->
        <Column :label="$t('common.remark')" :showSearch="true" 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:currency:detail']" icon="el-icon-view" size="mini" type="text"
                       @click="handleView(row)">{{ $t('common.view') }}
            </el-button>

            <el-dropdown v-hasPermi="['user:currency:edit', 'user:currency:remove']" size="mini"
                         @command="(command) => handleCommand(command, row)">
              <el-button icon="el-icon-d-arrow-right" size="mini" type="text">{{ $t('common.more') }}</el-button>

              <el-dropdown-menu slot="dropdown">
                <!--修改-->
                <el-dropdown-item v-hasPermi="['user:currency:edit']" command="handleUpdate"
                                  icon="el-icon-edit">{{ $t('common.edit') }}
                </el-dropdown-item>
                <!--删除-->
                <el-dropdown-item v-hasPermi="['user:currency:remove']" command="handleDelete"
                                  icon="el-icon-delete">{{ $t('common.delete') }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <!--&lt;!&ndash;修改&ndash;&gt;-->
            <!--<el-button v-hasPermi="['user:currency:edit']" icon="el-icon-edit" size="mini" type="text"-->
            <!--           @click="handleUpdate(row)">{{ $t('common.edit') }}-->
            <!--</el-button>-->
            <!--&lt;!&ndash;删除&ndash;&gt;-->
            <!--<el-button v-hasPermi="['user:currency: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="30vw">
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="12">
            <!--币种-->
            <Input v-model="form.currencyName" :disabled="!editAble" :label="$t('currency.currencyName')"
                   prop="currencyName" required
                   width="100%"/>
          </el-col>
          <el-col :span="12">
            <!--汇率-->
            <InputNumber v-model="form.exchangeRate" :disabled="!editAble" :label="$t('currency.exchangeRate')"
                         :precision="5"
                         :rules="exchangeRateRules"
                         prop="exchangeRate" required width="100%"/>
          </el-col>
        </el-row>
        <DatePickerRange :disabled="!editAble" :label="$t('currency.expiration')" :required="true"
                         prop="dateRange" prop-end="expirationDate" prop-start="effectiveDate"
                         type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" width="100%"/>
        <!--备注-->
        <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 {addCurrency, delCurrency, getCurrency, listCurrency, updateCurrency} from "@/api/user/currency";
import CardTable from "@/components/element/table/CardTable.vue";
import Column from "@/components/element/table/Column.vue";
import DatePickerRange from "@/components/element/form/items/DatePickerRange.vue";
import InputNumber from "@/components/element/form/items/InputNumber.vue";

export default {
  name: "Currency",
  components: {InputNumber, DatePickerRange, Column, CardTable},
  data() {
    return {
      pageLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 币种汇率表格数据
      currencyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        currencyName: null,
        exchangeRate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 是否可编辑
      editAble: false,
      // 汇率校验
      exchangeRateRules: [
        // {required: true, message: "请输入汇率", trigger: "blur"},
        {
          validator: (rule, value, callback) => {
            const reg = /^\d+(\.\d{1,5})?$/; // 匹配正整数或者五位小数的正则表达式
            if (!value || reg.test(value)) {
              callback();
            } else {
              callback(new Error(this.$t('currency.ruleExchangeRange')));
            }
          }, trigger: 'blur'
        },
        {
          validator: (rule, value, callback) => {
            if (value === 0) {
              callback(new Error(this.$t('currency.exchangeRate') + this.$t('common.ruleCannotBe0')));
            } else {
              callback();
            }
          }, trigger: 'blur'
        }
      ],

    };
  },
  created() {
  },
  methods: {
    /** 查询币种汇率列表 */
    async getList() {
      this.loading = true;
      try {
        const response = await listCurrency(this.queryParams);
        this.currencyList = response.rows;
        // this.total = response.total;
        this.queryParams.total = response.total;
      } finally {
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        currencyId: null,
        currencyName: null,
        exchangeRate: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        dateRange: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {

      this.queryParams.currencyName = null;
      this.queryParams.exchangeRate = null;
      this.queryParams.createUserNick = null;
      this.queryParams.createTime = null;
      this.queryParams.remark = null;
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;

      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.currencyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleView(row) {
      this.reset();
      this.title = this.$t('common.view');
      this.editAble = false
      this.form = row;
      this.form.dateRange = [row?.effectiveDate, row?.expirationDate];
      this.open = true;
    },


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

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.editAble = true;
      this.open = true;
      this.title = this.$t('common.add') + this.$t('currency.currencyExchange');
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.pageLoading = true;
      try {
        const currencyId = row.currencyId || this.ids
        const response = await getCurrency(currencyId);
        if (!response.data) {
          this.$modal.msgError(this.$t('common.noDataEmptyText'));
          return;
        }
        this.form = response.data;
        this.form.dateRange = [response.data?.effectiveDate, response.data?.expirationDate];
        this.editAble = true;
        this.open = true;
        this.title = this.$t('common.edit') + this.$t('currency.currencyExchange');
      } finally {
        this.pageLoading = false;
      }
    },
    /** 提交按钮 */
    submitForm2() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.currencyId != null) {
            updateCurrency(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.open = false;
              this.getList();
            });
          } else {
            addCurrency(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          this.pageLoading = true;
          try {
            const response = this.form.currencyId != null ?
              await updateCurrency(this.form) :
              await addCurrency(this.form);

            if (response) {
              const message = this.form.currencyId != null ? this.$t('common.editSuccess') : this.$t('common.addSuccess');
              this.$modal.msgSuccess(message);
              this.open = false;
            }
          } finally {
            this.pageLoading = false;
          }
          this.getList();
        }
      });
    },

    /** 删除按钮操作 */
    async handleDelete(row) {
      try {
        const currencyIds = row.currencyId || this.ids;
        await this.$modal.confirm(this.$t('common.isDelete'));
        this.pageLoading = true;
        await delCurrency(currencyIds);
        this.getList();
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      } finally {
        this.pageLoading = false;
      }
    },

    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('user/currency/export', {
    //     ...this.queryParams
    //   }, `currency_${new Date().getTime()}.xlsx`)
    // }
  }
};
</script>


<style lang='scss'>
.btn-custom-cancel {
  float: right;
  margin-left: 10px;
}
</style>


<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>
