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

const adminStore = useAdminStore();
const { adminData, menuTree } = storeToRefs(adminStore);
// 国际化
import { useI18n } from 'vue-i18n'
const { t } = useI18n()


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, // 0:全部退款, 1:部分退款
  permanentGold: '',
  freeGold: '',
  taskGold: '',
  sumGold: 0,
  remark: '',
  price: '',
  linkId: '',
  adminId: adminData.value.id,
  adminName: adminData.value.name,
  orderCode: '',
  type: 0
})

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

const getRefund = async function () {
  if (!addRefund.value.jwcode) {
    ElMessage.error(t('elmessage.checkJwcode'))
    return
  }
  addRefund.value.orderCode = ''
  addRefund.value.goodsName = ''
  addRefund.value.permanentGold = ''
  addRefund.value.freeGold = ''
  addRefund.value.taskGold = ''
   addRefund.value.price = ''
   addRefund.value.linkId = ''
  let type = null
  if (addRefund.value.refundType === '商品退款') {
    type = 1
  } else {
    type = 0
  }
  const params = {
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
    goldDetail: {
      jwcode: addRefund.value.jwcode,
      flag: 0,
      type: type,
      markets:[]
    }
  }
  try {
    const res = await API({
      url: '/goldDetail/getGoldDetail',
      data: {
        ...params
      }
    })
    tableData.value = res.data.list
    pagination.value.total = res.data.total
    if (Array.isArray(res.data.list) && res.data.list.length > 0) {
      orderCodes.value = res.data.list.map(item => ({
        label: item.orderCode,
        value: item.orderCode
      }))
      console.log("看看订单号们", orderCodes.value)
    } else {
      ElMessage.info(t('elmessage.noOrder'))
    }
  } catch (error) {
    console.log('goldDetail有错误', error)
    ElMessage.error(t('elmessage.requestFailed'))
    tableData.value = []
    pagination.value.total = 0
  }
}
// 这是添加退款信息的接口
const add = async function () {
  // 检查是否有添加权限
  if (!canAdd.value) {
    ElMessage.error(t('elmessage.noPermission'))
    return
  }
  try {
    if (addRefund.value.refundType === '商品退款') {
      addRefund.value.type = 1
    } else {
      addRefund.value.type = 0
    }
    // 对提交的金币数乘以 100
    const processedRefund = {
      ...addRefund.value,
      permanentGold: addRefund.value.permanentGold * 100,
      freeGold: addRefund.value.freeGold * 100,
      taskGold: addRefund.value.taskGold * 100,
      sumGold: addRefund.value.sumGold * 100,
      price: addRefund.value.price * 100,
      linkId: addRefund.value.linkId
    }
    console.log('提交的退款信息', processedRefund)
    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(t('elmessage.addSuccess'))
    // 重置表单
    cancel()
  } catch (error) {
    console.log('请求失败', error)
    ElMessage.error('请求失败，请重试')
    addDisabled.value = false
  }
}

// 提交禁止重复点击
const addDisabled = ref(false)

// 提交退款信息前的表单验证
const addBefore = () => {
  Ref.value.validate(async (valid) => {
    if (valid) {
      ElMessageBox.confirm(t('elmessage.confirmRefund'))
        .then(() => {
          add()
        })
        .catch(() => {
          console.log('取消退款')
        })
    } else {
      // 提示
      ElMessage({
        type: 'error',
        message: t('elmessage.checkInputContent')
      })
    }
  })
}

// 表单验证
const Ref = ref(null)
const validateJwCode = (rule, value, callback) => {
  if (!value) {
    callback(new Error(t('elmessage.noEmptyJwcode')));
    return;
  }
  if (/[^0-9]/.test(value)) {
    callback(new Error(t('elmessage.limitDigitJwcode')));
    return;
  }
  callback();
};
const rules = reactive({
  jwcode: [{ required: true, validator: validateJwCode, trigger: 'blur' }],
  refundType: [{ required: true, message: t('elmessage.checkRefundType'), trigger: 'blur' }],
  goodsName: [{ required: false, message: t('elmessage.checkRefundGoods'), trigger: 'blur' }],
  // 订单号
  orderCode: [{ required: true, message: t('elmessage.checkOrderNo'), trigger: 'blur' }],
  taskGold: [{ required: true, message: t('elmessage.checkTaskGold'), trigger: 'blur' }],
  freeGold: [{ required: true, message: t('elmessage.checkFreeGold'), trigger: 'blur' }],
  permanentGold: [
    { required: true, message: t('elmessage.checkPermanentGold'), trigger: 'blur' }
  ],
  sumGold: [
    { required: true, message: t('elmessage.checkPayModel'), trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (addRefund.value.refundModel === 1 && value === 0) {
          return Promise.reject(new Error(t('elmessage.noTotalGoldZero')))
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
})
// 查找客户信息的方法
const user = ref({
  firstRechargeTime: ''
})
const getUser = async function (jwcode) {
  trimJwCode();
  // 验证精网号
  if (!jwcode) {
    ElMessage.warning(t('elmessage.noEmptyJwcode'));
    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(t('elmessage.noUser'));
    } 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);

      tableData.value = []
      addRefund.value.refundType = ''
    }
  } catch (error) {
    console.log("请求失败", error);
    ElMessage.error(t('elmessage.jwcodeError'));
  }
}


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

