<script setup>
import { ref, onMounted, reactive, computed } from "vue";
import ElementPlus from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import moment from "moment";
import { ta } from "element-plus/es/locales.mjs";
import API from "../../api/index.js";
import * as XLSX from "xlsx";
// 变量
//这是获取用户信息的接口
const adminData = ref({});
const getAdminData = async function () {
  try {
    const result = await API.post(
      "http://54.251.137.151:10702/admin/userinfo",
      {}
    );
    adminData.value = result;
    console.log("请求成功", result);
    console.log("用户信息", adminData.value);
  } catch (error) {
    console.log("请求失败", error);
  }
};
// 充值明细表格
const tableData = ref([]);
// 计算用户各金币总数的不分页对象
const tableAllData = ref([]);
// 各金币总数
const rechargeCoin = ref(0);
const freeCoin = ref(0);
const taskCoin = ref(0);
// 搜索===========================================
//分页总条目
const total = ref(100);
// 搜索对象时间
const getTime = ref([]);
// 搜索detailY
const detailY = ref({});
// 不分页的搜索对象
const getAllObj = ref({});
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50,
});
//开启条件筛选导出excel
const getPutEX = ref(false);

// 支付方式选项
const num = [
  {
    value: "1",
    label: "增加",
  },
  {
    value: "2",
    label: "减少",
  },
];

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

// 方法
// 搜索===========================================================================
// 搜索方法
const get = async function (val) {
  try {
    // 地区赋值
    if (adminData.value.area === "泰国") {
      detailY.value.areas = ["泰国", "越南"];
    } else if (adminData.value.area !== "总部") {
      detailY.value.area = adminData.value.area;
    }
    // 搜索参数页码赋值
    if (typeof val === "number") {
      getObj.value.pageNum = val;
    }
    // 搜索参数时间赋值
    if (getTime.value != null) {
      if (getTime.value.startDate != "" && getTime.value.endDate != "") {
        detailY.value.startDate = getTime.value[0];
        detailY.value.endDate = getTime.value[1];
      }
    } else {
      detailY.value.startDate = "";
      detailY.value.endDate = "";
    }
    // 添加排序字段和排序方式到请求参数
    detailY.value.sortField = sortField.value;
    detailY.value.sortOrder = sortOrder.value;
    console.log("搜索参数", getObj.value);
    // 发送POST请求
    const result = await API.post("http://54.251.137.151:10702/detailY", {
      ...getObj.value,
      detailY: { ...detailY.value },
    });
    const result2 = await API.post("http://54.251.137.151:10702/detailY", {
      ...getAllObj.value,
      detailY: { ...detailY.value },
    });
    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    console.log("请求成功2", result2);
    // 存储表格数据
    tableData.value = result.data.list;
    console.log("tableData", tableData.value);
    tableAllData.value = result2.data;
    console.log("tableAllData", tableAllData.value);
    // 存储分页总数
    total.value = result.data.total;
    console.log("total", total.value);
    // 计算各金币总数并除以100
    // 下列各数除以100，并最多显示两位小数
    rechargeCoin.value = parseFloat((tableAllData.value.sumR / 100).toFixed(2));
    freeCoin.value = parseFloat((tableAllData.value.sumF / 100).toFixed(2));
    taskCoin.value = parseFloat((tableAllData.value.sumT / 100).toFixed(2));
    // for (let i = 0; i < tableAllData.value.length; i++) {
    //   rechargeCoin.value += tableAllData.value[i].rechargeCoin;
    //   freeCoin.value += tableAllData.value[i].freeCoin;
    //   taskCoin.value += tableAllData.value[i].taskCoin;
    // }
    console.log(
      "各金币总数",
      rechargeCoin.value,
      freeCoin.value,
      taskCoin.value
    );
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};
// 搜索
const search = function () {
  getObj.value.pageNum = 1;
  get();
};
// 重置
const reset = function () {
  detailY.value.jwcode = "";
  detailY.value.num = "";
  detailY.value.startDate = "";
  detailY.value.endDate = "";
  detailY.value.area = "";
  sortField.value = "";
  sortOrder.value = "";
  getTime.value = {};
  //重置平台信息
  detailY.value.consumePlatform = "";
};
// 今天
const getToday = function () {
  const today = new Date();
  const startDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate()
  );
  const endDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  );
  getTime.value = [startDate, endDate];
  console.log("getTime", getTime.value);
  get();
};
// 昨天
const getYesterday = function () {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  const startDate = new Date(
    yesterday.getFullYear(),
    yesterday.getMonth(),
    yesterday.getDate()
  );
  const endDate = new Date(
    yesterday.getFullYear(),
    yesterday.getMonth(),
    yesterday.getDate() + 1
  );
  getTime.value = [startDate, endDate];
  console.log("getTime", getTime.value);
  get();
};
// 近7天
const get7Days = function () {
  const today = new Date();
  const startDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() - 6
  );
  const endDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  );
  getTime.value = [startDate, endDate];
  console.log("getTime", getTime.value);
  get();
};

