<script setup>
import { ref, onMounted, computed, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { createApp } from "vue";
import moment from "moment";
import API from "../../api/index.js";
import _ from "lodash";

// 查询用户接口
const adminData = ref({
  name: "",
});
const getAdminData = async function () {
  try {
    const result = await API.post(
      "http://39.99.159.73:20090/admin/userinfo",
      {}
    );
    adminData.value = result;
    rateAdd.value.adminId = adminData.value.adminId;
    rateEdit.value.adminId = adminData.value.adminId;
    console.log("请求成功", result);
    console.log("用户信息", user.value);
  } catch (error) {
    console.log("请求失败", error);
  }
};
getAdminData();

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

//汇率表格数据
const tableData = ref([]);
//搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0);
//分页总条目

//时间选择器
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);
}

const time = ref({});
const get = async function (val) {
  // 搜索参数时间赋值
  if (value1.value != null) {
    if (value1.value.startDate != "" && value1.value.endDate != "") {
      time.value.startTime = value1.value[0];
      time.value.endTime = value1.value[1];
    }
  } else {
    time.value.startTime = "";
    time.value.endTime = "";
  }
  try {
    // 搜索参数页码赋值
    if (typeof val === "number") {
      getObj.value.pageNum = val;
    }

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

    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    // 存储表格数据
    tableData.value = result.data.list;
    console.log("tableData", tableData.value);
    // 在这里可以根据需求进一步处理成功后的逻辑，比如更新UI显示成功消息等
    // 存储分页总条目
    total.value = result.data.total;
    console.log("total", total.value);
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};
// 搜索
const search = function () {
  getObj.value.pageNum = 1;
  get();
};
// 添加方法
const rateAdd = ref({});
const addRate = async function () {
  rateAdd.value.adminId = adminData.value.adminId;
  if (rateAdd.value.startTime) {
    const date = new Date(rateAdd.value.startTime);
    date.setHours(0, 0, 0, 0);
    rateAdd.value.startTime = `${date.getFullYear()}-${String(
      date.getMonth() + 1
    ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} 00:00:00`;
  }
  if (rateAdd.value.endTime) {
    const date = new Date(rateAdd.value.endTime);
    date.setHours(23, 59, 59, 999);
    rateAdd.value.endTime = `${date.getFullYear()}-${String(
      date.getMonth() + 1
    ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} 23:59:59`;
  }
  try {
    console.log("搜索参数", getObj.value);
    // 发送POST请求
    const result = await API.post(
      "http://39.99.159.73:20090/rates/add",
      rateAdd.value
    );
    if (result.code == 0) {
      ElMessage.error(result.msg);
    }
    // 将响应结果存储到响应式数据中
    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: "请检查输入内容",
      });
    }
  });
};
// 使用 _.throttle 并设置 trailing 为 false 实现严格节流，只执行一次
const throttledAdd = _.throttle(add, 5000, { trailing: false });
// 编辑方法
const rateEdit = ref({});
//查询已有的数据
const getEditData = async function (row) {
  try {
    console.log("搜索参数", getObj.value);
    // 发送POST请求
    const result = await API.post(
      "http://39.99.159.73:20090/rates/searchById?rateId=" + row.rateId,
      {}
    );

    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    // 存储表格数据

    rateEdit.value = result.data;
    rateEdit.value.adminId = adminData.value.adminId;
    console.log("这是编辑的数值", rateEdit.value);
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};
const editRate = async function () {
  if (rateEdit.value.startTime) {
    const date = new Date(rateEdit.value.startTime);
    date.setHours(0, 0, 0, 0);
    rateEdit.value.startTime = `${date.getFullYear()}-${String(
      date.getMonth() + 1
    ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} 00:00:00`;
  }
  if (rateEdit.value.endTime) {
    const date = new Date(rateEdit.value.endTime);
    date.setHours(23, 59, 59, 999);
    rateEdit.value.endTime = `${date.getFullYear()}-${String(
      date.getMonth() + 1
    ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} 23:59:59`;
  }
  try {
    console.log("搜索参数", rateEdit.value);
    // 发送POST请求
    const result = await API.post(
      "http://39.99.159.73:20090/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 API.post(
      "http://39.99.159.73:20090/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",
  },
];

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 formatDateTwe(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");
  return `${year}-${month}-${day}`;
}

// //表格高度
// 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 <= rateAdd.value.startTime) {
    callback(new Error("结束时间不能小于开始时间"));
  } else {
    callback();
  }
};
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({
  currency: [{ required: true, message: "请选择货币名称", trigger: "blur" }],
  exchangeRate: [{ validator: checkFreeGoldRadio, trigger: "blur" }],
  startTime: [
    { required: true, message: "请选择开始时间", trigger: "blur" },
    { validator: checkStartTime, trigger: "blur" },
  ],
  endTime: [
    { required: true, message: "请选择结束时间", trigger: "blur" },
    { validator: checkEndTime, trigger: "blur" },
  ],
});

