<script setup>
import { ref, onMounted, computed, reactive } from "vue";
import { ElMessageBox } from "element-plus";
import axios from "axios";
import { createApp } from "vue";
import moment from "moment";

const regeAdd = ref(false);
const regeEdit = ref(false);

//汇率表格数据
const tableData = ref([]);
//搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 5,
});
const total = ref(0);
//分页总条目
const get = async function (val) {
  try {
    // 搜索参数页码赋值
    if (typeof val === "number") {
      getObj.value.pageNum = val;
    }

    console.log("搜索参数", getObj.value);
    // 发送POST请求
    const result = await axios.post("http://192.168.8.174:10010/rates/search", {
      ...getObj.value,
      rate: { ...value1.value },
    });

    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    // 存储表格数据
    tableData.value = result.data.data.list;
    console.log("tableData", tableData.value);
    // 在这里可以根据需求进一步处理成功后的逻辑，比如更新UI显示成功消息等
    // 存储分页总条目
    total.value = result.data.data.total;
    console.log("total", total.value);
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};

// 添加方法
const rateAdd = ref({
  adminId: "1",
});
const addRate = async function () {
  try {
    console.log("搜索参数", getObj.value);
    // 发送POST请求
    const result = await axios.post(
      "http://192.168.8.174:10010/rates/add",
      rateAdd.value
    );

    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    get();
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};

const add = () => {
  Ref.value.validate(async (valid) => {
    if (valid) {
      ElMessageBox.confirm("确认添加？")
        .then(() => {
          addRate();
          rateAdd.value = {};
          value1.value = {
            startTime: "",
            endTime: "",
          };
          regeAdd.value = false;
        })
        .catch(() => {
          regeAdd.value = false;
        });
    } else {
      //提示
      ElMessage({
        type: "error",
        message: "请检查输入内容",
      });
    }
  });
};

// 编辑方法
const rateEdit = ref({});
//查询已有的数据
const getEditData = async function (row) {
  try {
    console.log("搜索参数", getObj.value);
    // 发送POST请求
    const result = await axios.post("http://192.168.8.174:10010/rates/search", {
      rate: { rateId: row.rateId },
    });

    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    // 存储表格数据
    rateEdit.value = result.data.data[0];
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};
const editRate = async function () {
  try {
    console.log("搜索参数", rateEdit.value);
    // 发送POST请求
    const result = await axios.post(
      "http://192.168.8.174:10010/rates/update",
      rateEdit.value
    );
    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    get();
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};
const edit = () => {
  ElMessageBox.confirm("确认修改？")
    .then(() => {
      editRate();
      regeEdit.value = false;
    })
    .catch(() => {
      regeEdit.value = false;
    });
};

// 删除方法
const deleteRate = async function (row) {
  try {
    // 发送POST请求
    const result = await axios.post(
      "http://192.168.8.174:10010/rates/delete/ " + row.rateId
    );
    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    get();
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};

// 挂载
onMounted(async function () {
  get();
});
//分页
function handlePageChange(currentPage, pageSize) {
  get();
}
//货币条目
const options = [
  {
    value: "USD",
    label: "USD",
  },
  {
    value: "EUR",
    label: "EUR",
  },
  {
    value: "JPY",
    label: "JPY",
  },
  {
    value: "GBP",
    label: "GBP",
  },
  {
    value: "AUD",
    label: "AUD",
  },
];

//时间选择器
const value1 = ref({
  startTime: "",
  endTime: "",
}); // 时间数组
function handleDateChange(value) {
  if (value && value.length === 2) {
    value1.value.startTime = value[0]; // 开始日期
    value1.value.endTime = value[1]; // 结束日期
  }
  console.log(value1);
}

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}`;
}

//表格高度
const tableHeight = computed(function () {
  return (getObj.value.pageSize + 1) * 50 + "px";
});

// 新增数据规则
// 表单验证ref
const Ref = ref(null);
const handleStartTimeChange = () => {
  Ref.value.validateField("endTime");
};
const checkStartTime = function (rule, value, callback) {
  if (value <= new Date()) {
    callback(new Error("开始时间不能小于当前时间"));
  } else {
    callback();
  }
};
const checkEndTime = function (rule, value, callback) {
  if (value <= new Date()) {
    callback(new Error("结束时间不能小于当前时间"));
  } else if (value <= addObj.value.startTime) {
    callback(new Error("结束时间不能小于开始时间"));
  } else {
    callback();
  }
};
const rules = reactive({
  currency: [{ required: true, message: "请选择货币名称", trigger: "blur" }],
  exchangeRate: [{ required: true, message: "请输入汇率", trigger: "blur" }],
  updateName: [{ required: true, message: "请输入添加人", trigger: "blur" }],
  startTime: [
    { required: true, message: "请选择开始时间", trigger: "blur" },
    { validator: checkStartTime, trigger: "blur" },
  ],
  endTime: [
    { required: true, message: "请选择结束时间", trigger: "blur" },
    { validator: checkEndTime, trigger: "blur" },
  ],
});

// 验证跳转输入框的数字是否合法
const checkNumber = function () {
  if (typeof parseInt(getObj.value.pageNum) === "number") {
    console.log(
      "总共有多少页" + Math.ceil(total.value / getObj.value.pageSize)
    );
    if (
      getObj.value.pageNum > 0 &&
      getObj.value.pageNum <= Math.ceil(total.value / getObj.value.pageSize)
    ) {
      console.log("输入的数字合法");
      get();
    } else {
      //提示
      ElMessage({
        type: "error",
        message: "请检查输入内容",
      });
    }
  } else {
    //提示
    ElMessage({
      type: "error",
      message: "请检查输入内容",
    });
  }
};
</script>

<template>
  <!-- 这是主页面 -->
  <el-row>
    <el-col>
      <el-card>
        <!-- 这是时间 -->
        <div class="demo-range">
          时间：
          <el-date-picker
            v-model="value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="handleDateChange"
            :size="size"
            value-format="YYYY-MM-DD"
          />
          <!-- 按钮 -->
          <el-button
            class="button-item"
            type="primary"
            style="float: right"
            @click="get"
            >查询</el-button
          >
          <el-button
            class="button-item"
            style="float: right"
            @click="handledelete"
            >重置</el-button
          >
        </div>
      </el-card>
    </el-col>
  </el-row>

  <el-row>
    <el-col>
      <el-card class="box-card" style="max-width: 100%">
        <!-- 添加 -->
        <div class="add-item">
          <el-button
            style="color: #048efb; border: 1px solid #048efb"
            @click="regeAdd = true"
            >新增汇率</el-button
          >
        </div>
        <!-- 表格 -->
        <div>
          <el-table
            :data="tableData"
            v-if="(tableData.flag = 1)"
            :height="tableHeight"
            style="width: 100%"
          >
            <el-table-column prop="currency" label="货币名称" :span="3" />
            <el-table-column prop="exchangeRate" label="汇率" :span="3">
              <template #default="scope">
                <p>{{ scope.row.exchangeRate }} ：1新币</p>
              </template>
            </el-table-column>

            <el-table-column prop="createTime" label="添加时间" :span="5">
              <template #default="scope">
                <span>{{ formatDate(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" :span="5">
              <template #default="scope">
                <span>{{ formatDate(scope.row.updateTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="updateName" label="更新人" :span="4" />
            <el-table-column label="操作" :span="4">
              <template #default="scope">
                <el-button
                  type="text"
                  @click="
                    regeEdit = true;
                    getEditData(scope.row);
                  "
                  >编辑</el-button
                >
                <el-button type="text" @click="deleteRate(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            background
            :page-size="getObj.pageSize"
            layout="slot"
            :total="total"
          >
            <div>共{{ total }}条,每页</div>
            <el-select
              v-model="getObj.pageSize"
              class="page-size"
              @change="get()"
              style="width: 80px"
            >
              <el-option
                v-for="item in [5, 6, 7, 8, 9, 10]"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <div>条</div>
          </el-pagination>
          <el-pagination
            background
            layout="prev, pager, next, slot"
            :page-size="getObj.pageSize"
            :total="total"
            :current-page="getObj.pageNum"
            @current-change="get"
          >
            <div>跳至</div>
            <el-input
              v-model="getObj.pageNum"
              style="width: 40px"
              @change="checkNumber"
            />
            <div>页</div>
          </el-pagination>
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 这是添加弹窗 -->
  <el-dialog v-model="regeAdd" title="新增汇率" width="500">
    <template #footer>
      <el-form
        ref="Ref"
        style="max-width: 600px"
        :model="rateAdd"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item prop="currency" label="货币名称:">
          <el-select
            v-model.number="rateAdd.currency"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="exchangeRate" label="汇率:">
          <el-input v-model="rateAdd.exchangeRate" style="width: 120px" />
          <p class="unit">:1</p>
          <p>(提示：当前规则每 5 元人民币可兑换 1 新币)</p>
        </el-form-item>
        <el-form-item prop="updateName" label="提交人:">
          <el-input v-model="rateAdd.updateName" style="width: 240px" />
        </el-form-item>
        <el-form-item prop="startTime" label="开始时间:">
          <el-date-picker
            v-model="rateAdd.startTime"
            type="date"
            placeholder="请选择时间"
            :default-value="new Date()"
            @change="handleStartTimeChange"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item prop="endTime" label="结束时间:">
          <el-date-picker
            v-model="rateAdd.endTime"
            type="date"
            placeholder="请选择时间"
            :default-value="new Date()"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <div class="dialog-footer">
            <el-button type="primary" @click="add">添加</el-button>
            <el-button @click="regeAdd = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
  </el-dialog>

  <!-- 这是编辑弹窗 -->
  <el-dialog v-model="regeEdit" title="修改汇率" width="500">
    <template #footer>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="rateEdit"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="货币名称:">
          <el-select
            v-model="rateEdit.currency"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="汇率:">
          <el-input v-model="rateEdit.exchangeRate" style="width: 120px" />
          <p class="unit">:1</p>
          <p>(提示：当前规则每 5 元人民币可兑换 1 新币)</p>
        </el-form-item>
        <el-form-item label="提交人:">
          <el-input v-model="rateEdit.updateName" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <div class="dialog-footer">
            <el-button type="primary" @click="edit">修改</el-button>
            <el-button @click="regeEdit = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
  </el-dialog>

  <!-- 这是编辑弹窗 -->
  <el-dialog v-model="regeEdit" title="修改汇率" width="500">
    <template #footer>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="rateEdit"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="货币名称:">
          <el-select
            v-model="rateEdit.currency"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="汇率:">
          <el-input v-model="rateEdit.exchangeRate" style="width: 120px" />
          <p class="unit">:1</p>
          <p>(提示：当前规则每 5 元人民币可兑换 1 新币)</p>
        </el-form-item>
        <el-form-item label="提交人:">
          <el-input v-model="rateEdit.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="regeEdit = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
  </el-dialog>
</template>

<style scoped>
p {
  margin: 0px;
}

.el-form-item {
  margin-left: 70px;
}

.ad {
  margin-left: 10px;
}

.pagination {
  margin-top: 20px;
  margin-left: 33%;
}

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

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

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

el-table-column {
  text-align: center;
}

p {
  color: rgb(150, 150, 150);
}

.unit {
  margin-left: 10px;
}

.el-card {
  padding: 0px;
}
.pagination {
  display: flex;
}
</style>
