<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import API from '@/util/http.js'
import moment from 'moment'
import {useAdminStore} from "@/store/index.js";
import {storeToRefs} from "pinia";
import {findMenuById, permissionMapping} from "@/utils/menuTreePermission.js"
import { ta } from 'element-plus/es/locales.mjs';

const adminStore = useAdminStore();
const {adminData, menuTree} = storeToRefs(adminStore);

const addRe = ref({
  typeR: '0'
})
const tableData = ref([])
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 精网号去空格
const trimJwCode = () => {
  if (addRefund.value.jwcode) {
    addRefund.value.jwcode = addRefund.value.jwcode.replace(/\s/g, '');
  }
}
// 这是添加退款信息的表单
const addRefund = ref({
  jwcode: '',
  goodsName: '',
  refundType: '',
  refundModel: 0,
  permanentGold: '',
  freeGold: '',
  taskGold: '',
  sumGold: 0,
  remark: '',
  adminId: null,
  orderCode: '',
  type: 0
})

// 取消按钮
const cancel = function () {
  addRefund.value = {
    jwcode: '',
    goodsName: '',
    refundType: '',
    refundModel: 0,
    permanentGold: '',
    freeGold: '',
    taskGold: '',
    sumGold: 0,
    remark: '',
    adminId: adminData.value.id,
    orderCode: '',
  }
  addRe.value.typeR = '0'
}