// 验证跳转输入框的数字是否合法
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: "请检查输入内容",
    });
  }
};

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

// 这是导出excel表格的方法
// 导出Excel的方法
// 定义字段映射
const json_fields = (row) => {
  return [
    row.jwcode, // 姓名
    row.area, // 精网号
    row.platform, // 所属地区
    row.count, // 平台信息
    row.updateType, // 更新数量
    row.rechargeCoin, // 免费金币
    row.freeCoin, // 永久金币
    row.taskCoin, // 任务金币
    row.createAdmin, // 提交人
    row.createTime,
    row.name,
    row.id,
  ];
};

// 定义元数据
const json_meta = [
  [
    {
      key: "charset",
      value: "utf-8",
    },
  ],
];
const headers = [
  "精网号",
  "地区",
  "平台信息",
  "数量",
  "更新类型",
  "永久金币",
  "免费金币",
  "任务金币",
  "提交人",
  "更新时间",
  "用户名",
  "id",
];
const exportExcel = () => {
  // 先将 json_fields 应用到数据上
  const data = excelInfo.value.map(json_fields);
  const ws = XLSX.utils.aoa_to_sheet(data);
  // 添加表头到工作表
  XLSX.utils.sheet_add_aoa(ws, [headers], { origin: "A1" });
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  XLSX.writeFile(wb, "客户金币明细.xlsx");
};
const today = new Date();
const startDate = new Date(
  today.getFullYear(),
  today.getMonth(),
  today.getDate()
);
const endDate = new Date(
  today.getFullYear(),
  today.getMonth(),
  today.getDate() + 1
);
const putExcel = ref({
  startDate: startDate,
  endDate: endDate,
});
const excelInfo = ref({});
const loading = ref(false);
const areyour = async function () {
  try {
    loading.value = true;
    const result = await API.post(
      "http://54.251.137.151:10702/detailY/searchAll",
      {
        ...putExcel.value,
      }
    );
    excelInfo.value = result.data;

    // 处理 excelInfo 中的数据
    if (Array.isArray(excelInfo.value)) {
      excelInfo.value.forEach((item) => {
        if (item.rechargeCoin) {
          item.rechargeCoin = item.rechargeCoin / 100;
        }
        if (item.freeCoin) {
          item.freeCoin = item.freeCoin / 100;
        }
        if (item.taskCoin) {
          item.taskCoin = item.taskCoin / 100;
        }
      });
    }

    areyouright.value = true;
    ElMessage({
      type: "success",
      message: "查询成功",
    });
    loading.value = false;
  } catch (error) {
    console.log("请求失败", error);
    loading.value = false;
  }
};

const areyouright = ref(false);

