<script setup>
import { ref, onMounted, reactive, computed, watch, nextTick } 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 '@/util/http'
import moment from 'moment'
import { range, re } from 'mathjs'
import { utils, read } from 'xlsx'
import throttle from 'lodash/throttle'
// 精网号去空格
const trimJwCode = () => {
  if (addRecharge.value.jwcode) {
    addRecharge.value.jwcode = addRecharge.value.jwcode.replace(/\s/g, ''); 
  }
}
// 上传图片前的验证函数
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return (isJPG || isPNG) && isLt2M
}
// 这是添加上传图片的接口
const imageUrl = ref('')
const rechargeVoucher = ref('')
const Rate = ref()
const adminData = ref({})
const getAdminData = async function () {
  try {
    const result = await API({
      url: '/admin/userinfo',
      data: {}
    })
    adminData.value = result
    addRecharge.value.adminId = adminData.value.adminId
    addRecharge.value.area = adminData.value.area
    console.log('请求成功', result)
    console.log('用户信息', user.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 这是添加充值信息的表单
const addRecharge = ref({
  rechargeVoucher: '',
  rechargeWay: '客服充值',
  freeGold: '0',
  rechargeGold: 0,
  paidGold: 0,
  Rate: null,
  rechargeRatio: '0'
})
// 这是添加充值信息的接口
const add = async function () {
  try {
    console.log('开始添加充值信息', addRecharge.value)
    // 发送POST请求
    const result = await API({
      url: '/recharge/recharge/add',
      data: addRecharge.value
    })
    if (result.code === 0) {
      ElMessage.error(result.msg)
      return
    }
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 显示成功消息
    ElMessage.success('添加成功')
    // 重置表单
    addRecharge.value = {}
    addRecharge.value.adminId = adminData.value.adminId
    addRecharge.value.area = adminData.value.area
    addRecharge.value.rechargeVoucher = ''
    addRecharge.value.rechargeWay = '客服充值'
    addRecharge.value.freeGold = ''
    addRecharge.value.rechargeGold = 1
    addRecharge.value.paidGold = ''
    imageUrl.value = ''
    Rate.value = null
    user.value = {}
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
const addBefore = () => {
  Ref.value.validate(async (valid) => {
    if (valid) {
      ElMessageBox.confirm('确认添加？')
        .then(() => {
          add()
          console.log('添加成功')
        })
        .catch(() => {
          console.log('取消添加')
        })
    } else {
      //提示
      ElMessage({
        type: 'error',
        message: '请检查输入内容'
      })
    }
  })
}

// 表单验证
// 开始时间改变时，重新验证结束时间
const Ref = ref(null)

// 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' }],
  activityId: [{ required: true, message: '请选择活动名称', trigger: 'blur' }],
  paidGold: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value > 0) {
          callback()
        } else {
          callback(new Error('请输入大于0的金额'))
        }
      }
    }
  ],
  // 必须进行选择

  rechargeGold: [
    {
      required: true,
      message: '请选择充值方式',
      trigger: 'blur'
    }
  ],
  payWay: [{ required: true, message: '请选择付款方式', trigger: 'blur' }],
  rechargeTime: [{ required: true, message: '请选择交款时间', trigger: 'blur' }]
})

