<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import moment from "moment";
import request from "@/util/http";


/*
====================工具方法==============================
*/
// 精网号去空格
const trimJwCode = () => {
  if (addConsume.value.jwcode) {
    // 去除所有空格，并尝试转换为整数
    const trimmed = addConsume.value.jwcode.toString().replace(/\s/g, '');
    const numeric = Number(trimmed);

    // 如果转换为数字成功，保存为数字，否则提示错误
    if (!isNaN(numeric)) {
      addConsume.value.jwcode = numeric;
    } else {
      ElMessage.error("精网号格式不正确，请输入数字");
    }
  }
}

/*
====================数据=================================
*/
//这是获取当前登录的用户信息
const adminData = ref({});
// 通过精网号查询用户（客户）信息 表单
const user = ref({
  jwcode: null,
  name: "",
  market: "",
  historySumGold: null,
  historyPermanentGold: null,
  historyFreeGold: null,
  historyTaskGold: null,
  rechargeNum: null,
  consumeNum: null,
  firstRecharge: "",
  nowPermanentGold: null,
  nowFreeJune: null,
  nowTaskGold: null,
  nowFreeDecember: null,
  nowFreeGold: null,
  nowSumGold: null
})
// 这是添加消费信息的表单（金币）
const addConsume = ref({
  // jwcode 是数字
  jwcode: null, //精网号
  goodsName: "",// 商品名称
  sumGold: null, // 消费金币总数
  freeGold: null, // 免费金币
  permanentGold: null, // 永久金币
  taskGold: null, // 任务金币
  remark: "",//备注
  adminId: null,// 当前管理员id

});
// 表单验证
const Ref = ref(null);
// 表单验证规则
const rules = reactive({
  jwcode: [{required: true, message: "请输入精网号", trigger: "blur"}],
  goodsName: [{required: true, message: "请选择消费商品", trigger: "change"}], // 修改为 change
  sumGold: [
    {required: true, message: "消费金币总数不能为空", trigger: "blur"},

  ],

});
// 查询商品的表单
const goods = ref([]);


/*
====================方法=================================
*/
const getAdminData = async function () {
  try {//await 暂停函数执行，直到请求完成
    const result = await request({
      url: "/admin/userinfo",
      data: {},
    });
    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);
  }
};

// 消耗金币计算函数
function calculateCoins(sumGold) {
  const {nowFreeGold, nowPermanentGold, nowTaskGold} = user.value;
  if (user.value.jwcode) {
    if (sumGold <= 0) return {free: 0, permanent: 0, task: 0};

    let remaining = sumGold;
    let freeUsed = 0, permanentUsed = 0, taskUsed = 0;

    // 优先消耗免费金币
    if (nowFreeGold > 0) {
      freeUsed = Math.min(nowFreeGold, remaining);
      remaining -= freeUsed;
    }

    // 其次消耗永久金币
    if (remaining > 0 && nowPermanentGold > 0) {
      permanentUsed = Math.min(nowPermanentGold, remaining);
      remaining -= permanentUsed;
    }

    // 最后消耗任务金币
    if (remaining > 0 && nowTaskGold > 0) {
      taskUsed = remaining;
    }

    return {free: freeUsed, permanent: permanentUsed, task: taskUsed};

  }
  // 提示
  return {free: 0, permanent: 0, task: 0};

}

// 输入验证函数
function validateInput() {
  const sumGold = addConsume.value.sumGold;
  trimJwCode();
  trimJwCode();
  if (user.value.jwcode == null) {
    ElMessage.error("请先查询用户信息");
    addConsume.value.sumGold = null;
  }

  // 验证金币数值
  if (user.value.jwcode && sumGold <= 0) {
    ElMessage.error("消费金币总数必须大于0");
    // 将sunGold设置为null
    addConsume.value.sumGold = null;
    return false;
  }

  // 验证金币总和
  const totalAvailableGold = user.value.nowSumGold

  console.log("可用金币总和", totalAvailableGold);
  console.log("可用金币总和", sumGold);

  if (user.value.jwcode && sumGold > totalAvailableGold) {
    ElMessage.error("消费金币总数超过可用金币总和");
    // 将sunGold设置为null
    addConsume.value.sumGold = null;
    return false;
  }

  return true;
}

