<template>
  <basic-container class="currency-page">
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      v-model="form"
      ref="crud"
      :permission="permissionList"
      :before-open="beforeOpen"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button
          type="primary"
          icon="el-icon-upload"
          plain
          v-if="permission.currency_import"
          @click="handleImport"
          >批量导入
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="permission.currency_template"
          @click="handleTemplate"
          >下载模板
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          plain
          v-if="permission.currency_export"
          @click="handleExport"
          >批量导出
        </el-button>
      </template>
      <template #codeForm>
        <el-autocomplete
          v-model="form.code"
          :fetch-suggestions="fetchCurrencyOptions"
          clearable
          placeholder="请输入币种编码查询选择"
          value-key="code"
          class="currency-page__input"
          @select="handleCurrencySelect"
          @change="handleCodeChange"
        >
          <template #default="{ item }">
            <span>{{ item.code }}</span>
            <span class="currency-page__option-name">{{ item.name }}</span>
          </template>
        </el-autocomplete>
      </template>
      <template #status="{ row }">
        <el-tag :type="row.status === 1 ? 'primary' : 'info'">
          {{ row.status === 1 ? '启用' : '停用' }}
        </el-tag>
      </template>
      <template #menu="{ row, index }">
        <el-link
          type="primary"
          v-if="permission.currency_edit"
          @click="$refs.crud.rowEdit(row, index)"
        >
          编辑
        </el-link>
        <el-link
          type="primary"
          v-if="permission.currency_status"
          @click="handleStatus(row)"
        >
          {{ row.status === 1 ? '停用' : '启用' }}
        </el-link>
      </template>
    </avue-crud>

    <el-dialog title="币种汇率导入" append-to-body v-model="excelBox" width="555px">
      <avue-form :option="excelOption" v-model="excelForm">
        <template #excelTemplate>
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { changeStatus, getDetail, getList, submit } from '@/api/base/currency';
import { exportBlob } from '@/api/common';
import { mapGetters } from 'vuex';
import { downloadXls } from '@/utils/util';
import { openImportDialog } from '@/utils/import-excel';
import { formatUpdateUserName } from '@/utils/audit';
import { getToken } from '@/utils/auth';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

const statusDic = [
  { label: '启用', value: 1 },
  { label: '停用', value: 2 },
];

const sourceDic = [
  { label: '手工录入', value: '手工录入' },
  { label: '批量导入', value: '批量导入' },
];

