<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 type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['user:contractCurrency:add']">{{ $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.currencyName')"  :search-dict="dict.type.currency_type"
                :search-params="queryParams"
                :showSearch="true"
                prop="currencyName"  search-type="select" select-prop="currencyNameList" selectMore/>

        <!--汇率-->
        <Column :label="$t('currency.exchangeRate')" 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.effectiveDate')" :showSearch="true" align="center" prop="effectiveDate"
                propStart='effectiveStart' propEnd="effectiveEnd" search-type="dateRange">
          <template #default="{ row }">
            {{ row.effectiveDate ? $moment(row.effectiveDate).format('YYYY-MM-DD') : '-' }}
          </template>
        </Column>
        <!--失效日期-->
        <Column :label="$t('currency.expirationDate')" :showSearch="true" align="center" prop="expirationDate"
                propStart='expirationStart' propEnd="expirationEnd" search-type="dateRange">
          <template #default="{ row }">
            {{ row.expirationDate ? $moment(row.expirationDate).format('YYYY-MM-DD') : '-' }}
          </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')" 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:contractCurrency:detail']" icon="el-icon-view" size="mini" type="text"
                       @click="handleView(row)">{{ $t('common.view') }}
            </el-button>

            <el-button v-hasPermi="['user:contractCurrency:edit']" icon="el-icon-edit" size="mini" type="text"
                       @click="handleUpdate(row)">{{ $t('common.edit') }}
            </el-button>

            <el-button v-hasPermi="['user:contractCurrency: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%"/>-->
            <Select :data="dict.type.currency_type" v-model="form.currencyName" :disabled="!editAble" required
                    :label="$t('currency.currencyName')" prop="currencyName" 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>
        <!--prop-end="expirationDate" prop-start="effectiveDate"-->
        <DatePickerRange :disabled="!editAble" :label="$t('currency.expiration')" :required="true"
                         prop="dateRange"
                         type="daterange" value-format="yyyy-MM-dd" 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/contractCurrency";
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: "ContractCurrency",
  dicts: ['currency_type'],
  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,
        currencyNameList:[]
      },
      // 表单参数
      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() {
    this.getList()
  },
  methods: {
    /** 查询币种汇率列表 */
    async getList() {
      this.loading = true;
      try {
        const {effectiveDate, expirationDate, createTime, ...params} = this.queryParams;
        // const response = await listCurrency(this.queryParams);
        const response = await listCurrency(params);
        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.$set(this.queryParams, 'currencyName', []);
      this.$set(this.queryParams, 'exchangeRate', null);
      this.$set(this.queryParams, 'createUserNick', null);
      this.$set(this.queryParams, 'createTime', null);
      this.$set(this.queryParams, 'effectiveDate', null);
      this.$set(this.queryParams, 'effectiveStart', null);
      this.$set(this.queryParams, 'effectiveEnd', null);
      this.$set(this.queryParams, 'expirationDate', null);
      this.$set(this.queryParams, 'expirationStart', null);
      this.$set(this.queryParams, 'expirationEnd', null);
      this.$set(this.queryParams, 'remark', null);
      this.$set(this.queryParams, 'beginTime', null);
      this.$set(this.queryParams, 'endTime', null);
      this.$set(this.queryParams, 'currencyNameList', []);

      // 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.pageLoading = true;
      this.reset();
      this.title = this.$t('common.view');
      this.editAble = false
      // this.form = { ...row };
      // this.form.dateRange = [row?.effectiveDate, row?.expirationDate];
      getCurrency(row.currencyId).then(res => {
        this.form = res.data;
        this.open = true;
        this.pageLoading = false;
      });
    },


    // 更多操作触发
    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;
      }
    },
    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>