// 这是添加消费信息的接口
const add = async function () {
  try {
    // 验证输入数据 再验证一次
    if (!validateInput()) {
      return;
    }
    // 计算金币使用情况
    calculateCoins(addConsume.value.sumGold);

    console.log("addConsume.value", addConsume.value)
    // 发送POST请求
    const result = await request({
      // url: "/consume/add",
      url: "/consume/add",
      data: {
        ...addConsume.value,
        jwcode: addConsume.value.jwcode,
        // adminId: addConsume.value.adminId,
        // todo 一定要删除 换成上面的
        adminId: 1,


        sumGold: addConsume.value.sumGold * 100,
        freeGold: addConsume.value.freeGold * 100,
        taskGold: addConsume.value.taskGold * 100,
        permanentGold: addConsume.value.permanentGold * 100,
        goodsName: addConsume.value.goodsName,
        remark: addConsume.value.remark
      }

    });

    console.log("add请求", result);
    // 处理响应
    handleResponse(result);
    // 重置表单
    resetForm();

  } catch (error) {
    console.error("请求失败", error);
    ElMessage.error("添加失败，请检查网络连接或联系管理员");
  }
};

// 响应处理函数
function handleResponse(result) {
  console.log("响应结果", result)
  if (result.code === 200) {
    ElMessage.success("添加成功");
    console.log("请求成功", result);
  } else {
    ElMessage.error(result.msg || "添加失败，未知错误");
  }
}

// 重置表单函数
function resetForm() {
  // 清空表单数据
  addConsume.value = {
    jwcode: null,
    goodsName: "",
    sumGold: null,
    freeGold: null,
    permanentGold: null,
    taskGold: null,
    remark: "",
    adminId: adminData.value.adminId,
    adminName: adminData.value.adminName,
  };

  console.log("重置表单")

  user.value = {
    jwcode: null,
    name: "",
    market: "",
    historySumGold: null,
    historyPermanentGold: null,
    historyFreeGold: null,
    historyTaskGold: null,
    rechargeNum: null,
    consumeNum: null,
    firstRecharge: "",
    nowPermanentGold: null,
    nowFreeJune: null,
    nowTaskGold: null,
    nowFreeDecember: null,
    nowFreeGold: null,
    nowSumGold: null
  }
  // user.value.jwcode = null;
  // user.value = null;
}