export default {
  data() {
    const validateCurrencyCode = (rule, value, callback) => {
      if (!/^[A-Z]{3}$/.test(value || '')) {
        callback(new Error('币种编码为3位大写字母'));
      } else {
        callback();
      }
    };
    const validateExchangeRate = (rule, value, callback) => {
      if (value === undefined || value === null || value === '') {
        callback();
      } else if (Number(value) <= 0) {
        callback(new Error('汇率必须大于0'));
      } else if (!/^\d+(\.\d{1,6})?$/.test(String(value))) {
        callback(new Error('汇率最多保留6位小数'));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      loading: true,
      data: [],
      excelBox: false,
      excelForm: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        dialogWidth: 860,
        labelPosition: 'right',
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        searchIcon: true,
        searchIndex: 4,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        menuWidth: 180,
        menuFixed: 'right',
        column: [
          {
            label: '币种编码',
            prop: 'code',
            search: true,
            formslot: true,
            minWidth: 120,
            maxlength: 3,
            rules: [
              { required: true, message: '请选择币种编码', trigger: 'blur' },
              { validator: validateCurrencyCode, trigger: 'blur' },
            ],
          },
          {
            label: '币种名称',
            prop: 'name',
            minWidth: 150,
            search: true,
            rules: [{ required: true, message: '请输入币种名称', trigger: 'blur' }],
          },
          {
            label: '汇率',
            prop: 'exchangeRate',
            type: 'number',
            minWidth: 120,
            precision: 6,
            rules: [{ validator: validateExchangeRate, trigger: 'blur' }],
          },
          {
            label: '生效日期',
            prop: 'effectiveDate',
            sortable: true,
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            minWidth: 130,
            rules: [{ required: true, message: '请选择生效日期', trigger: 'click' }],
          },
          {
            label: '生效日期',
            prop: 'effectiveDateRange',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            searchRange: true,
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: '失效日期',
            prop: 'expiryDate',
            sortable: true,
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            minWidth: 130,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '失效日期',
            prop: 'expiryDateRange',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            searchRange: true,
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            search: true,
            slot: true,
            dataType: 'number',
            dicData: statusDic,
            value: 1,
            minWidth: 100,
          },
          {
            label: '来源',
            prop: 'dataSource',
            type: 'select',
            search: true,
            dicData: sourceDic,
            value: '手工录入',
            minWidth: 120,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 4,
            span: 24,
            hide: true,
            maxlength: 200,
            showWordLimit: true,
            rules: [{ max: 200, message: '最多 200 个字符', trigger: 'blur' }],
          },
          {
            label: '更新人',
            prop: 'updateUserName',
            formatter: formatUpdateUserName,
            addDisplay: false,
            editDisplay: false,
            minWidth: 120,
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            sortable: true,
            type: 'datetime',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            addDisplay: false,
            editDisplay: false,
            display: false,
            minWidth: 160,
          },
          {
            label: '更新时间',
            prop: 'updateTimeRange',
            type: 'datetime',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            searchRange: true,
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
        ],
      },
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/blade-system/currency/import-currency',
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.currency_add, false),
      };
    },
    ids() {
      return this.selectionList.map(ele => ele.id).join(',');
    },
  },
  methods: {
    handleCodeChange(value) {
      this.form.code = String(value || '')
        .toUpperCase()
        .replace(/[^A-Z]/g, '')
        .slice(0, 3);
      const matched = this.data.find(item => item.code === this.form.code);
      if (matched) {
        this.form.name = matched.name;
      }
    },
    fetchCurrencyOptions(queryString, callback) {
      getList(1, 20, { code: String(queryString || '').toUpperCase() })
        .then(res => {
          const records = res.data.data.records || [];
          const exists = new Map();
          records.forEach(item => {
            if (!exists.has(item.code)) {
              exists.set(item.code, {
                code: item.code,
                value: item.code,
                name: item.name,
              });
            }
          });
          callback(Array.from(exists.values()));
        })
        .catch(() => callback([]));
    },
    handleCurrencySelect(item) {
      this.form.code = item.code;
      this.form.name = item.name;
    },
    normalizeRow(row) {
      const values = { ...row };
      values.code = String(values.code || '').toUpperCase();
      values.exchangeRate = values.exchangeRate === '' ? null : values.exchangeRate;
      values.dataSource = values.dataSource || '手工录入';
      values.status = values.status || 1;
      return values;
    },
    validateRow(row) {
      if (row.remark && row.remark.length > 200) {
        this.$message.warning('备注不能超过 200 字');
        return false;
      }
      if (
        row.exchangeRate !== undefined &&
        row.exchangeRate !== null &&
        row.exchangeRate !== '' &&
        Number(row.exchangeRate) <= 0
      ) {
        this.$message.warning('汇率必须大于0');
        return false;
      }
      if (
        row.exchangeRate !== undefined &&
        row.exchangeRate !== null &&
        row.exchangeRate !== '' &&
        !/^\d+(\.\d{1,6})?$/.test(String(row.exchangeRate))
      ) {
        this.$message.warning('汇率最多保留6位小数');
        return false;
      }
      return true;
    },
    rowSave(row, done, loading) {
      const values = this.normalizeRow(row);
      if (!this.validateRow(values)) {
        loading();
        return;
      }
      submit(values).then(
        () => {
          this.onLoad(this.page);
          this.$message({ type: 'success', message: '操作成功!' });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      const values = this.normalizeRow(row);
      if (!this.validateRow(values)) {
        loading();
        return;
      }
      submit(values).then(
        () => {
          this.onLoad(this.page);
          this.$message({ type: 'success', message: '操作成功!' });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    handleStatus(row) {
      const nextStatus = row.status === 1 ? 2 : 1;
      const actionName = nextStatus === 1 ? '启用' : '停用';
      this.$confirm(`是否确认${actionName}该条汇率？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => changeStatus(row.id, nextStatus))
        .then(() => {
          this.onLoad(this.page);
          this.$message({ type: 'success', message: '操作成功!' });
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          done();
        });
        return;
      }
      this.form = {
        status: 1,
        dataSource: '手工录入',
      };
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    buildQuery(params = {}) {
      const values = { ...params, ...this.query };
      const rangeMap = {
        effectiveDateRange: ['effectiveDateStart', 'effectiveDateEnd'],
        expiryDateRange: ['expiryDateStart', 'expiryDateEnd'],
        updateTimeRange: ['updateTimeStart', 'updateTimeEnd'],
      };
      Object.keys(rangeMap).forEach(key => {
        const range = values[key];
        if (range && range.length === 2) {
          values[rangeMap[key][0]] = range[0];
          values[rangeMap[key][1]] = range[1];
        }
        values[key] = null;
      });
      return values;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, this.buildQuery(params))
        .then(res => {
          const result = res.data.data;
          this.page.total = result.total;
          this.data = result.records;
          if (result.records.length === 0 && result.total > 0 && page.currentPage > 1) {
            this.page.currentPage = page.currentPage - 1;
            this.onLoad(this.page, this.query);
          }
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleImport() {
      openImportDialog(this, '币种汇率');
    },
    handleExport() {
      this.$confirm('是否导出币种汇率数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob('/blade-system/currency/export-currency', this.buildExportParams(), { feedback: true })
          .then(res => {
            downloadXls(res.data, `币种汇率${this.$dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`);
          })
          .finally(() => {
            NProgress.done();
          });
      });
    },
    buildExportParams() {
      return {
        ...this.buildQuery(),
        ids: this.ids,
        [this.website.tokenHeader]: getToken(),
      };
    },
    handleTemplate() {
      exportBlob(
        `/blade-system/currency/export-template?${this.website.tokenHeader}=${getToken()}`,
        { feedback: true }
      ).then(res => {
        downloadXls(res.data, '币种汇率模板.xlsx');
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.currency-page {
  :deep(.el-table th .cell),
  :deep(.el-table td .cell) {
    white-space: nowrap;
  }

  &__input {
    width: 100%;
  }

  &__option-name {
    float: right;
    color: #8492a6;
    font-size: 13px;
    margin-left: 16px;
  }
}
</style>