// 存储所有商品信息和订单号下拉数据
const goodsName = ref([])
const orderCodes = ref([])

// 根据订单号自动带出商品名和金币信息
const handleOrderChange = (orderCode) => {
  addRefund.value.refundModel = 0
  addRefund.value.goodsName = ''
  addRefund.value.permanentGold = ''
  addRefund.value.freeGold = ''
  addRefund.value.taskGold = ''
  const order = tableData.value.find(item => item.orderCode === orderCode)
  if (order) {
    addRefund.value.goodsName = order.goodsName
    addRefund.value.price = Number(order.price || 0) / 100
    addRefund.value.linkId = order.linkId || ''
    if (addRefund.value.refundType === '金币退款') {
      selectedGoodsGold.value = {
        permanentGold: Number(order.permanentGold) || 0,
        freeGold: Number(order.freeGold) || 0,
        taskGold: Number(order.taskGold) || 0
      }
      console.log('看看金币退款参数', selectedGoodsGold.value)
    } else {
      selectedGoodsGold.value = {
        permanentGold: -Number(order.permanentGold) || 0,
        freeGold: -Number(order.freeGold) || 0,
        taskGold: -Number(order.taskGold) || 0
      }
      console.log('看看商品退款参数', selectedGoodsGold.value)
    }

    // 全部退款的填充
    if (addRefund.value.refundModel === 0) {
      addRefund.value.permanentGold = selectedGoodsGold.value.permanentGold.toString()
      addRefund.value.freeGold = selectedGoodsGold.value.freeGold.toString()
      addRefund.value.taskGold = selectedGoodsGold.value.taskGold.toString()
    }
  } else {
    addRefund.value.goodsName = ''
    addRefund.value.price = ''
    addRefund.value.linkId = ''
    selectedGoodsGold.value = {
      permanentGold: 0,
      freeGold: 0,
      taskGold: 0
    }
  }
}

// 存储选中商品的金币花费信息
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 = ''
  addRefund.value.price = ''
  addRefund.value.linkId = ''
}

// 处理退款方式切换
const handleRefundModelChange = () => {
  // 全部退款的自动填充  上面有
  if (addRefund.value.refundModel === 0) {
    addRefund.value.permanentGold = selectedGoodsGold.value.permanentGold.toString();
    addRefund.value.freeGold = selectedGoodsGold.value.freeGold.toString();
    addRefund.value.taskGold = selectedGoodsGold.value.taskGold.toString();
  }
  if (Ref.value) {
    Ref.value.clearValidate('sumGold')
  }
}

// 统一的输入处理函数
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(t('elmessage.limitBalance'));
  }

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