// 添加前验证
const addBefore = () => {
  Ref.value.validate(async (valid) => {
    if (valid) {
      ElMessageBox.confirm("确认添加？")
          .then(() => {
            console.log("这里是jwcode", addConsume.value.jwcode)
            add();
            console.log("添加成功",);
            addConsume.value = {};
          })
          .catch(() => {
            console.log("取消添加");
          });
    } else {
      //提示
      ElMessage({
        type: "error",
        message: "请检查输入内容",
      });
    }
  });
};
// 查询客户信息（通过精网号）
const getUser = async function (jwcode) {
  trimJwCode();
  try {
    // 发送POST请求
    const result = await request({
      // url: "user/selectUser",
      url: "/user/selectUser", // todo 服务器改回无ip的
      data: {
        // 只需要传精网号
        jwcode: addConsume.value.jwcode,
      },
    });
    console.log("请求成功", result);

    if (result.code === 0) {
      ElMessage.error(result.msg);
    } else if (result.data === null) {
      ElMessage.error("用户不存在");
    } else {
      user.value = result.data;
      console.log("用户信息", user.value);
      ElMessage.success(result.msg);
    }
  } catch (error) {
    console.log("请求失败", error);
    ElMessage.error("查询失败，请检查精网号是否正确");
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};
// 获取商品信息(三楼接口)
const getGoods = async function () {
  try {
    // 发送POST请求
    const result = await request({
      // url: "/product", // todo 后续换3楼的 2025年6月27日10:38:26 解决
      url: "http://39.101.133.168:8828/live_mall/api/product/all",
    });
    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    goods.value = result.data.map(item => ({
      id: item.id,
      label: item.name,
      value: item.name
    }));


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

/*
====================监听=================================
*/

// 监听消费总金额变化，自动计算三类金币
watch(
    () => addConsume.value.sumGold,
    (newValue) => {
      if (newValue > 0) {
        const {free, permanent, task} = calculateCoins(newValue);
        addConsume.value.freeGold = free;
        addConsume.value.permanentGold = permanent;
        addConsume.value.taskGold = task;
      } else {
        addConsume.value.freeGold = null;
        addConsume.value.permanentGold = null;
        addConsume.value.taskGold = null;
      }
    }
);

/*
====================挂载=================================
*/
// 挂载
onMounted(async function () {
  await getAdminData();
  await getGoods();

});

</script>

<template>

  <div>


    <!-- 根据activeTab切换显示内容 -->
    <!-- 新增消耗的布局---------------------------------------------------------- -->
    <!-- <div v-if="activeTab === 'addConsume'"> -->
    <!-- <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"
    >
      <!--      todo 添加错误提示-->

      <el-form-item prop="jwcode" label="精网号">

        <el-input
            v-model="addConsume.jwcode"
            style="width: 220px"
        />
        <el-button
            type="primary"
            @click="getUser(addConsume.jwcode)"
            style="margin-left: 20px"
        >查询
        </el-button
        >
      </el-form-item>

      <div style="display: flex; align-items: center; gap: 20px;">
        <el-form-item prop="productName" label="商品名称" style="flex: 1; margin-right: 0px">

          <el-select
              v-model="addConsume.goodsName"
              placeholder="请选择商品"
              style="width: 450px"
          >
            <el-option
                v-for="item in goods"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>

        </el-form-item>


      </div>

      <el-form-item prop="allGold" label="消费金币总数">
        <el-input
            v-model="addConsume.sumGold"
            style="width: 100px"
            @input="validateInput()"
            @change="calculateCoins()"
        />
      </el-form-item>


      <!-- 三类金币自动计算（禁用状态，不可编辑） -->
      <div style="display: flex; align-items: center">
        <el-form-item prop="permanentGold" label="永久金币" style="float: left">
          <el-input
          v-model="addConsume.permanentGold"
              disabled
              style="width: 100px; margin-left: -5px"
          >
          <template #default="scope">{{ scope.row.permanentGold / 100 }}</template>
          </el-input>
          <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.freeGold"
              style="width: 100px; margin-left: -5px"
          />
          <p style="margin-right: 0px">个</p>
        </el-form-item>
        <el-form-item prop="taskGold" label="任务金币" style="margin-left: -20px">
          <el-input
              disabled
              v-model="addConsume.taskGold"
              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 type="success" @click="resetForm()" style="margin-left: 280px">重置</el-button>

      <el-button type="primary" @click="addBefore"> 提交</el-button>
    </el-form>


    <!-- 客户信息栏 -->
    <el-card v-if="user.jwcode" 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.historySumGold / 100 }}</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.nowSumGold !== undefined"
            >
              {{ user.nowSumGold / 100 }}</span
            >
              <span
                  style="display: inline; white-space: nowrap; color: #b1b1b1"
                  v-if="user.nowSumGold !== null "
              >(永久金币:{{ user.nowPermanentGold / 100 }};免费金币:{{
                  (user.nowFreeGold) / 100
                }};任务金币:{{ user.nowTaskGold / 100 }})</span>

            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="首次充值日期">
              <p v-if="user.firstRecharge">
                {{ moment(user.firstRecharge).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.rechargeNum }}</p>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="消费次数">
              <p style="color: #2fa1ff">{{ user.consumeNum }}</p>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="所属门店">
              <p>{{ user.market }}</p>
            </el-form-item>
          </el-col>
          <el-col :span="14">
          </el-col>
        </el-row>
      </el-form>
    </el-card>

  </div>


  <!-- 金币消耗明细的布局------------------------------------------------------- -->
  <!-- <div v-else-if="activeTab === 'detail'"> -->

  <!-- </div>
  </div> -->

</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>
