<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 { permissionMapping, hasMenuPermission } from "@/utils/menuTreePermission.js"
import { useI18n } from 'vue-i18n'
const { t } = useI18n()


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(t('elmessage.pleaseInputRate')))
  } else if (value < 0 || isNaN(value)) {
    callback(new Error(t('elmessage.pleaseInputCorrectRateFormat')))
  } 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(t('elmessage.requestFailed'));
  }
}
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 hasrateShow = ref(false)
const hasrateEdit = ref(false)

// 初始化权限状态
const initPermissions = () => {
  if (!menuTree.value || !menuTree.value.length) return;
  hasrateShow.value = hasMenuPermission(menuTree.value, permissionMapping.view_exchange_rate);
  hasrateEdit.value = hasMenuPermission(menuTree.value, permissionMapping.edit_exchange_rate);

};
// 编辑汇率
const editRate = async function () {
  if (!hasrateEdit) {
    ElMessage.error(t('elmessage.noPermission'))
    return
  }
  // 提交前验证 汇率是否为数字
  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)
  }

}
// 添加前验证
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(t('elmessage.pleaseInputCorrectSymbol'));
    // value = value.replace('。', '.');
  }
  // 处理多个小数点的情况，保留第一个，移除后续的
  const parts = value.split('.');
  if (parts.length > 2) {
    value = parts[0] + '.' + parts.slice(1).join('');
    ElMessage.warning(t('elmessage.onlyOneDecimalPoint'));
  }
  // 禁止输入负数
  if (value.startsWith('-')) {
    ElMessage.warning(t('elmessage.noNegativeNumber'));
    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(t('elmessage.integerPartLimit'))
    }
    // 限制小数部分最多两位
    if (parts[1].length > 7) {
      parts[1] = parts[1].slice(0, 7)
      value = parts[0] + '.' + parts[1]
      ElMessage.info(t('elmessage.decimalPartLimit'))
    } else {
      value = parts[0] + '.' + parts[1]
    }
  } else {
    // 纯整数时限制最多六位
    if (value.length > 6) {
      value = value.slice(0, 6)
      ElMessage.info(t('elmessage.integerPartLimit'))
    }
  }
  // 小数点前没有数字时补0
  if (value.startsWith('.')) {
    value = '0' + value;
    // 需求没有，注释，先不显示
    // ElMessage.info('已自动补充前导0');
  }
  // 更新表单值
  rateEdit.value.num = value

  return value
}

onMounted(async function () {
  initPermissions()
  await getAllRate()
})
</script>

<template>
  <el-card class="card2" style="width:81vw;height:92vh" v-if="hasrateShow">
    <el-table :data="tableData" v-if="(tableData.flag = 1)">
      <el-table-column type="index" :label="t('common_list.id')" 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="t('common_list.rateName')" :span="2" />
      <el-table-column prop="num" :label="t('common_list.num')" :span="2">
        <template #default="scope">
          <p>
            {{ scope.row.num }} ：1
          </p>
        </template>
      </el-table-column>

      <el-table-column prop="updateTime" :label="t('common_list.updateTime')" :span="3">
        <template #default="scope">
          <span>{{ formatDate(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="hasrateEdit" :label="t('common_list.operation')" :span="3">
        <template #default="scope">
          <el-link :underline="false" class="edit-btn" @click="() => {
            regeEdit = true
            getEditData(scope.row)
          }">{{ t('common.edit') }}
          </el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <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-dialog align-center v-model="regeEdit" :title="t('rate.modifyRate')" width="30vw" :close-on-click-modal="false"
    @close="handleEditDialogClose">
    <el-form ref="editFormRef" :model="rateEdit" :rules="rules" label-width="auto" class="edit-form" :size="formSize"
      status-icon>
      <el-form-item prop="rateName" :label="t('common_list.rateName')">
        <el-input v-model="rateEdit.rateName" disabled style="width: 10vw" />
      </el-form-item>

      <el-form-item prop="num" :label="t('common_list.num')">
        <el-input v-model="rateEdit.num" @update:modelValue="handleInput" style="width: 120px" />
        <span class="unit">:1</span>
      </el-form-item>
      <div class="rate-tip">
        {{ t('rate.prompt1') }}
        <span>{{ rateEdit.num }}</span>
        <span>{{ rateEdit.rateName }}</span>{{ t('rate.prompt2') }}
      </div>

    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" @click="edit">{{ t('common.modify') }}</el-button>
      <el-button @click="cancelEdit">{{ t('common.cancel') }}</el-button>
    </div>
  </el-dialog>
</template>


<style scoped>
.card1 {
  background: #F3FAFE;
}

:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
/* 表格 */
:deep(.el-table__body td) {
  background-color: #F3FAFE !important;
}

/* 表头 */
:deep(.el-table__header th) {
  background-color: #F3FAFE !important;
}

/* 鼠标悬停 */
:deep(.el-table__row:hover > .el-table__cell) {
  background-color: #E5EBFE !important;
}


.pagination {
  margin-top: 20px;
  display: flex;
}

.edit-form {
  width: 35vw;
  height: 13vh;
}

.dialog-footer {
  display: flex;
  margin-left: 5vw;
}

.unit {
  margin-left: 0.5vw;
}

.rate-tip {
  hyphens: auto;
  margin-left: 1.4vw;
}

/**表单的卡片样式**/
.card2 {
  background: #E7F4FD;
}


/**表头背景等**/
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
/* 表格 */
:deep(.el-table__body td) {
  background-color: #F3FAFE !important;
}

/* 表头 */
:deep(.el-table__header th) {
  background-color: #F3FAFE !important;
}

/* 鼠标悬停 */
:deep(.el-table__row:hover > .el-table__cell) {
  background-color: #E5EBFE !important;
}
</style>