// 查找客户信息的方法
const user = ref({})
const getUser = async function (jwcode) {
  trimJwCode();
  try {

    // 发送POST请求
    const result = await API({
      url: '/recharge/user',
      data: {
        jwcode: addRecharge.value.jwcode,
        area: adminData.value.area
      }
    })
    console.log('请求成功', result)

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

// 这是查询活动的接口
const activity = ref([])
const getActivity = async function () {
  try {
    // 发送POST请求
    const result = await API({
      url: '/recharge/activity/select',
      data: {
        activity: { status: 1 }
      }
    })

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

// 这是查询货币的接口
const currency = ref([])
const getCurrency = async function () {
  try {
    // 发送POST请求
    const result = await API({
      url: '/rates/status',
      data: {}
    })

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

// 上传图片成功的回调函数
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  console.log('图片上传成功', response, uploadFile)
  addRecharge.value.rechargeVoucher = `http://54.251.137.151:10702/upload/${response.data}`
  console.log('图片名称', addRecharge.value.rechargeVoucher)
}

//充值方式条目
const options = [
  {
    value: '微信',
    label: '微信'
  },
  {
    value: '支付宝',
    label: '支付宝'
  },
  {
    value: '银联',
    label: '银联'
  },
  {
    value: '信用卡',
    label: '信用卡'
  },
  {
    value: '借记卡',
    label: '借记卡'
  },
  {
    value: '现金充值',
    label: '现金充值'
  }
]

//根据活动id获取汇率
const getActivityById = async function (row) {
  try {
    // 发送POST请求
    const result = await API({
      url: '/recharge/activity/select',
      data: {
        activity: { activityId: row }
      }
    })
    addRecharge.value.rechargeRatio = result.data[0].rechargeRatio
    console.log('看看有了吗', addRecharge.value.rechargeRatio)
  } catch (error) {
    console.log('请求失败', error)
  }
}
function handleActivityChange(value) {
  // 在这里执行你的逻辑，例如获取选中的值
  console.log('选中的值：', value)
  getActivityById(value)
  console.log('看看', addRecharge.value)
}
// 监听 paidGold 的变化
const calculatedFree = computed(() => {
  const result = addRecharge.value.paidGold / addRecharge.value.rechargeRatio
  if (isNaN(result) || result < 1 || addRecharge.value.rechargeRatio == 0) {
    return 0
  } else {
    return Math.trunc(result)
  }
})
watch(calculatedFree, (newVal) => {
  addRecharge.value.freeGold = newVal
})
const calculatedRecharge = computed(() => {
  return addRecharge.value.paidGold * Rate.value
})
watch(calculatedRecharge, (newVal) => {
  addRecharge.value.rechargeGold = newVal
})
//这是重置重置表单的方法
const deleteRecharge = function () {
  addRecharge.value = {
    adminId: adminData.value.adminId,
    area: adminData.value.area,
    rechargeVoucher: '',
    rechargeWay: '客服充值',
    freeGold: Number(0),
    rechargeGold: 0,
    paidGold: Number(0)
  }
  imageUrl.value = ''
  Rate.value = ''
}

// 批量充值
// jwcode列表
const jwcodeList = ref([])
let jwcodeSet
// 获取jwcode列表
const getJwcodeList = async function () {
  try {
    // 发送POST请求
    const result = await API({
      url: '/recharge/user/jwcode',
      data: {
        jwcode: jwcode,
        area: adminData.value.area
      }
    })

    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 存储表格数据
    jwcodeList.value = result.data
    console.log('精网号', jwcodeList.value)
    // 将数组转换为set
    jwcodeSet = new Set(jwcodeList.value)
    console.log('精网号set', jwcodeSet)
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}

// 校验精网号
// 精网号错误对象
const errorCount = ref(0)
// 校验规则
const validateInput = function (row, index) {
  console.log(jwcodeSet.has(row.jwcode), 'has')
  if (!jwcodeSet.has(row.jwcode) && row.jwcode != '' && row.jwcode != null) {
    row.isInputInvalid = true
    row.inputErrorMessage = '精网号不存在'
    errorCount.value++
    return
  } else {
    row.isInputInvalid = false
    row.inputErrorMessage = ''
    errorCount.value--
  }
}

// 批量充值弹窗
const batchRechargeVisible = ref(false)
const i = ref(1)
const delObj = ref({})
const batchDelObj = ref([])
const resetObj = ref({})
// 批量充值表格数据
const batchData = ref([
  {
    line: 1,
    showInput: true,
    isInputInvalid: false,
    inputErrorMessage: '',
    freeGold: '0',
    rechargeGold: '0',
    paidGold: '0'
  }
])

// 打开批量充值弹窗
const openBatchRechargeVisible = function () {
  batchRechargeVisible.value = true
}
// 关闭批量充值弹窗
const closeBatchRechargeVisible = function () {
  batchRechargeVisible.value = false
}
// 批量充值初始化
const batchInit = function () {
  openBatchRechargeVisible()
}

// 添加行数对象
const addLineObj = ref(0)
//添加一行
const addLine = function () {
  batchData.value.unshift({
    line: ++i.value,
    showInput: true,
    isInputInvalid: false,
    inputErrorMessage: '',
    freeGold: '0',
    rechargeGold: '0',
    paidGold: '0'
  })
}
const loading = ref(false)
// 添加多行
const addLines = async function () {
  try {
    loading.value = true // 操作开始前，将loading设为true，显示加载动画
    console.log(loading.value, 'loading.value')

    await new Promise((resolve) => setTimeout(resolve, 100)) // 人为创建一个小延迟

    for (let j = 0; j < addLineObj.value; j++) {
      batchData.value.unshift({
        line: ++i.value,
        showInput: true,
        isInputInvalid: false,
        inputErrorMessage: '',
        freeGold: '0',
        rechargeGold: '0',
        paidGold: '0'
      })
    }

    ElMessage.success('添加成功')
    console.log(batchData.value, 'batchData.value')
  } catch (error) {
    console.log('添加失败', error)
    ElMessage.error('添加失败')
  } finally {
    loading.value = false
    console.log(loading.value, 'loading.value')
  }
}
// 添加多行点击按钮
// const addLines = async function () {
//   try {

//     loading.value = true; // 操作开始前，将loading设为true，显示加载动画
//     console.log(loading.value, "loading.value")

//     await new Promise(resolve => setTimeout(resolve, 100)); // 人为创建一个小延迟

//     const newItems = Array.from({ length: addLineObj.value }, (_, index) => reactive({
//       line: ++i.value,
//       showInput: true,
//       isInputInvalid: false,
//       inputErrorMessage: '',
//       freeGold: "0",
//       rechargeGold: "0",
//       paidGold: "0",
//     }));
//     batchData.value = [...newItems, ...batchData.value];
//     ElMessage.success("添加成功");

//     console.log(batchData.value, "batchData.value");

//     loading.value = false;
//     console.log(loading.value, "loading.value")
//   } catch (error) {
//     console.log("添加失败", error);
//     ElMessage.error("添加失败");
//     // 如果出现异常，也要确保关闭加载动画
//     loading.value = false;
//   }
// };
// 使用 _.throttle 并设置 trailing 为 false 实现严格节流，只执行一次
const throttledAddLines = throttle(addLines, 500, { trailing: false })
// 导入excel按钮的ref
const uploadRefMap = ref({})
// 获取excel数据
const excelList = ref([])
// 动态设置upload Ref
const handleSetUploadRefMap = (el) => {
  if (el) {
    uploadRefMap.value[`Upload_Ref`] = el
  }
}
// 文件上传自定义
const httpExcelRequest = async (op) => {
  // 获取除文件之外的参数，具体根据实际业务需求来
  console.log(op.data)
  // 获取上传的excel  并解析数据
  let file = op.file
  let dataBinary = await readFile(file)
  let workBook = read(dataBinary, { type: 'binary', cellDates: true })
  let workSheet = workBook.Sheets[workBook.SheetNames[0]]
  const excelData = utils.sheet_to_json(workSheet, { header: 1 })
  excelList.value = excelData
  console.log(excelData)
}

const readFile = (file) => {
  return new Promise((resolve) => {
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = (ev) => {
      resolve(ev.target?.result)
    }
  })
}

//获取批量删除的数组
const handleSelectionChangebatch = function (val) {
  console.log('val===', val)
  batchDelObj.value = val
}
//批量删除
const batchDel = function () {
  ElMessageBox.confirm('确认批量删除吗？', '批量删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      console.log('batchDel===', batchDelObj.value)
      batchData.value = batchData.value.filter((itemA) => {
        return !batchDelObj.value.some((itemB) => itemB.line == itemA.line)
      })
      console.log('batchData===', batchData.value)
      ElMessage({
        type: 'success',
        message: '操作成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '操作撤销'
      })
    })
}
//单行删除初始化
const del = function (row) {
  console.log('row===', row)
  delObj.value.line = row.line
}
// 单行删除
const delConfirm = function () {
  batchData.value = batchData.value.filter(
    (item) => item.line != delObj.value.line
  )
  console.log('batchData===', batchData.value)
}
//单行重置初始化
const reset = function (row) {
  resetObj.value.line = row.line
}
// 单行重置
const resetConfirm = function () {
  for (let i = 0; i < batchData.value.length; i++) {
    if (batchData.value[i].line == resetObj.value.line) {
      batchData.value[i] = {}
      batchData.value[i].line = resetObj.value.line
      batchData.value[i].showInput = true
      break
    }
  }
}
//取消批量充值
const cancelBatch = function () {
  ElMessageBox.confirm('确认取消吗？此操作将不会保存任何数据。', '确认取消', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      batchData.value = [{ line: 1, showInput: true }]
      closeBatchRechargeVisible()
      ElMessage({
        type: 'success',
        message: '操作成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '操作撤销'
      })
    })
}
//监听改变活动时的操作
const changeActivity = function (row) {
  console.log('row===', row)
  let ratio = 0
  for (let i = 0; i < activity.value.length; i++) {
    if (activity.value[i].activityId == row.activityId) {
      ratio = activity.value[i].rechargeRatio
      break
    }
  }
  console.log('ratio===', ratio)
  if (row.paidGold == null || row.paidGold == '') {
    row.freeGold = 0
  } else {
    if (ratio == 0) {
      row.freeGold = 0
    } else {
      row.freeGold = Math.ceil(row.paidGold / ratio)
    }
  }
}
//监听改变永久金币时的操作
const changePaidGold = function (row) {
  console.log('row===', row)
  let ratio = 0
  if (row.activityId == null || row.activityId == '') {
    row.freeGold = 0
  } else {
    for (let i = 0; i < activity.value.length; i++) {
      if (activity.value[i].activityId == row.activityId) {
        ratio = activity.value[i].rechargeRatio
        break
      }
    }
    if (ratio == 0) {
      row.freeGold = 0
    } else {
      row.freeGold = Math.ceil(Number(row.paidGold) / ratio)
    }
  }
  let rate = row.rate
  if (rate == null || rate == '') {
    row.rechargeGold = 0
  } else {
    if (row.paidGold == null || row.paidGold == '') {
      row.rechargeGold = 0
    } else {
      row.rechargeGold = Math.ceil(Number(row.paidGold) * rate)
    }
  }
}
// 监听改变币种时的操作
const changeRate = function (row) {
  console.log('row===', row)
  let rate = row.rate
  if (rate == null || rate == '') {
    row.rechargeGold = 0
  } else {
    if (row.paidGold == null || row.paidGold == '') {
      row.rechargeGold = 0
    } else {
      row.rechargeGold = Math.ceil(Number(row.paidGold) * rate)
    }
  }
}
//监听改变凭证时的操作
const changeVoucher = function (row) {
  if (
    (imageUrl.value != '' && rechargeVoucher.value != '') ||
    (imageUrl.value != null && rechargeVoucher.value != null)
  ) {
    console.log('row===', row)
    row.imageUrl = imageUrl.value
    row.rechargeVoucher = rechargeVoucher.value
    console.log('row===', row)
    imageUrl.value = ''
    rechargeVoucher.value = ''
  }
}
// 上传图片成功的回调函数
const handleBatchAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  console.log('图片上传成功', response, uploadFile)
  rechargeVoucher.value = `http://54.251.137.151:10702/upload/${response.data}`
  console.log('图片名称', rechargeVoucher.value)
}
//批量充值确认按钮
const batchAdd = async function () {
  try {
    console.log('batchData===', batchData.value)
    let msg = ''
    if (batchData.value.length == 0) {
      ElMessage({
        type: 'error',
        message: '至少需要输入一条数据！'
      })
      return
    }
    if (errorCount.value > 0) {
      console.log('errorCount.value', errorCount.value)
      ElMessage({
        type: 'error',
        message: '请检查输入的精网号是否正确！'
      })
      return
    }
    for (let i = 0; i < batchData.value.length; i++) {
      batchData.value[i].adminId = adminData.value.adminId
      batchData.value[i].area = adminData.value.area
      batchData.value[i].rechargeWay = '客服充值'
      if (
        batchData.value[i].jwcode == '' ||
        batchData.value[i].jwcode == null
      ) {
        msg += `精网号不能为空！ <br/>`
      }
      if (
        batchData.value[i].activityId == '' ||
        batchData.value[i].activityId == null
      ) {
        msg += `活动不能为空！ <br/>`
      }
      if (
        batchData.value[i].paidGold == '' ||
        batchData.value[i].paidGold == null
      ) {
        msg += `永久金币不能为空！ <br/>`
      }
      if (
        batchData.value[i].freeGold == '' ||
        batchData.value[i].freeGold == null
      ) {
        msg += `免费金币不能为空！ <br/>`
      }
      if (
        batchData.value[i].rechargeGold == '' ||
        batchData.value[i].rechargeGold == null
      ) {
        msg += `充值金额不能为空！ <br/>`
      }
      if (
        batchData.value[i].payWay == '' ||
        batchData.value[i].payWay == null
      ) {
        msg += `收款方式不能为空！ <br/>`
      }
      if (
        batchData.value[i].rechargeTime == '' ||
        batchData.value[i].rechargeTime == null
      ) {
        msg += `交款时间不能为空！ <br/>`
      }
      if (msg != '' && msg != null) {
        console.log(batchData.value[i])
        ElMessage({
          dangerouslyUseHTMLString: true,
          type: 'error',
          message: msg
        })
        return
      }
    }

    console.log('batchData===', batchData.value)

    const result = await API({
      url: '/recharge/recharge/addmore',
      data: {
        ...batchData.value
      }
    })

    if (result.code === 0) {
      ElMessage.error('添加失败')
      return
    }

    ElMessage({
      type: 'success',
      message: '添加成功！'
    })

    closeBatchRechargeVisible()
  } catch (error) {
    console.log('error===', error)
    ElMessage.error('添加失败')
    return
  }
}
// 使用 _.throttle 并设置 trailing 为 false 实现严格节流，只执行一次
const throttledBatchAdd = throttle(batchAdd, 2000, { trailing: false })
// 批量设置的对象
const batchSettingObj = ref({
  rechargeGold: '0',
  paidGold: '0',
  freeGold: '0'
})
// 批量充值弹窗
const batchSettingVisible = ref(false)
// 打开批量充值弹窗
const openBatchSettingVisible = function () {
  batchSettingVisible.value = true
}
// 关闭批量充值弹窗
const closeBatchSettingVisible = function () {
  batchSettingVisible.value = false
}
// 批量设置初始化
const batchSettingInit = function () {
  openBatchSettingVisible()
}
// 上传图片成功的回调函数
const batchSettingHandleAvatarSuccess = (response, uploadFile) => {
  batchSettingObj.value.imageUrl = URL.createObjectURL(uploadFile.raw)
  console.log('图片上传成功', response, uploadFile)
  batchSettingObj.value.rechargeVoucher = `http://54.251.137.151:10702/upload/${response.data}`
  console.log('图片名称', batchSettingObj.value.rechargeVoucher)
}
// 批量设置取消按钮
const cancelBatchSetting = function () {
  batchSettingObj.value = {
    rechargeGold: '0',
    paidGold: '0',
    freeGold: '0'
  }
  closeBatchSettingVisible()
}
// 批量设置确认按钮
const batchSettingConfirm = function () {
  for (let i = 0; i < batchData.value.length; i++) {
    if (
      batchSettingObj.value.jwcode != '' &&
      batchSettingObj.value.jwcode != null
    ) {
      batchData.value[i].jwcode = batchSettingObj.value.jwcode
    }
    if (
      batchSettingObj.value.activityId != '' &&
      batchSettingObj.value.activityId != null
    ) {
      batchData.value[i].activityId = batchSettingObj.value.activityId
    }
    if (
      batchSettingObj.value.paidGold != '' &&
      batchSettingObj.value.paidGold != null
    ) {
      batchData.value[i].paidGold = batchSettingObj.value.paidGold
    }
    if (
      batchSettingObj.value.freeGold != '' &&
      batchSettingObj.value.freeGold != null
    ) {
      batchData.value[i].freeGold = batchSettingObj.value.freeGold
    }
    if (
      batchSettingObj.value.rate != '' &&
      batchSettingObj.value.rate != null
    ) {
      batchData.value[i].rate = batchSettingObj.value.rate
    }
    if (
      batchSettingObj.value.rechargeGold != '' &&
      batchSettingObj.value.rechargeGold != null
    ) {
      batchData.value[i].rechargeGold = batchSettingObj.value.rechargeGold
    }
    if (
      batchSettingObj.value.payWay != '' &&
      batchSettingObj.value.payWay != null
    ) {
      batchData.value[i].payWay = batchSettingObj.value.payWay
    }
    if (
      batchSettingObj.value.rechargeTime != '' &&
      batchSettingObj.value.rechargeTime != null
    ) {
      batchData.value[i].rechargeTime = batchSettingObj.value.rechargeTime
    }
    if (
      batchSettingObj.value.imageUrl != '' &&
      batchSettingObj.value.imageUrl != null
    ) {
      batchData.value[i].imageUrl = batchSettingObj.value.imageUrl
    }
    if (
      batchSettingObj.value.rechargeVoucher != '' &&
      batchSettingObj.value.rechargeVoucher != null
    ) {
      batchData.value[i].rechargeVoucher = batchSettingObj.value.rechargeVoucher
    }
    if (
      batchSettingObj.value.remark != '' &&
      batchSettingObj.value.remark != null
    ) {
      batchData.value[i].remark = batchSettingObj.value.remark
    }
  }
  batchSettingObj.value = {
    rechargeGold: '0',
    paidGold: '0',
    freeGold: '0'
  }
  closeBatchSettingVisible()
}

// 挂载
onMounted(async function () {
  await getAdminData()
  await getCurrency()
  await getActivity()
  await getJwcodeList()
})
</script>

<template>
  <div style="display: flex">
    <div style="margin-right: 20px">新增充值</div>
    <!-- <el-button type="primary" plain @click="batchInit()">批量充值</el-button> -->
  </div>

  <el-form
    :model="addRecharge"
    ref="Ref"
    :rules="rules"
    label-width="auto"
    style="max-width: 600px"
    class="add-form"
  >
    <el-form-item prop="jwcode" label="精网号">
      <el-input v-model="addRecharge.jwcode" style="width: 220px" />
      <el-button
        type="primary"
        @click="getUser(addRecharge.jwcode)"
        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"
        @change="handleActivityChange"
      >
        <el-option
          v-for="item in activity"
          :key="item.value"
          :label="item.activityName"
          :value="item.activityId"
        />
      </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" style="width: 100px" />
      <p>个</p>
    </el-form-item>
    <el-form-item prop="rechargeGold" label="充值金额">
      <el-select
        prop="rechargeGold"
        v-model="Rate"
        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 v-model="addRecharge.rechargeGold" 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="交款时间">
      <!-- 修改 type 属性为 datetime 以支持时分秒选择 -->
      <el-date-picker
        v-model="addRecharge.rechargeTime"
        type="datetime"
        style="width: 300px"
      />
    </el-form-item>
    <el-form-item
      prop="rechargeVoucher"
      label="交款凭证"
      style="margin-bottom: 5px"
    >
      <el-upload
        action="http://54.251.137.151:10702/upload"
        class="avatar-uploader"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        style="width: 100px; height: 115px"
      >
        <img
          v-if="imageUrl"
          :src="imageUrl"
          class="avatar"
          style="width: 100px; height: 115px"
        />
        <el-icon
          v-else
          class="avatar-uploader-icon"
          style="width: 100px; height: 100px"
        >
          <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="adminData.name"
        disabled
        placeholder="提交人姓名"
      />
    </el-form-item>
    <el-button @click="deleteRecharge" style="margin-left: 280px"
      >重置</el-button
    >
    <el-button type="primary" @click="addBefore"> 提交 </el-button>
  </el-form>

  <!-- 客户信息栏 -->
  <el-card
    style="width: 1200px; float: right"
    class="customer-info"
    width="3000px"
  >
    <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="历史金币总数">
            <!-- 检查 user.totalRechargeGold 是否为有效的数字 -->
            <p v-if="!isNaN(Number(user.totalRechargeGold))">
              {{ Number(user.totalRechargeGold / 100) }}
            </p>
            <!-- 如果不是有效的数字，显示默认值 -->
            <p v-else></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 !== undefined"
              >{{
                (user.buyJb + user.free6 + user.free12 + user.coreJb) / 100
              }}</span
            >
            <span
              style="display: inline; white-space: nowrap; color: #b1b1b1"
              v-if="user.buyJb !== undefined"
              >(永久金币:{{ user.buyJb / 100 }};免费金币:{{
                (user.free6 + user.free12) / 100
              }};任务金币:{{ user.coreJb / 100 }})</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>

  <el-dialog
    v-model="batchRechargeVisible"
    title="批量充值"
    width="1800px"
    style="height: 700px"
    :close-on-click-modal="false"
  >
    <el-row style="margin-bottom: 10px">
      <!-- <el-button type="primary" @click="addLine()" style="margin-right: 10px">新增一行</el-button> -->
      <div style="font-weight: bold; font-size: 20px">
        <span>添加</span>
        <el-input-number
          min="1"
          style="width: 100px"
          controls-position="right"
          v-model="addLineObj"
        ></el-input-number>
        <span>行</span>
        <el-button
          type="primary"
          @click="throttledAddLines"
          style="margin-right: 10px"
          >添加</el-button
        >
      </div>
      <el-button
        type="warning"
        @click="batchSettingInit()"
        style="margin-right: 10px"
        >批量设置</el-button
      >
      <!-- <el-upload :ref="(el) => handleSetUploadRefMap(el)" action="" :http-request="httpExcelRequest" :limit="1" :show-file-list="false"
        class="uploadExcelContent" :data={} style="margin-right: auto">
        <el-button type="success" >导入jwcode</el-button>
      </el-upload> -->
      <el-button
        type="danger"
        plain
        @click="batchDel()"
        style="margin-right: 10px; width: 130px"
        >批量删除</el-button
      >
    </el-row>
    <el-row>
      <el-table
        v-loading="loading"
        :data="batchData"
        border
        max-height="540px"
        style="height: 540px"
        @selection-change="handleSelectionChangebatch"
      >
        <el-table-column type="selection" width="50px" />
        <el-table-column property="index" label="序号" width="55px">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column property="jwcode" label="精网号" width="150px">
          <template #default="scope">
            <el-input
              v-if="scope.row.showInput"
              :class="{ 'is-invalid': scope.row.isInputInvalid }"
              @blur="validateInput(scope.row)"
              v-model="scope.row.jwcode"
              style="width: 110px"
            />
            <p v-if="scope.row.isInputInvalid" class="error-message">
              {{ scope.row.inputErrorMessage }}
            </p>
          </template>
          <!-- <template #default="scope">
            <el-select-v2 v-if="scope.row.showInput" filterable clearable v-model="scope.row.jwcode"
              placeholder="请选择精网号" style="widows: 110px;" :options="jwcodeList">
            <el-select-v2
              v-if="scope.row.showInput"
              filterable
              clearable
              v-model="scope.row.jwcode"
              placeholder="请选择精网号"
              style="widows: 110px"
              :options="jwcodeList"
            >
            </el-select-v2>
            <span v-else>{{ scope.row.jwcode }}</span>
          </template> -->
        </el-table-column>
        <el-table-column property="activityName" label="活动名称" width="150px">
          <template #default="scope">
            <el-select
              v-if="scope.row.showInput"
              filterable
              clearable
              v-model="scope.row.activityId"
              placeholder="请选择活动名称"
              @change="changeActivity(scope.row)"
            >
              <el-option
                v-for="item in activity"
                :key="item.activityId"
                :label="item.activityName"
                :value="item.activityId"
              >
              </el-option>
            </el-select>
            <span v-else>{{ scope.row.activityName }}</span>
          </template>
        </el-table-column>
        <el-table-column property="paidGold" label="永久金币" width="110px">
          <template #default="scope">
            <el-input
              v-if="scope.row.showInput"
              v-model="scope.row.paidGold"
              style="width: 70px"
              @change="changePaidGold(scope.row)"
            />
            <span v-else>{{ scope.row.paidGold }}</span>
          </template>
        </el-table-column>
        <el-table-column property="freeGold" label="免费金币" width="110px">
          <template #default="scope">
            <el-input
              v-if="scope.row.showInput"
              v-model="scope.row.freeGold"
              style="width: 70px"
            />
            <span v-else>{{ scope.row.freeGold }}</span>
          </template>
        </el-table-column>
        <el-table-column property="rate" label="货币名称">
          <template #default="scope">
            <el-select
              v-if="scope.row.showInput"
              filterable
              clearable
              v-model="scope.row.rate"
              placeholder="请选择币种"
              @change="changeRate(scope.row)"
            >
              <el-option
                v-for="item in currency"
                :key="item.exchangeRate"
                :label="item.currency"
                :value="item.exchangeRate"
              >
              </el-option>
            </el-select>
            <span v-else>{{ scope.row.rate }}</span>
          </template>
        </el-table-column>
        <el-table-column property="rechargeGold" label="充值金额" width="110px">
          <template #default="scope">
            <el-input v-model="scope.row.rechargeGold"></el-input>
          </template>
        </el-table-column>
        <el-table-column property="payWay" label="收款方式" width="130px">
          <template #default="scope">
            <el-select
              v-if="scope.row.showInput"
              filterable
              clearable
              v-model="scope.row.payWay"
              placeholder="请选择收款方式"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <span v-else>{{ scope.row.payWay }}</span>
          </template>
        </el-table-column>
        <el-table-column property="rechargeTime" label="交款时间" width="150px">
          <template #default="scope">
            <el-date-picker
              v-if="scope.row.showInput"
              type="date"
              v-model="scope.row.rechargeTime"
              style="width: 120px"
              placeholder="请选择交款时间"
            >
            </el-date-picker>
            <span v-else>{{
              moment(scope.row.rechargeTime).format('YYYY-MM-DD HH:mm:ss')
            }}</span>
          </template>
        </el-table-column>
        <el-table-column property="rechargeVoucher" label="充值凭证">
          <template #default="scope">
            <el-upload
              action="http://54.251.137.151:10702/upload"
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleBatchAvatarSuccess"
              v-if="scope.row.showInput"
              @change="changeVoucher(scope.row)"
            >
              <img
                v-if="scope.row.imageUrl"
                :src="scope.row.imageUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
            <span v-else>{{ scope.row.rechargeVoucher }}</span>
          </template>
        </el-table-column>
        <el-table-column property="remark" label="备注" width="130px">
          <template #default="scope">
            <el-input
              type="textarea"
              v-if="scope.row.showInput"
              v-model="scope.row.remark"
              style="max-width: 90px"
              :rows="1"
              cols="12"
            ></el-input>
            <span v-else>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column property="submitter" label="提交人">
          <el-input :value="adminData.name" disabled />
        </el-table-column>
        <el-table-column
          fixed="right"
          prop="operation"
          label="操作"
          width="150px"
        >
          <template #default="scope">
            <div style="display: flex">
              <el-popconfirm
                title="确定将此条信息删除吗？"
                @confirm="delConfirm"
              >
                <template #reference>
                  <el-button type="danger" text @click="del(scope.row)">
                    删除
                  </el-button>
                </template>
                <template #actions="{ confirm, cancel }">
                  <el-button size="small" @click="cancel">取消</el-button>
                  <el-button type="primary" size="small" @click="confirm">
                    确定
                  </el-button>
                </template>
              </el-popconfirm>
              <el-popconfirm
                title="确定将此条信息重置吗？"
                @confirm="resetConfirm"
              >
                <template #reference>
                  <el-button type="primary" text @click="reset(scope.row)">
                    重置
                  </el-button>
                </template>
                <template #actions="{ confirm, cancel }">
                  <el-button size="small" @click="cancel">取消</el-button>
                  <el-button type="primary" size="small" @click="confirm">
                    确定
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <div class="batch-btn">
        <el-button @click="cancelBatch()"> 取消 </el-button>
        <el-button type="primary" @click="throttledBatchAdd()">
          提交
        </el-button>
      </div>
    </el-row>
  </el-dialog>

  <el-dialog
    v-model="batchSettingVisible"
    title="批量设置"
    :close-on-click-modal="false"
    style="width: 550px"
  >
    <el-form label-position="left" label-width="auto">
      <el-form-item label="活动名称">
        <el-select
          v-model="batchSettingObj.activityId"
          placeholder="请选择活动名称"
          clearable
        >
          <el-option
            v-for="item in activity"
            :key="item.activityId"
            :label="item.activityName"
            :value="item.activityId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="永久金币">
        <el-input
          v-model="batchSettingObj.paidGold"
          placeholder="请输入永久金币"
        ></el-input>
      </el-form-item>
      <el-form-item label="免费金币">
        <el-input v-model="batchSettingObj.freeGold"></el-input>
      </el-form-item>
      <el-form-item label="充值金额">
        <div style="display: flex">
          <el-select
            v-model="batchSettingObj.rate"
            placeholder="请选择币种"
            style="width: 120px; margin-right: 10px"
            clearable
          >
            <el-option
              v-for="item in currency"
              :key="item.exchangeRate"
              :label="item.currency"
              :value="item.exchangeRate"
            ></el-option>
          </el-select>
          <el-input
            v-model="batchSettingObj.rechargeGold"
            placeholder="请输入充值金额"
          ></el-input>
        </div>
      </el-form-item>
      <el-form-item prop="payWay" label="收款方式">
        <el-select
          v-model="batchSettingObj.payWay"
          placeholder="请选择收款方式"
          clearable
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="rechargeTime" label="交款时间">
        <el-date-picker
          v-model="batchSettingObj.rechargeTime"
          type="date"
          placeholder="请选择交款时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item prop="rechargeVoucher" label="交款凭证">
        <el-upload
          action="http://54.251.137.151:10702/upload"
          class="avatar-uploader"
          :show-file-list="false"
          :on-success="batchSettingHandleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          style="width: 100px; height: 115px"
        >
          <img
            v-if="batchSettingObj.imageUrl"
            :src="batchSettingObj.imageUrl"
            class="avatar"
            style="width: 100px; height: 115px"
          />
          <el-icon
            v-else
            class="avatar-uploader-icon"
            style="width: 100px; height: 100px"
          >
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item prop="remark" label="备注">
        <el-input
          type="textarea"
          v-model="batchSettingObj.remark"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <el-button @click="cancelBatchSetting()" style="margin-left: 370px"
      >取消</el-button
    >
    <el-button type="primary" @click="batchSettingConfirm()"> 确认 </el-button>
  </el-dialog>
</template>

<style scoped>
p {
  margin: 0px;
}

.batch-btn {
  margin-top: 20px;
  margin-left: auto;
}

.el-form-item {
  margin-left: 50px;
}

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

<style>
.error-message {
  color: red;
  font-size: 8px;
}

.is-invalid .el-input__inner {
  border-color: red;
}

.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;
}

.add-form {
  margin-top: 50px;
  max-width: 50%;
  float: left;
}

.customer-info {
  max-width: 60%;
}
</style>
