<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from '@/util/http'

/*
====================工具方法=========================
*/

/*
====================数据===================================
*/

// 查询当前登录的信息
const adminData = ref({
  id: '',
  adminName: ''
})

// 默认 编辑板块是关的
const regeEdit = ref(false)

// 表单引用(根据id获取信息后 将内容存到编辑表单)
const editFormRef = ref(null)


//汇率表格数据
const tableData = ref([])

//搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 10
})

const total = ref(0)

// 编辑方法 表单
const rateEdit = ref({
  id: null,
  rateName: '',
  num: null,
  adminId: null,
  updateTime: Date.now(),
})
//货币条目
const rateNames = [
  {
    value: 'USD',
    label: 'USD'
  },
  {
    value: 'HKD',
    label: 'HKD'
  },
  {
    value: 'THB',
    label: 'THB'
  },
  {
    value: 'VND',
    label: 'VND'
  },
  {
    value: 'CAD',
    label: 'CAD'
  },
  {
    value: 'MYR',
    label: 'MYR'
  },
  {
    value: 'KRW',
    label: 'KRW'
  },
  {
    value: 'JPY',
    label: 'JPY'
  },
  {
    value: 'CNY',
    label: 'CNY'
  }
]
// 汇率校验
const checkFreeGoldRadio = function (rule, value, callback) {
  if (value == '0' || value == null || value == '') {
    callback(new Error('请输入汇率比'))
  } else if (value < 0 || isNaN(value)) {
    callback(new Error('请输入正确的格式'))
  } else {
    callback()
  }
}
// 定义表单验证规则
const rules = reactive({
  rateName: [{required: true, message: '请选择货币名称', trigger: 'blur'}],
  num: [{validator: checkFreeGoldRadio, trigger: 'blur'}],
})

// 表单大小
const formSize = ref('default')

/*
====================方法=========================
*/

// 获取当前登录信息
const getAdminData = async function () {
  try {
    const result = await request({
      url: '/admin/userinfo',
      data: {}
    })
    adminData.value = result
    rateEdit.value.adminId = adminData.value.id
    console.log('请求成功', result)
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 获取所有汇率 列表
const getAllRate = async function (val) {
  try {
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val;
    }

    // 发送POST请求
    const result = await request({
      url: '/rate/selectAll',
      method: 'POST',
      data: {
        pageNum: getObj.value.pageNum,
        pageSize: getObj.value.pageSize,
      }
    });

    // 将响应结果存储到响应式数据中
    console.log('这是汇率列表 请求成功', result);

    // 存储表格数据
    tableData.value = result.data.list;
    // 存储分页总条目
    total.value = result.data.total;

  } catch (error) {
    console.log('请求失败', error);
    ElMessage.error('请求失败');
  }
}

// 获取分页数据
const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  getAllRate()
}

// 获取分页数据
const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  getAllRate()
}