// 重置的按钮
const handledelete = function () {
  value1.value = {};
  startTime.value = "";
  endTime.value = "";
};
// 验证跳转输入框的数字是否合法
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)
    ) {
      getObj.value.pageNum = parseInt(getObj.value.pageNum);
      console.log("输入的数字合法");
      get();
    } else {
      //提示
      ElMessage({
        type: "error",
        message: "请检查输入内容",
      });
    }
  } else {
    //提示
    ElMessage({
      type: "error",
      message: "请检查输入内容",
    });
  }
};

// 删除=========================================================
// 删除按钮

// 删除按钮的气泡弹出框确认按钮
const delConfirm = async function (row) {
  try {
    // 发送POST请求
    const result = await API.post(
      "http://39.99.159.73:20090/rates/delete/ " + row.rateId,
      {}
    );
    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    get();
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};

//这是限制输入小数不超过七位的限制方法
function handleInput(value) {
  // 限制小数点后7位，这里使用正则表达式来实现
  rateAdd.value.exchangeRate = value
    .replace(/(\.\d{7})\d+/, "$1")
    .replace(/^(\d+)(\.\d{0,7})?$/, "$1$2");
}
</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="结束时间"
            :size="size"
            value-format="YYYY-MM-DD"
          />
          <!-- 按钮 -->
          <el-button
            class="button-item"
            type="primary"
            style="float: right"
            @click="search()"
            >查询</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
              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="currency" label="货币名称" :span="2" />
            <el-table-column prop="exchangeRate" label="汇率" :span="2">
              <template #default="scope">
                <p>
                  {{ scope.row.exchangeRate }}{{ scope.row.currency }} ：1新币
                </p>
              </template>
            </el-table-column>

            <el-table-column prop="createTime" label="添加时间" :span="3">
              <template #default="scope">
                <span>{{ formatDate(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="adminName" label="提交人" :span="1" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <span v-if="scope.row.status === 1">
                  <div class="status">
                    <span class="green-dot"></span>
                    <span>使用中</span>
                  </div>
                </span>
                <span v-if="scope.row.status === 0">
                  <div class="status">
                    <span class="red-dot"></span>
                    <span>未开始</span>
                  </div>
                </span>
                <span v-if="scope.row.status === 2">
                  <div class="status">
                    <span class="grey-dot"></span>
                    <span>已过期</span>
                  </div>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="startTime" label="持续时间" :span="10">
              <template #default="scope">
                <span>{{ formatDateTwe(scope.row.startTime) }}</span>
                <span>---</span>
                <span>{{ formatDateTwe(scope.row.endTime) }}</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
                >
                <el-popconfirm
                  title="确定将此条活动删除吗？"
                  @confirm="delConfirm"
                >
                  <template #reference>
                    <el-button type="primary" text> 删除 </el-button>
                  </template>
                  <template #actions="{ confirm, cancel }">
                    <el-button size="small" @click="cancel">取消</el-button>
                    <el-button
                      type="primary"
                      size="small"
                      @click="confirm(scope.row)"
                    >
                      确定
                    </el-button>
                  </template>
                </el-popconfirm>
              </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, 10, 20, 50, 100]"
                :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"
    :close-on-click-modal="false"
  >
    <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"
            @update:modelValue="handleInput"
            style="width: 120px"
          />
          <p class="unit">:1</p>
          <p>
            (提示：当前规则每 {{ rateAdd.exchangeRate }}
            {{ rateAdd.currency }}可兑换 1 新币)
          </p>
        </el-form-item>
        <el-form-item prop="adminId" label="提交人:">
          <el-input :value="adminData.name" disabled 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="throttledAdd">添加</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"
    :close-on-click-modal="false"
  >
    <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>
            (提示：当前规则每 {{ rateEdit.exchangeRate }}
            {{ rateEdit.currency }}可兑换 1 新币)
          </p>
        </el-form-item>
        <el-form-item label="提交人:">
          <el-input disabled :value="adminData.name" style="width: 240px" />
        </el-form-item>
        <el-form-item label="开始时间:">
          <el-date-picker
            v-model="rateEdit.startTime"
            type="date"
            placeholder="请选择时间"
            :default-value="new Date()"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间:">
          <el-date-picker
            v-model="rateEdit.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="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;
}

.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;
}
.status {
  display: flex;
}
</style>