//选地区
const area = [
  {
    value: "马来西亚",
    label: "马来西亚",
  },
  {
    value: "新加坡",
    label: "新加坡",
  },
  {
    value: "香港",
    label: "香港",
  },
  {
    value: "泰国",
    label: "泰国",
  },
  {
    value: "加拿大",
    label: "加拿大",
  },
  {
    value: "越南HCM",
    label: "越南HCM",
  },
];
//选消费平台
const platform = [
  {
    value: "4",
    label: "金币系统",
  },

  {
    value: "1",
    label: "ERP系统",
  },
  {
    value: "2",
    label: "Homily Chart",
  },
  {
    value: "3",
    label: "Homily Link",
  },
  {
    value: "0",
    label: "初始化金币",
  },
];
const TimeGet = ref("1");

// 今天
const getT = function () {
  const today = new Date();
  const startDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate()
  );
  const endDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  );
  putExcel.value.startDate = startDate;
  putExcel.value.endDate = endDate;
  console.log("putExcel", putExcel.value);
};
//3天
const get3 = function () {
  const today = new Date();
  const startDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() - 2
  );
  const endDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  );
  putExcel.value.startDate = startDate;
  putExcel.value.endDate = endDate;
  console.log("putExcel", putExcel.value);
};
// 7天
const get7 = function () {
  const today = new Date();
  const startDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() - 6
  );
  const endDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  );
  putExcel.value.startDate = startDate;
  putExcel.value.endDate = endDate;
  console.log("putExcel", putExcel.value);
};
// 30天
const get30 = function () {
  const today = new Date();
  const startDate = new Date(
    today.getFullYear(),
    today.getMonth() - 1,
    today.getDate()
  );
  const endDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  );
  putExcel.value.startDate = startDate;
  putExcel.value.endDate = endDate;
  console.log("putExcel", putExcel.value);
};

// 新增排序字段和排序方式
const sortField = ref("");
const sortOrder = ref("");
// 处理排序事件
const handleSortChange = (column) => {
  console.log("排序字段：", column.prop);
  console.log("排序方式：", column.order);
  if (column.prop === "rechargeCoin") {
    sortField.value = "recharge_coin";
  } else if (column.prop === "taskCoin") {
    sortField.value = "task_coin";
  } else if (column.prop === "freeCoin") {
    sortField.value = "free_coin";
  } else if (column.prop === "createTime") {
    sortField.value = "create_time";
  } else if (column.prop === "gold") {
    sortField.value = "gold";
  }
  sortOrder.value = column.order === "ascending" ? "ASC" : "DESC";
  get();
};
</script>

