<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";

// 这是添加充值信息的表单
const addRecharge = ref({
  rechargeVoucher: "",
  rechargeWay: "客服充值",
});
// 这是添加充值信息的接口
const add = async function () {
  try {
    // 发送POST请求
    const result = await axios.post(
      "http://192.168.8.93:10010/recharge/recharge/add",
      addRecharge.value
    );

    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    // 存储表格数据
    console.log("用户信息", user.value);
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};
const addBefore = () => {
  Ref.value.validate(async (valid) => {
    if (valid) {
      ElMessageBox.confirm("确认添加？")
        .then(() => {
          add();
          console.log("添加成功");
          imageUrl.value = "";
          addRecharge.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 rules = reactive({
  homilyId: [{ required: true, message: "请输入精网号", trigger: "blur" }],
  activityId: [{ required: true, message: "请选择活动名称", trigger: "blur" }],
  paidGold: [{ required: true, message: "请输入充值金币", trigger: "blur" }],
  rechargeGold: [
    { required: true, message: "请输入充值金额", trigger: "blur" },
  ],
  payWay: [{ required: true, message: "请选择付款方式", trigger: "blur" }],
  rechargeTime: [
    { required: true, message: "请选择交款时间", trigger: "blur" },
    { validator: checkEndTime, trigger: "blur" },
  ],
});

// 查找客户信息的方法
const user = ref({});
const getUser = async function (homilyId) {
  try {
    // 发送POST请求
    const result = await axios.post("http://192.168.8.93:10020/recharge/user", {
      homilyId: homilyId,
    });

    // 将响应结果存储到响应式数据中
    console.log("请求成功", result);
    // 存储表格数据
    user.value = result.data.data[0];
    console.log("用户信息", user.value);
  } catch (error) {
    console.log("请求失败", error);
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
};

// 这是查询活动的接口
const activity = ref([]);
const getActivity = async function () {
  try {
    // 发送POST请求
    const result = await axios.post(
      "http://192.168.8.93:10010/recharge/activity/select",
      {}
    );

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

// 这是查询货币的接口
const currency = ref([]);
const getCurrency = async function () {
  try {
    // 发送POST请求
    const result = await axios.post(
      "http://192.168.8.174:10010/rates/search",
      {}
    );

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

// 这是添加上传图片的接口
const imageUrl = ref("");

// 上传图片成功的回调函数
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  console.log("图片上传成功", response, uploadFile);
  addRecharge.value.rechargeVoucher =
    "http://192.168.8.93:10010/upload/" + response.data;
  console.log("图片名称", addRecharge.value.rechargeVoucher);
};
// 上传图片之前的校验函数
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

//充值方式条目
const options = [
  {
    value: "现金充值",
    label: "现金充值",
  },
  {
    value: "龙鳞卡",
    label: "龙鳞卡",
  },
  {
    value: "弘粉卡",
    label: "弘粉卡",
  },
];

const calculatedFreeGold = computed(() => {
  return addRecharge.value.paidGold * addRecharge.value.activityId;
});
const calculatedRechargeGold = computed(() => {
  addRecharge.value.paidGold * addRecharge.value.reteId;
});
watch(calculatedFreeGold, calculatedRechargeGold, (newVal) => {
  addRecharge.value.freeGold = newVal;
  addRecharge.value.rechargeGold = newVal;
});
</script>

<template>
  <div>新增充值</div>

  <el-form
    :model="addRecharge"
    ref="Ref"
    :rules="rules"
    label-width="auto"
    style="max-width: 600px"
  >
    <el-form-item prop="homilyId" label="精网号">
      <el-input v-model="addRecharge.homilyId" style="width: 220px" />
      <el-button
        type="primary"
        @click="getUser(addRecharge.homilyId)"
        style="margin-left: 20px"
        >查询</el-button
      >
    </el-form-item>
    <el-form-item prop="activityId" label="活动名称">
      <el-select
        v-model="addRecharge.activityId"
        placeholder="请选择"
        style="width: 300px"
      >
        <el-option
          v-for="item in activity"
          :key="item.value"
          :label="item.activityName"
          :value="item.rechargeRatio"
        />
      </el-select>
    </el-form-item>
    <el-form-item prop="paidGold" label="充值金币">
      <el-input v-model="addRecharge.paidGold" style="width: 100px" />
      <p style="margin-right: 20px">个</p>
      <p>免费金币</p>
      <el-input
        v-model="addRecharge.freeGold"
        disabled
        :value="addRecharge.paidGold * addRecharge.activityId"
        style="width: 100px"
      />
      <p>个</p>
    </el-form-item>
    <el-form-item label="充值金额">
      <el-select
        prop="rechargeGold"
        v-model="addRecharge.rateId"
        placeholder="货币名称"
        style="width: 95px; margin-right: 5px"
      >
        <el-option
          v-for="item in currency"
          :key="item.value"
          :label="item.currency"
          :value="item.exchangeRate"
        />
      </el-select>
      <el-input
        disabled
        :value="addRecharge.paidGold * addRecharge.rateId"
        style="width: 200px"
      />
    </el-form-item>
    <el-form-item prop="payWay" label="收款方式">
      <el-select
        v-model="addRecharge.payWay"
        placeholder="请选择"
        style="width: 300px"
      >
        <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="rechargeTime" label="交款时间">
      <el-date-picker
        v-model="addRecharge.rechargeTime"
        type="date"
        style="width: 300px"
      />
    </el-form-item>
    <el-form-item
      prop="rechargeVoucher"
      label="交款凭证"
      style="margin-bottom: 5px"
    >
      <el-upload
        class="avatar-uploader"
        action="http://192.168.8.93:10010/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <p style="margin-left: 10px; color: rgb(177, 176, 176)">
        仅支持.jpg .png格式，文件≤1MB
      </p>
    </el-form-item>
    <el-form-item prop="remark" label="备注">
      <el-input
        v-model="addRecharge.remark"
        style="width: 300px"
        :rows="2"
        maxlength="100"
        show-word-limit
        type="textarea"
      />
    </el-form-item>
    <el-form-item prop="submitter" label="提交人">
      <el-input
        style="width: 300px"
        value="张三"
        disabled
        placeholder="提交人姓名"
      />
    </el-form-item>
  </el-form>

  <el-button @click="closeAddActivityVisible" style="margin-left: 280px"
    >取消</el-button
  >
  <el-button type="primary" @click="addBefore"> 提交 </el-button>

  <!-- 客户信息栏 -->
  <el-card
    style="width: 700px; float: right; margin-top: -470px; margin-right: 100px"
  >
    <el-form
      :model="user"
      label-width="auto"
      style="max-width: 600px"
      label-position="left"
    >
      <el-text size="large" style="margin-left: 20px">客户信息</el-text>
      <el-row style="margin-top: 20px">
        <el-col :span="12">
          <el-form-item label="姓名:">
            <p>{{ user.name }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="历史金币总数"> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="精网号">
            <p>{{ user.homilyId }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="当前金币总数"> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="首次充值日期"> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="充值次数"> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责客服"> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消费次数"> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属门店"> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="待审核"> </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;
}
</style>
