<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/util/http'
import { useAdminStore } from "@/store/index.js";
import { storeToRefs } from "pinia";
import { findMenuById, permissionMapping } from "@/utils/menuTreePermission.js"
const adminStore = useAdminStore()
const { adminData, menuTree } = storeToRefs(adminStore)

const regeEdit = ref(false)
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({
  num: [{ validator: checkFreeGoldRadio, trigger: 'blur' }],
})
// 表单大小
const formSize = ref('default')
const getAllRate = async function (val) {
  try {
    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()
}
const getEditData = async function (row) {
  try {
    console.log('搜索参数', getObj.value)
    const result = await request({
      url: '/rate/selectById',
      data: { id: row.id }
    })
    console.log('根据id查 请求成功', result)
    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 () {
  if (findMenuById(menuTree.value, permissionMapping.Exchange_Rate_Modification)) {
    // 提交前验证 汇率是否为数字
    rateEdit.value.num = parseFloat(rateEdit.value.num);
    try {
      console.log('搜索参数', rateEdit.value)
      const result = await request({
        url: '/rate/update',
        data: rateEdit.value
      })
      console.log('请求成功', result)
      await getAllRate()
    } catch (error) {
      console.log('请求失败', error)
    }
  } else {
    ElMessage.error('没有权限')
  }
}
// 添加前验证
const edit = () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await ElMessageBox.confirm("确认修改？");
        await editRate();
        console.log("修改成功");
        regeEdit.value = false;
      } catch (error) {
        console.log("取消修改", error);
        regeEdit.value = false;
      }
    } else {
      ElMessage({
        type: "error",
        message: "请检查输入内容",
      })
    }
  })
}
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);
  }
  // 最多两位小数，超过时才显示提示
  if (value.includes('.')) {
    const parts = value.split('.')
    // 限制整数部分最多六位
    if (parts[0].length > 6) {
      parts[0] = parts[0].slice(0, 6)
      ElMessage.info('整数部分最多允许六位')
    }
    // 限制小数部分最多两位
    if (parts[1].length > 2) {
      parts[1] = parts[1].slice(0, 2)
      value = parts[0] + '.' + parts[1]
      ElMessage.info('最多允许两位小数')
    } else {
      value = parts[0] + '.' + parts[1]
    }
  } else {
    // 纯整数时限制最多六位
    if (value.length > 6) {
      value = value.slice(0, 6)
      ElMessage.info('整数部分最多允许六位')
    }
  }
  // 小数点前没有数字时补0
  if (value.startsWith('.')) {
    value = '0' + value;
    // 需求没有，注释，先不显示
    // ElMessage.info('已自动补充前导0');
  }
  // 更新表单值
  rateEdit.value.num = value

  return value
}
onMounted(async function () {
  await getAllRate()
})
</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-input v-model="rateEdit.rateName" disabled style="width: 240px" />
        </el-form-item>

        <el-form-item prop="num" label="汇率:">
          <el-input v-model="rateEdit.num" @update:modelValue="handleInput" style="width: 120px" />
          <span class="unit">:1</span>
          <span class="rate-tip">
            (提示：当前规则每
            <span>{{ rateEdit.num }}</span>
            <span>{{ rateEdit.rateName }}</span>可兑换 1 新币)
          </span>
        </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;
}

.unit {
  margin-left: 10px;
}

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