<template>
  <el-dialog
    v-model="areyouright"
    title=""
    width="500"
    :close-on-click-modal="false"
  >
    <el-button type="success" @click="exportExcel()">导出</el-button>
  </el-dialog>

  <!-- 这是导出excel的弹窗 -->
  <el-dialog
    v-model="getPutEX"
    title="请选择导出条件"
    width="500"
    :close-on-click-modal="false"
  >
    <template #footer>
      <el-form
        v-loading="loading"
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="putExcel"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item prop="activityName" label="精网号:">
          <el-input
            v-model="putExcel.jwcode"
            placeholder="请输入精网号"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="所属地区："
          ><el-select
            v-model="putExcel.area"
            placeholder="请选择所属地区"
            style="width: 240px"
            clearable
          >
            <el-option
              v-for="item in area"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="更新时间：">
          <el-radio-group v-model="TimeGet">
            <el-radio value="1" @click="getT()">今天</el-radio>
            <el-radio value="3" @click="get3()">近三天</el-radio>
            <el-radio value="7" @click="get7()">近一周</el-radio>
            <el-radio value="30" @click="get30()">近一个月</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-button
          type="primary"
          size="small"
          style="margin-left: 10px"
          @click="areyour()"
          >确定</el-button
        >
      </el-form>
    </template>
  </el-dialog>

  <el-row>
    <el-col>
      <el-card style="margin-bottom: 20px">
        <el-row style="margin-bottom: 10px">
          <el-col :span="6">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">精网号：</el-text>
              <el-input
                v-model="detailY.jwcode"
                style="width: 240px"
                placeholder="请输入精网号"
                clearable
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">平台信息：</el-text>
              <el-select
                v-model="detailY.consumePlatform"
                placeholder="请选择平台信息"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in platform"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">更新类型：</el-text>
              <el-select
                v-model="detailY.num"
                placeholder="请选择更新类型"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in num"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">所属地区：</el-text>
              <el-select
                v-model="detailY.area"
                placeholder="请选择所属地区"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in area"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>

        <div class="head-card-element">
          <el-text class="mx-1" size="large">更新时间：</el-text>
          <el-date-picker
            v-model="getTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            style="margin-right: 700px"
          />
          <el-button type="success" @click="getPutEX = true"
            >导出Excel表格</el-button
          >
          <el-button @click="reset()">重置</el-button>
          <el-button type="primary" @click="search()">查询</el-button>
        </div>
      </el-card>
    </el-col>
  </el-row>
  <el-row>
    <el-col>
      <el-card>
        <!-- <div>
          现有金币：永久金币：{{ Math.abs(rechargeCoin) }}，免费金币：{{
            Math.abs(freeCoin)
          }}，任务金币：{{ Math.abs(taskCoin) }}
        </div> -->
        <!-- 设置表格容器的高度和滚动样式 -->
        <div style="height: 584px; overflow-y: auto">
          <el-table
            :data="tableData"
            style="width: 100%"
            @sort-change="handleSortChange"
            height="584px"
          >
            <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
              fixed="left"
              prop="username"
              label="姓名"
              width="150"
            />
            <el-table-column
              fixed="left"
              prop="jwcode"
              label="精网号"
              width="120"
            />
            <el-table-column prop="area" label="所属地区" width="120" />
            <el-table-column
              prop="consumePlatform"
              label="平台信息"
              width="140"
            >
              <template #default="scope">
                <!-- 使用非严格相等比较 -->
                <span v-if="scope.row.consumePlatform == 0">初始化金币</span>
                <span v-if="scope.row.consumePlatform == 1">ERP系统</span>
                <span v-if="scope.row.consumePlatform == 3">Homily Link</span>
                <span v-if="scope.row.consumePlatform == 2">Homily Chart</span>
                <span v-if="scope.row.consumePlatform == 4">金币系统</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="gold"
              label="更新数量"
              width="120"
              sortable="“custom”"
            >
              <template #default="scope">
                <span>{{ scope.row.gold / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="updateType" label="更新类型" width="110">
              <!-- 模板内容 -->
              <template #default="scope">
                <span v-if="scope.row.updateType == 1">
                  <span>消费</span>
                </span>
                <span v-if="scope.row.updateType == 0">
                  <span>充值</span>
                </span>
                <span v-if="scope.row.updateType == 2">
                  <span>退款</span>
                </span>
                <span v-if="scope.row.updateType == 3">
                  <span>其他</span>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="rechargeCoin"
              sortable="“custom”"
              label="永久金币"
              width="110"
            >
              <template #default="scope">
                <span>{{ scope.row.rechargeCoin / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="freeCoin"
              sortable="“custom”"
              label="免费金币"
              width="110"
            >
              <template #default="scope">
                <span>{{ scope.row.freeCoin / 100 }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="taskCoin"
              sortable="“custom”"
              label="任务金币"
              width="110"
            >
              <template #default="scope">
                <span>{{ scope.row.taskCoin / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="提交人" width="110" />
            <el-table-column
              prop="createTime"
              sortable="“custom”"
              label="更新时间"
              width="210"
              show-overflow-tooltip
            >
              <template #default="scope">
                <span>{{
                  moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss")
                }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px">
          <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>
</template>

<style scoped>
.pagination {
  display: flex;
}

.status {
  display: flex;
}

.head-card {
  display: flex;
}

/* .head-card-element {
  margin-right: 20px;
} */

/* .head-card-btn {
  margin-left: auto;
} */
</style>
