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

//这是获取用户信息的接口
const adminData = ref({});
const getAdminData = async function () {
  try {
    const result = await API.post(
      "/hwjb/admin/userinfo",
      {}
    );
    adminData.value = result;
    addConsume.value.adminId = adminData.value.adminId;
    addConsume.value.name = adminData.value.name;
    console.log("请求成功", result);
    console.log("用户信息", adminData.value);
  } catch (error) {
    console.log("请求失败", error);
  }
};
getAdminData();

// 这是添加消费信息的表单
const addConsume = ref({
  freeCoin: 0,
  rechargeCoin: 0,
  taskCoin: 0,
  updateType: "1",
});
// 这是添加消费信息的接口
const add = async function () {
  try {
    // 发送POST请求
    const result = await API.post(
      "/hwjb/consume/add",
      addConsume.value
    );
    if (result.code === 0) {
      ElMessage.error(result.msg);
      return;
    } else {
      ElMessage.success("添加成功");
    }
    //重置表单
    addConsume.value = {};
    addConsume.value.adminId = adminData.value.adminId;
    addConsume.value.adminName = adminData.value.adminName;
    addConsume.value.updateType = "1";
    addConsume.value.freeCoin = 0;
    addConsume.value.rechargeCoin = 0;
    addConsume.value.taskCoin = 0;
    console.log("请求成功", result);
    user.value = {};
  } catch (error) {
    console.log("请求失败", error);
    ElMessage.error("添加失败，请检查输入内容是否正确");

    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};
const addBefore = () => {
  Ref.value.validate(async (valid) => {
    if (valid) {
      ElMessageBox.confirm("确认添加？")
        .then(() => {
          addConsume.value.freeCoin = Number(-addConsume.value.freeCoin);
          addConsume.value.rechargeCoin = Number(
            -addConsume.value.rechargeCoin
          );
          addConsume.value.taskCoin = Number(-addConsume.value.taskCoin);
          add();
          console.log("添加成功");
          imageUrl.value = "";
          addConsume.value = {};
        })
        .catch(() => {
          console.log("取消添加");
        });
    } else {
      //提示
      ElMessage({
        type: "error",
        message: "请检查输入内容",
      });
    }
  });
};

// 表单验证
// 开始时间改变时，重新验证结束时间
const Ref = ref(null);
const checkEndTime = function (rule, value, callback) {
  if (value <= new Date()) {
    callback(new Error("付款时间不能小于当前时间"));
  }
};
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({
  jwcode: [{ required: true, message: "请输入精网号", trigger: "blur" }],
  productId: [{ required: true, message: "请选择消费商品", trigger: "blur" }],
  taskCoin: [{ required: true, message: "请输入任务金币", trigger: "blur" }],
  freeCoin: [{ required: true, message: "请输入免费金币", trigger: "blur" }],
  rechargeCoin: [
    { required: true, message: "请输入免费金币", trigger: "blur" },
  ],
  allGold: [{ validator: checkFreeGoldRadio, trigger: "blur" }],
});
//这是重置方法
const delteConsume = function () {
  addConsume.value = {};
  addConsume.value.adminId = adminData.value.adminId;
  addConsume.value.adminName = adminData.value.adminName;
  addConsume.value.updateType = "1";
  addConsume.value.freeCoin = 0;
  addConsume.value.rechargeCoin = 0;
  addConsume.value.taskCoin = 0;
};
// 查找客户信息的方法
const user = ref({
  firstRechargeTime: "",
});
const getUser = async function (jwcode) {
  try {
    // 发送POST请求
    const result = await API.post("/hwjb/recharge/user", {
      jwcode: jwcode,
    });

    console.log("请求成功", result);

    user.value = result.data;
    console.log("用户a信息aaaaaaaaaaa", user.value);
    user.value.A =
      Number(user.value.pendingRechargeTimes) +
      Number(user.value.pendingSpendTimes);
    console.log("用户信息", user.value);
    console.log("用户信息", user.value.firstRechargeDate);
    if (result.data.code === 0) {
      ElMessage.error(result.msg);
    } else {
      ElMessage.success(result.msg);
    }
  } catch (error) {
    console.log("请求失败", error);
    ElMessage.error("查询失败，请检查精网号是否正确");
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};

// 查询商品的接口
const goods = ref([]);
const getGoods = async function () {
  try {
    // 发送POST请求
    const result = await API.post("/hwjb/product", {});
    // 将响应结果存储到响应式数据中

    console.log("请求成功", result);
    // 存储全部数据
    goods.value = result.data;
    console.log("allData", allData.value);
    console.log("地区", area.value);
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};
getGoods();

//这是查询用户金币信息的接口
const userGold = ref({});
const getUserGold = async function (jwcode) {
  try {
    // 发送POST请求
    const result = await API.post("/hwjb/recharge/user", {
      jwcode: jwcode,
    });
    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    // 存储表格数据
    userGold.value = result.data;
    addConsume.value.username = result.data.name;
    addConsume.value.area = result.data.area;
    if (result.data.code === 0) {
      ElMessage.error("查询失败，请检查精网号是否正确");
    }
  } catch (error) {
    console.log("请求失败", error);
    ElMessage.error("无此精网号");
    addConsume.value.jwcode = "";
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};

function calculateCoins() {
  if (
    userGold.value.coreJb +
      userGold.value.free6 +
      userGold.value.free12 +
      userGold.value.buyJb <
    addConsume.value.allGold
  ) {
    addConsume.value.allGold = 0;
    addConsume.value.taskCoin = 0;
    addConsume.value.freeCoin = 0;
    addConsume.value.rechargeCoin = 0;
    ElMessage.error("金币不足，请充值");
    return;
  } else {
    // 保存原始的allGold值
    const originalAllGold = addConsume.value.allGold;

    // 确保todayTask和todayFree是有效的数字
    const todayTask =
      typeof userGold.value.coreJb === "number" ? userGold.value.coreJb : 0;
    const todayFree =
      typeof (userGold.value.free6 + userGold.value.free12) === "number"
        ? userGold.value.free6 + userGold.value.free12
        : 0;

    // 根据用户输入的消费金币总数和已有的金币数量进行计算
    addConsume.value.taskCoin = Math.min(originalAllGold, todayTask);
    let remainingGold = originalAllGold - addConsume.value.taskCoin;

    addConsume.value.freeCoin = Math.min(remainingGold, todayFree);
    remainingGold -= addConsume.value.freeCoin;

    addConsume.value.rechargeCoin = remainingGold; // 剩余的都算作永久金币

    // 恢复allGold的原始值
    addConsume.value.allGold = originalAllGold;

    // 确保taskCoin, freeCoin, rechargeCoin不是NaN，如果是，则设置为0
    if (isNaN(addConsume.value.taskCoin)) addConsume.value.taskCoin = 0;
    if (isNaN(addConsume.value.freeCoin)) addConsume.value.freeCoin = 0;
    if (isNaN(addConsume.value.rechargeCoin)) addConsume.value.rechargeCoin = 0;

    console.log("计算结果", addConsume.value);
  }
}
</script>

<template>
  <div style="margin-bottom: 20px; font-weight: bolder">新增消费</div>

  <el-form
    :model="addConsume"
    ref="Ref"
    :rules="rules"
    label-width="auto"
    style="max-width: 750px"
    class="form-style"
  >
    <el-form-item prop="jwcode" label="精网号">
      <el-input
        v-model="addConsume.jwcode"
        style="width: 220px"
        @change="getUserGold(addConsume.jwcode)"
      />
      <el-button
        type="primary"
        @click="getUser(addConsume.jwcode)"
        style="margin-left: 20px"
        >查询</el-button
      >
    </el-form-item>
    <el-form-item prop="productId" label="商品名称">
      <el-select
        v-model="addConsume.productId"
        placeholder="请选择"
        style="width: 300px"
      >
        <el-option
          v-for="item in goods"
          :key="item.value"
          :label="item.name"
          :value="item.productId"
        />
      </el-select>
    </el-form-item>
    <el-form-item prop="allGold" label="消费金币总数">
      <el-input
        v-model="addConsume.allGold"
        style="width: 100px"
        @change="calculateCoins()"
      />
    </el-form-item>
    <div style="display: flex; align-items: center">
      <el-form-item prop="rechargeCoin" label="永久金币" style="float: left">
        <el-input
          disabled
          v-model="addConsume.rechargeCoin"
          style="width: 100px; margin-left: -5px"
        />
        <p style="margin-right: 0px">个</p>
      </el-form-item>
      <el-form-item
        prop="freeCoin"
        label="免费金币"
        style="float: left; margin-left: -20px"
      >
        <el-input
          disabled
          v-model="addConsume.freeCoin"
          style="width: 100px; margin-left: -5px"
        />
        <p style="margin-right: 0px">个</p>
      </el-form-item>
      <el-form-item prop="taskCoin" label="任务金币" style="margin-left: -20px">
        <el-input
          disabled
          v-model="addConsume.taskCoin"
          style="width: 100px; margin-left: -5px"
        />
        <p style="margin-right: 20px">个</p>
      </el-form-item>
    </div>
    <el-form-item prop="remark" label="备注">
      <el-input
        v-model="addConsume.remark"
        style="width: 300px"
        :rows="2"
        maxlength="100"
        show-word-limit
        type="textarea"
      />
    </el-form-item>
    <el-form-item prop="commitName" label="提交人">
      <el-input
        style="width: 300px"
        :value="adminData.name"
        disabled
        placeholder="提交人姓名"
      />
    </el-form-item>
    <el-button @click="delteConsume" style="margin-left: 280px">重置</el-button>
    <el-button type="primary" @click="addBefore"> 提交 </el-button>
  </el-form>

  <!-- 客户信息栏 -->
  <el-card style="width: 850px; float: right" class="customer-info">
    <el-form
      :model="user"
      label-width="auto"
      style="max-width: 1200px"
      label-position="left"
    >
      <el-text size="large" style="margin-left: 20px">客户信息</el-text>
      <el-row style="margin-top: 20px">
        <el-col :span="10">
          <el-form-item label="姓名:">
            <p>{{ user.name }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="历史金币总数">
            <p>{{ user.totalRechargeGold }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="精网号">
            <p>{{ user.jwcode }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="当前金币总数" style="width: 500px">
            <span style="color: #2fa1ff; margin-right: 5px" v-if="user.buyJb">{{
              user.buyJb + user.free6 + user.free12 + user.coreJb
            }}</span>
            <span
              style="display: inline; white-space: nowrap; color: #b1b1b1"
              v-if="user.buyJb"
              >(永久金币:{{ user.buyJb }};免费金币:{{
                user.free6 + user.free12
              }};任务金币:{{ user.coreJb }})</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="首次充值日期">
            <p v-if="user.firstRechargeDate">
              {{ moment(user.firstRechargeDate).format("YYYY-MM-DD HH:mm:ss") }}
            </p>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="充值次数">
            <p style="color: #2fa1ff">{{ user.rechargeTimes }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="负责客服">
            <p>{{ adminData.name }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="消费次数">
            <p style="color: #2fa1ff">{{ user.spendTimes }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="所属门店">
            <p>{{ adminData.area }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="待审核">
            <p style="color: #2fa1ff">
              {{ user.A }}
            </p>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</template>

<style scoped>
p {
  margin: 0px;
}
.el-form-item {
  margin-left: 50px;
}

/* 上传图片的格式 */
.avatar-uploader .avatar {
  width: 50px;
  height: 50px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}
.form-style {
  margin-top: 50px;
  max-width: 50%;
  float: left;
}
.form-style2 {
  max-width: 60%;
}

p {
  font-size: 13px;
  transform: scale(1);
}
</style>