const show = function () {
  console.log('===================================', addRefund.value.refundType)
}
// 这是添加退款信息的接口
const add = async function () {
  try {

    // 更新 refundModel
    addRefund.value.refundModel = parseInt(addRe.value.typeR);
    if (addRefund.value.refundType === '商品退款') {
      addRefund.value.type = 1
    } else {
      addRefund.value.type = 0
    }
    // 对提交的金币数乘以 100
    const processedRefund = {
      ...addRefund.value,
      permanentGold: (Number(addRefund.value.permanentGold) || 0) * 100,
      freeGold: (Number(addRefund.value.freeGold) || 0) * 100,
      taskGold: (Number(addRefund.value.taskGold) || 0) * 100,
      sumGold: (Number(addRefund.value.sumGold) || 0) * 100
    }
    addDisabled.value = true
    // 发送POST请求
    const result = await API({
      url: '/refund/add',
      data: processedRefund
    })

    addDisabled.value = false
    if (result.code === 0) {
      ElMessage.error(result.msg)
      return
    }
    console.log('请求成功', result)
    ElMessage.success('添加成功')
    // 重置表单
    cancel()
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
//提交禁止重复点击
const addDisabled = ref(false)

// 提交退款信息前的表单验证
const addBefore = () => {
  Ref.value.validate(async (valid) => {
    if (valid) {

      // try {
      //   await getUser(addRefund.value.jwcode);
      //   if (!user.value.jwcode) {
      //     ElMessage.error('请先验证有效的精网号');
      //     return;
      //   }
      // } catch (error) {
      //   ElMessage.error('精网号验证失败');
      //   return;
      // }

      ElMessageBox.confirm('确认退款？')
        .then(() => {
          add()
          console.log('退款成功')
        })
        .catch(() => {
          console.log('取消退款')
        })
    } else {
      //提示
      ElMessage({
        type: 'error',
        message: '请检查输入内容'
      })
    }
  })
}

// 表单验证
// 开始时间改变时，重新验证结束时间
const Ref = ref(null)
const startChange = (val) => {
}
const validateJwCode = (rule, value, callback) => {
  if (!value) {
    callback(new Error('精网号不能为空'));
    return;
  }
  if (/[^0-9]/.test(value)) {
    callback(new Error('精网号只能包含数字'));
    return;
  }
  callback();
};
const rules = reactive({
  jwcode: [{ required: true, validator: validateJwCode, trigger: 'blur' }],
  refundType: [{ required: true, message: '请选择退款类型', trigger: 'blur' }],
  goodsName: [{ required: false, message: '请选择退款商品', trigger: 'blur' }],
  // 订单号
  orderCode: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  taskGold: [{ required: true, message: '请输入任务金币', trigger: 'blur' }],
  freeGold: [{ required: true, message: '请输入免费金币', trigger: 'blur' }],
  permanentGold: [
    { required: true, message: '请输入永久金币', trigger: 'blur' }
  ],
  sumGold: [
    { required: true, message: '请选择付款方式', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value === 0) {
          return Promise.reject(new Error('总金币不能为0'))
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
})


// 取消按钮
const cancelExceptJwcode = function () {
  addRefund.value = {
    jwcode: addRefund.value.jwcode, // 保留精网号
    goodsName: '',
    refundType: '',
    refundModel: 0,
    permanentGold: '',
    freeGold: '',
    taskGold: '',
    sumGold: 0,
    remark: '',
    adminId: adminData.value.id
  }
  addRe.value.typeR = '0'
}

// 查找客户信息的方法
const user = ref({
  firstRechargeTime: ''
})
const getUser = async function (jwcode) {
  trimJwCode();
  // cancelExceptJwcode();
  // 验证精网号
  if (!jwcode) {
    ElMessage.warning('精网号不能为空');
    return;
  }

  // 验证精网号是否为数字
  if (!/^\d{1,9}$/.test(jwcode)) {
    cancel()
    return;
  }
  try {
    // 发送POST请求
    const result = await API({
      url: '/user/selectUser',
      data: {
        jwcode: addRefund.value.jwcode
      }
    })
    console.log('请求成功', result)

    // 重置订单信息
    restGoods()
    //在此处错误逻辑的提示做了注释，在后续商品查询接口返回错误时，提示信息会显示在弹窗中
    if (result.code === 0) {
      ElMessage.error(result.msg);
    } else if (result.data === null) {
      ElMessage.error("用户不存在");
    } else {
      // 对传过来的金币数除以 100
      const processedData = {
        ...result.data,
        historySumGold: (Number(result.data.historySumGold) || 0),
        nowSumGold: (Number(result.data.nowSumGold) || 0),
        nowPermanentGold: (Number(result.data.nowPermanentGold) || 0),
        nowFreeGold: (Number(result.data.nowFreeGold) || 0),
        nowTaskGold: (Number(result.data.nowTaskGold) || 0)
      }
      user.value = processedData;
      console.log("用户信息", user.value);
      //ElMessage.success(result.msg);
    }
  } catch (error) {
    console.log("请求失败", error);
    ElMessage.error("精网号错误");

  }
}


// 退款类型，写死为商品退款
const refundType = ref([
  { value: '商品退款', label: '商品退款' },
  { value: '金币退款', label: '金币退款' }
]);

// 根据精网号查询商品
const goodsName = ref([]) // 存储所有商品信息
const orderCodes = ref([]) // 订单号下拉

const getGoods = async function (jwcode) {
  trimJwCode();
  if (!/^\d{1,9}$/.test(jwcode)) {
    ElMessage.warning('精网号必须为数字且不超过九位');
    return;
  }

  if (!addRefund.value.jwcode) {
    goodsName.value = []
    orderCodes.value = []
    return;
  }
  console.log('=======================', addRefund.value.refundType)
  if (addRefund.value.refundType === '商品退款') {
    addRefund.value.type = 1
  } else {
    addRefund.value.type = 0
  }
  try {
    const result = await API({
      url: '/refund/selectGoods',
      data: {
        jwcode: addRefund.value.jwcode,
        type: addRefund.value.type
      }
    })
    tableData.value = result.data
    if (result.data.length === 0) {
      ElMessage.error('该用户没有商品订单')
      return
    }

    if (Array.isArray(result.data)) {
      // 存储完整商品数据
      goodsName.value = result.data.map(item => ({
        orderCode: item.orderCode,
        goodsName: item.goodsName,
        permanentGold: Math.abs(Number((item.permanentGold) || 0) / 100),
        freeGold: Math.abs(Number((item.freeGold) || 0) / 100),
        taskGold: Math.abs(Number((item.taskGold) || 0) / 100),
      }))

      // 转换订单号数组 [{label, value}]
      orderCodes.value = result.data.map(item => ({
        label: item.orderCode,
        value: item.orderCode
      }))
    } else {
      ElMessage.error('商品数据格式错误，请联系管理员')
    }
  } catch (error) {
    console.log('请求失败', error)
    ElMessage.error('查询商品失败，请检查精网号是否正确')
    goodsName.value = []
    orderCodes.value = []
  }
}

// 根据订单号自动带出商品名
const handleOrderChange = (orderCode) => {
  const selected = goodsName.value.find(item => item.orderCode === orderCode)
  if (selected) {
    addRefund.value.goodsName = selected.goodsName
    // 退款方式是“全部退款”时，自动填充金币
    if (addRe.value.typeR === '0') {
      addRefund.value.permanentGold = selected.permanentGold
      addRefund.value.freeGold = selected.freeGold
      addRefund.value.taskGold = selected.taskGold
    }
    // 记录选中商品金币
    selectedGoodsGold.value = {
      permanentGold: selected.permanentGold,
      freeGold: selected.freeGold,
      taskGold: selected.taskGold
    }
  } else {
    restGoods()
  }
}


// 存储选中商品的金币花费信息
const selectedGoodsGold = ref({
  permanentGold: 0,
  freeGold: 0,
  taskGold: 0
})

// 重置订单信息
const restGoods = () => {
  addRefund.value.orderCode = ''
  addRefund.value.goodsName = ''
  addRefund.value.permanentGold = ''
  addRefund.value.freeGold = ''
  addRefund.value.taskGold = ''
}



// 处理退款方式切换，当部分退款切换全部退款时，退款金额应自动重新填充
const handleRefundModelChange = () => {
  if (addRe.value.typeR === '0') {
    // 全部退款时
    addRefund.value.permanentGold = selectedGoodsGold.value.permanentGold;
    addRefund.value.freeGold = selectedGoodsGold.value.freeGold;
    addRefund.value.taskGold = selectedGoodsGold.value.taskGold;
  }
}

const handleSelectionChange = (selectedOption) => {
  if (selectedOption) {
    // 更新商品名称
    addRefund.value.goodsName = selectedOption.value;

    // 更新金币字段
    addRefund.value.permanentGold = selectedOption.permanentGold || 0;
    addRefund.value.freeGold = selectedOption.freeGold || 0;
    addRefund.value.taskGold = selectedOption.taskGold || 0;

    // 记录选中商品的金币花费
    selectedGoodsGold.value.permanentGold = Number(selectedOption.permanentGold) || 0;
    selectedGoodsGold.value.freeGold = Number(selectedOption.freeGold) || 0;
    selectedGoodsGold.value.taskGold = Number(selectedOption.taskGold) || 0;
  } else {
    // 清空逻辑保持不变
  }
  console.log('选择的商品', selectedOption);
}
// 统一的输入处理函数
const handleGoldInput = (type, value) => {
  // 1. 过滤非法字符（只允许数字和小数点）
  let filtered = value.replace(/[^\d.]/g, '');

  // 2. 防止多个小数点
  const dotCount = (filtered.match(/\./g) || []).length;
  if (dotCount > 1) {
    // 保留第一个小数点，移除后续的小数点
    const parts = filtered.split('.');
    filtered = parts[0] + '.' + parts.slice(1).join('');
  }

  // 3. 限制小数点后两位
  if (filtered.includes('.')) {
    const [integer, decimal] = filtered.split('.');
    if (decimal.length > 2) {
      filtered = `${integer}.${decimal.slice(0, 2)}`;
    }
  }

  // 4. 检查是否以小数点开头，如果是，在前面添加0
  if (filtered.startsWith('.')) {
    filtered = '0' + filtered;
  }

  // 5. 更新值
  addRefund.value[type] = filtered;

  // 6. 验证逻辑（这里直接应用修正后的值）
  const maxValue = selectedGoodsGold.value[type];
  const inputValue = Number(filtered || 0);

  if (isNaN(inputValue)) {
    return;
  }

  if (inputValue > maxValue) {
    // 修正为最大值并设置回输入框
    const correctedValue = maxValue.toFixed(2);
    addRefund.value[type] = correctedValue;
    ElMessage.warning('所填金额大于该类金币余额');
  }

  if (inputValue < 0) {
    // 修正为0并设置回输入框
    addRefund.value[type] = '0';
    ElMessage.warning('不能输入负数');
  }
}

// 使用示例
const handlePermanentGoldInput = (value) => handleGoldInput('permanentGold', value);
const handleFreeGoldInput = (value) => handleGoldInput('freeGold', value);
const handleTaskGoldInput = (value) => handleGoldInput('taskGold', value);

// 计算总金币
const calculatedRechargeGoods = computed(() => {
  const permanentGold = addRefund.value.permanentGold === '' ? 0 : +addRefund.value.permanentGold;
  const freeGold = addRefund.value.freeGold === '' ? 0 : +addRefund.value.freeGold;
  const taskGold = addRefund.value.taskGold === '' ? 0 : +addRefund.value.taskGold;
  return Number((permanentGold + freeGold + taskGold).toFixed(2));
})

watch(calculatedRechargeGoods, (newVal) => {
  addRefund.value.sumGold = newVal
  console.log('计算的总金币', newVal)
})
const handlePageSizeChange = function (val) {
  pagination.value.pageSize = val
}
const handleCurrentChange = function (val) {
  pagination.value.pageNum = val
}

</script>

<template>
  <div class="father">
    <div class="userAndForm">
      <div class="left">
        <el-form :model="addRefund" ref="Ref" :rules="rules" label-width="auto" label-position="right"
          style="min-width: 420px" class="add-form">
          <el-form-item prop="jwcode" label="精网号">
            <el-input v-model="addRefund.jwcode" style="width: 220px" />
            <el-button type="primary" @click="getUser(addRefund.jwcode)" style="margin-left: 20px">查询
            </el-button>
          </el-form-item>
          <el-form-item prop="refundType" label="退款类型" @change="show">
            <el-select v-model="addRefund.refundType" placeholder="请选择" style="width: 220px"
              @change="getGoods(addRefund.jwcode)">
              <el-option v-for="item in refundType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="orderCode" label="订单号">
            <el-select v-model="addRefund.orderCode" placeholder="请选择订单号" style="width: 220px;" clearable filterable
              :filter-method="handleFilter" @change="handleOrderChange">
              <el-option v-for="(item, index) in orderCodes" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item prop="goodsName" label="商品名">
            <el-input v-model="addRefund.goodsName" style="width: 220px" disabled />
          </el-form-item>


          <el-form-item prop="refundModel" label="退款方式:">
            <el-radio-group v-model="addRe.typeR" @change="handleRefundModelChange">
              <el-radio value="0">全部退款</el-radio>
              <el-radio value="1">部分退款</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item prop="permanentGold" label="永久金币">
            <el-input v-model="addRefund.permanentGold" style="width: 220px"
              :disabled="addRe.typeR === '0' ? true : false" @input="handlePermanentGoldInput($event)" type="number">
            </el-input>&nbsp;&nbsp;个
          </el-form-item>


          <el-form-item prop="freeGold" label="免费金币">
            <el-input v-model="addRefund.freeGold" style="float: left; width: 220px"
              :disabled="addRe.typeR === '0' ? true : false" @input="handleFreeGoldInput($event)" type="number" />
            &nbsp;&nbsp;个
          </el-form-item>

          <div>
            <el-form-item prop="taskGold" label="任务金币">
              <el-input v-model="addRefund.taskGold" style="float: left; width: 220px"
                :disabled="addRe.typeR === '0' ? true : false" @input="handleTaskGoldInput($event)" type="number" />
              &nbsp;&nbsp;个
            </el-form-item>
          </div>
          <div>
            <el-form-item prop="sumGold" label="退款金币总数">
              <el-input disabled v-model="addRefund.sumGold" style="width: 220px">
              </el-input>
            </el-form-item>
          </div>
          <div>

            <el-form-item prop="remark" label="备注">
              <el-input v-model="addRefund.remark" style="width: 220px" :rows="3" maxlength="100" show-word-limit
                type="textarea" />
            </el-form-item>
          </div>

          <el-button type="success" @click="cancel()" style="margin-left: 200px">重置</el-button>
          <el-button type="primary" :disabled="addDisabled" @click="addBefore"> 提交</el-button>
        </el-form>
      </div>
    </div>

    <div class="right">
      <div class="right-up">
        <!-- 客户信息栏 -->
        <el-card v-if="user.jwcode" class="customer-info">
          <el-form :model="user" label-width="auto" style="max-width: 1000px" label-position="left">
            <el-text size="large" style="padding:30%; ">客户信息</el-text>

            <!-- 第一行：姓名 + 历史金币 -->
            <el-row style="margin-top: 10px;height:5vh;">
              <el-col :span="9">
                <el-form-item label="姓名">
                  <p>{{ user.name }}</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
                  }}</span>
                </el-form-item>
                <!-- 金币详情独立显示 -->
                <el-form-item style="margin-top: -23px"> <!-- 负边距减少间距 -->
                  <span style="color: #b1b1b1; margin-left: 0px" v-if="user.nowPermanentGold !== undefined">(永久金币:{{
                    user.nowPermanentGold
                  }};
                    免费金币:{{ user.nowFreeGold }};
                    任务金币:{{ user.nowTaskGold }})</span>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行：精网号 + 当前金币（独立行） -->
            <el-row style="margin-top: 1px;height:5vh;">
              <el-col :span="9">
                <el-form-item label="精网号">
                  <p>{{ user.jwcode }}</p>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="消费次数">
                  <p style="color: #2fa1ff">{{ user.consumeNum }} </p>
                </el-form-item>
                <el-form-item style="margin-top: -23px"> <!-- 负边距减少间距 -->
                  <p style="font-size: small; color: #b1b1b1">(仅统计2025-01-01后的数据)</p>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第四行：消费次数 + 所属门店 -->
            <el-row style="margin-top: 1px;height:3vh;">
              <el-col :span="9">
                <el-form-item label="所属门店">
                  <p>{{ user.market }}</p>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>

      <div class="right-down">
        <el-card class="card" v-if="tableData.length > 0">
          <el-table :data="tableData" style="height:43vh;width:50vw">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="type" label="类型" width="120" >
              <template #default="{ row }">
                {{ row.orderCode.slice(3, 5) === 'CZ' ? '充值' : '消费' }}
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="商品名称" width="120" />
            <el-table-column prop="orderCode" label="订单号" width="240px" show-overflow-tooltip />
            <el-table-column prop="permanentGold" label="永久金币" width="120">
              <template #default="{ row }">
                {{ row.permanentGold / 100 }}
              </template>
            </el-table-column>
            <el-table-column prop="freeGold" label="免费金币" width="120">
              <template #default="{ row }">
                {{ (row.freeGold) / 100 }}
              </template>
            </el-table-column>
            <el-table-column prop="taskGold" label="任务金币" width="120">
              <template #default="{ row }">
                {{ row.taskGold / 100 }}
              </template>
            </el-table-column>
            <el-table-column prop="isRefund" label="订单状态" width="120" >
              <template #default="{ row }">
                {{ row.isRefund === '1' ? '已退款' : '未处理' }}
              </template>
            </el-table-column>
          </el-table>
          <el-pagination class="pagination" v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total" @size-change="handlePageSizeChange"
            @current-change="handleCurrentChange"></el-pagination>
        </el-card>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
p {
  margin: 0px;
}

.father {
  width: 75vw;
  height: 70vh;
  display: flex;
}

.userAndForm {
  width: 25vw;
  height: 100%;
  display: flex;
}

.left {
  width: 35%;
  display: flex;

  .add-form {
    width: 100%;
    margin-top: 50px;
  }
}

.right-up {
  width: 35vw;
  height: 20vh;
  display: flex;

  .customer-info {
    width: 90%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 10px;
    margin-left: 5vw;
  }
}

.card {
  width: 50vw;
  height: 50vh;
  margin-left: 5vw;
  margin-top: 1vh;
}

.pagination {
  display: flex;
  margin-top: 0.5vh;
}
</style>