//查询已有的数据（根据id）
const getEditData = async function (row) {
  try {
    console.log('搜索参数', getObj.value)
    // 发送POST请求
    const result = await request({
      url: '/rate/selectById',
      data: {id: row.id}
    })

    // 将响应结果存储到响应式数据中
    console.log('根据id查 请求成功', result)
    // 存储表格数据
    // rateEdit.value = result.data
    // 只赋部分的
    rateEdit.value.id = row.id
    rateEdit.value.rateName = row.rateName
    rateEdit.value.num = row.num
    console.log('根据id获取的数据', rateEdit.value)
    rateEdit.value.adminId = adminData.value.id

  } catch (error) {
    console.log('请求失败', error)
  }
}
// 编辑汇率
const editRate = async function () {
  // 提交前验证 汇率是否为数字
  rateEdit.value.num = parseFloat(rateEdit.value.num);
  try {
    console.log('搜索参数', rateEdit.value)
    // 发送POST请求
    const result = await request({
      url: '/rate/update',
      data: rateEdit.value
    })
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    await getAllRate()
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 编辑确认
const edit = () => {
  ElMessageBox.confirm('确认修改？')
      .then(() => {
        editRate()
        regeEdit.value = false
      })
      .catch(() => {
        regeEdit.value = false
      })
}

// 关闭编辑弹窗时重置表单
const cancelEdit = () => {
  regeEdit.value = false

}

// 关闭编辑弹窗
const handleEditDialogClose = () => {
  if (editFormRef.value) {
    getAllRate()
  }
}

// 日期格式化
function formatDate(value) {
  if (!value) return ''
  const date = new Date(value)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


// 输入框过滤
function handleInput(value) {
  // 检查是否使用了中文句号
  if (value.includes('。') || /[^\d.]/g.test(value)) {
    ElMessage.warning('请输入正确的符号');
    // value = value.replace('。', '.');
  }


  // 处理多个小数点的情况，保留第一个，移除后续的
  const parts = value.split('.');
  if (parts.length > 2) {
    value = parts[0] + '.' + parts.slice(1).join('');
    ElMessage.warning('只能包含一个小数点');
  }

  // 禁止输入负数
  if (value.startsWith('-')) {
    ElMessage.warning('不允许输入负数');
    value = value.substring(1);
  }

  // 小数点前没有数字时补0
  if (value.startsWith('.')) {
    value = '0' + value;
    // 需求没有，注释，先不显示
    // ElMessage.info('已自动补充前导0');
  }

  // 更新表单值
  rateEdit.value.num = value;

  return value;
}

/*
====================监听=========================
*/

/*
====================挂载=========================
*/

// 挂载
onMounted(async function () {
  await getAllRate()
  await getAdminData()
})


</script>


<template>
  <!-- 这是主页面 -->
  <el-row>
    <el-col>
      <el-card class="box-card" style="max-width: 100%">
        <!-- 表格 -->
        <div>
          <el-table
              :data="tableData"
              v-if="(tableData.flag = 1)"
          >
            <el-table-column
                type="index"
                label="序号"
                width="100px"
                fixed="left"
            >
              <template #default="scope">
                <span>{{
                    scope.$index + 1 + (getObj.pageNum - 1) * getObj.pageSize
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="rateName" label="货币名称" :span="2"/>
            <el-table-column prop="num" label="汇率" :span="2">
              <template #default="scope">
                <p>
                  {{ scope.row.num }} ：1
                </p>
              </template>
            </el-table-column>

            <el-table-column prop="updateTime" label="添加时间" :span="3">
              <template #default="scope">
                <span>{{ formatDate(scope.row.updateTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" :span="3">
              <template #default="scope">
                <el-button
                    type="text"
                    @click="
                    () => {
                      regeEdit = true
                      getEditData(scope.row)
                    }
                  "
                >编辑
                </el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
              background
              :page-size="getObj.pageSize"
              :page-sizes="[5, 10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handlePageSizeChange"
              @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 这是编辑弹窗 -->
  <el-dialog
      v-model="regeEdit"
      title="修改汇率"
      width="500"
      :close-on-click-modal="false"
      @close="handleEditDialogClose"
  >
    <template #footer>
      <el-form
          ref="editFormRef"
          style="max-width: 600px"
          :model="rateEdit"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
      >
        <el-form-item prop="rateName" label="货币名称:">
          <el-select
              v-model="rateEdit.rateName"
              placeholder="请选择"
              style="width: 240px"
          >
            <el-option
                v-for="item in rateNames"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="num" label="汇率:">
          <el-input
              v-model="rateEdit.num"
              @update:modelValue="handleInput"
              style="width: 120px"
          />
          <p class="unit">:1</p>
          <p class="rate-tip">
            (提示：当前规则每
            <span>{{ rateEdit.num }}</span>
            <span>{{ rateEdit.rateName }}</span>
            可兑换 1 新币)
          </p>
        </el-form-item>
        <el-form-item label="提交人:">
          <el-input disabled :value="adminData.adminName" style="width: 240px"/>
        </el-form-item>
        <el-form-item>
          <div class="dialog-footer">
            <el-button type="primary" @click="edit">修改</el-button>
            <el-button @click="cancelEdit">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
  </el-dialog>
</template>


<style scoped>
.pagination {
  margin-top: 20px;
  display: flex;
}

.box-card {
  margin-top: 20px;
}

.button-item {
  margin-left: 10px;
}

.add-item {
  margin-bottom: 10px;
}

.unit {
  margin-left: 10px;
}

.el-card {
  padding: 0px;
}

.pagination {
  display: flex;
}

.status {
  display: flex;
}

.rate-tip {
  hyphens: auto;
}
</style>