// 使用示例
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));
})
const canAdd = ref(findMenuById(menuTree.value,permissionMapping.add_gold_coin_refund))
watch(calculatedRechargeGoods, (newVal) => {
  addRefund.value.sumGold = newVal
})
const handlePageSizeChange = function (val) {
  pagination.value.pageSize = val
  getRefund()
}
const handleCurrentChange = function (val) {
  pagination.value.pageNum = val
  getRefund()
}
onMounted(() =>{
  console.log(adminData.value)
})
</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: 500px" class="add-form">
          <el-form-item prop="jwcode" :label="$t('common_add.jwcode')">
            <el-input v-model="addRefund.jwcode" style="width: 220px" />
            <el-button type="primary" @click="getUser(addRefund.jwcode)" style="margin-left: 20px">{{ $t('common.search') }}
            </el-button>
          </el-form-item>
          <el-form-item prop="refundType" :label="$t('common_add.refundType')">
            <el-select v-model="addRefund.refundType" :placeholder="$t('common_add.refundTypePlaceholder')" style="width: 220px"
              @change="getRefund(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="$t('common_add.orderNo')">
            <el-select v-model="addRefund.orderCode" :placeholder="$t('common_add.orderNoPlaceholder')" style="width: 220px;" clearable filterable
              @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="$t('common_add.goodsName')">
            <el-input v-model="addRefund.goodsName" style="width: 220px" disabled />
          </el-form-item>

          <el-form-item prop="refundModel" :label="$t('common_add.refundModel')">
            <el-radio-group v-model="addRefund.refundModel" @change="handleRefundModelChange">
              <el-radio :value="0">{{ $t('refund.refundMethods.allRefund') }}</el-radio>
              <el-radio :value="1">{{ $t('refund.refundMethods.partialRefund') }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item prop="permanentGold" :label="$t('common_add.permanentGold')">
            <el-input v-model="addRefund.permanentGold" style="width: 220px" :disabled="addRefund.refundModel === 0"
              @input="handlePermanentGoldInput($event)" type="number">
            </el-input>&nbsp;&nbsp;{{ $t('common.个') }}

            <template>

            </template>
          </el-form-item>

          <el-form-item prop="freeGold" :label="$t('common_add.freeGold')">
            <el-input v-model="addRefund.freeGold" style="float: left; width: 220px"
              :disabled="addRefund.refundModel === 0" @input="handleFreeGoldInput($event)" type="number" />
            &nbsp;&nbsp;{{ $t('common.个') }}
          </el-form-item>

          <div>
            <el-form-item prop="taskGold" :label="$t('common_add.taskGold')">
              <el-input v-model="addRefund.taskGold" style="float: left; width: 220px"
                :disabled="addRefund.refundModel === 0" @input="handleTaskGoldInput($event)" type="number" />
              &nbsp;&nbsp;{{ $t('common.个') }}
            </el-form-item>
          </div>
          <div>
            <el-form-item prop="sumGold" :label="$t('common_add.refundGoldCoin')">
              <el-input disabled v-model="addRefund.sumGold" style="width: 220px">
              </el-input>
            </el-form-item>
          </div>
          <div>
            <el-form-item prop="remark" :label="$t('common_add.remark')">
              <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">{{ $t('common.reset') }}</el-button>
          <el-button type="primary" :disabled="addDisabled" @click="addBefore" v-if="canAdd"> {{ $t('common.submit') }}</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" label-position="left">
            <span style="margin-left: 30%;font-size: larger;">{{ $t('common_add_user.customerInfo') }}</span>

            <el-row style="margin-top: 1vh;">
              <div class="line">
                <span style="width:5vw;">{{ $t('common_add_user.name') }}</span>
                <span style="width:10vw;">{{ user.name }}</span>
                <span style="width:10vw;">{{ $t('common_add_user.currentGoldCoinTotal') }}</span>
                <span style="color: #2fa1ff;width: 25vw;" v-if="user.nowSumGold !== undefined">{{
                  user.nowSumGold
                }}</span>
              </div>
            </el-row>
            <el-row style="height: 3vh;width: 100%;">
              <span style="height:3vh;color: #b1b1b1;font-size: small;margin-left:50%;"
                v-if="user.nowPermanentGold !== undefined">({{ $t('common_add_user.permanentGold') }}:{{
                  user.nowPermanentGold
                }};
                {{ $t('common_add_user.freeGold') }}:{{ user.nowFreeGold }};
                {{ $t('common_add_user.taskGold') }}:{{ user.nowTaskGold }})</span>
            </el-row>
            <el-row>
              <!-- 第二行：精网号 + 消费次数 -->
              <div class="line">
                <span style="width:5vw;">{{ $t('common_add_user.jwcode') }}</span>
                <span style="width: 10vw;">{{ user.jwcode }}</span>

                <span style="width:10vw;">{{ $t('common_add_user.consumptionTimes') }}</span>
                <span style="width: 10vw;color: #2fa1ff;">{{ user.consumeNum }}</span>
              </div>
            </el-row>
            <el-row>
              <span style="height:3vh;color: #b1b1b1;font-size: small;margin-left:50%;">({{ $t('common_add_user.onlyStatisticsDataAfter20250101') }}2025-01-01)</span>
            </el-row>

            <!-- 第四行：所属门店 -->
            <el-row>
              <div class="line">
                <span style="width:5vw;">{{ $t('common_add_user.store') }}</span>
                <span style="width: 10vw;">{{ user.market }}</span>
              </div>
            </el-row>
          </el-form>
        </el-card>
      </div>

      <div>
        <el-card class="card" v-if="tableData.length > 0">
          <el-table :data="tableData" style="height:43vh;width:50vw">
            <el-table-column type="index" :label="$t('refund.id')" width="80">
              <template #default="scope">
                <span>{{
                  scope.$index + 1 + (pagination.pageNum - 1) * pagination.pageSize
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="type" :label="$t('refund.type')" width="100">
              <template #default="{ row }">
                {{ row.type === 0 ? $t('refund.recharge') : $t('refund.consume') }}
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" :label="$t('refund.productName')" width="120" show-overflow-tooltip />
            <el-table-column prop="orderCode" :label="$t('refund.orderCode')" width="200px" show-overflow-tooltip />
            <el-table-column prop="permanentGold" :label="$t('refund.permanentGold')" width="120">
              <template #default="{ row }">
                {{ row.permanentGold }}
              </template>
            </el-table-column>
            <el-table-column prop="freeGold" :label="$t('refund.freeGold')" width="120">
              <template #default="{ row }">
                {{ row.freeGold }}
              </template>
            </el-table-column>
            <el-table-column prop="taskGold" :label="$t('refund.taskGold')" width="120">
              <template #default="{ row }">
                {{ row.taskGold }}
              </template>
            </el-table-column>
            <el-table-column prop="isRefund" :label="$t('refund.isRefund')" width="120">
              <template #default="{ row }">
                {{ row.isRefund === 1 ? $t('refund.no') : $t('refund.yes') }}
              </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: 35vw;
  display: flex;

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

.right-up {
  width: 52vw;
  height: 20vh;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 2vw;

  .customer-info {
    height: 21vh;
    padding-left: 5%;
    display: flex;
    align-items: center;

    .line {
      display: flex;
      height: 3vh;
    }
  }
}

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

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