<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 (recharge.value.jwcode) {
    recharge.value.jwcode = recharge.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 voucher = ref('')
const Rate = ref()
const adminData = ref({})
const getAdminData = async function () {
  try {
    const result = await API({
      url: '/admin/userinfo',
      data: {}
    })
    adminData.value = result
    recharge.value.adminId = adminData.value.adminId
    recharge.value.market = adminData.value.market
    console.log('请求成功', result)
    console.log('用户信息', user.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 这是添加充值信息的表单
const recharge = ref({
  voucher: '',
  rechargeWay: '客服充值',
  freeGold: '',
  money: null,
  permanentGold: '',
  Rate: null,
  rechargeRatio: '',
  rateId: null
})
// 这是添加充值信息的接口
const add = async function () {
  try {

    const formattedRecharge = { ...recharge.value,
      // 添加固定的 adminId
      adminId: fixedAdminId 
     }
    if (formattedRecharge.payTime) {
      // 使用 moment.js 格式化 payTime
      formattedRecharge.payTime = moment(formattedRecharge.payTime).format('YYYY-MM-DD HH:mm:ss')
    }

    console.log('开始添加充值信息', recharge.value)
    // 发送POST请求
    const result = await API({
      url: 'http://192.168.8.247:8081/recharge/add',
      data: formattedRecharge
    })
    if (result.code === 0) {
      ElMessage.error(result.msg)
      return
    }
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 显示成功消息
    ElMessage.success('添加成功')
    // 重置表单
    recharge.value = {}
    recharge.value.adminId = adminData.value.adminId
    recharge.value.market = adminData.value.market
    recharge.value.voucher = ''
    recharge.value.rechargeWay = '客服充值'
    recharge.value.freeGold = ''
    recharge.value.money = null
    recharge.value.permanentGold = ''
    recharge.value.rateId = null
    imageUrl.value = ''
    Rate.value = null
    user.value = {}
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}

//添加充值信息前的按钮点击事件，进行表单验证和用户确认操作
const addBefore = () => {
  Ref.value.validate(async (valid) => {
    if (valid) {
      if (Rate.value == null || Rate.value == '' || Rate.value == undefined) {
        ElMessage({
          type: 'error',
          message: '请选择币种'
        })
        return
      }
      if(recharge.value.money == null || recharge.value.money == '' || recharge.value.money == undefined){
        ElMessage({
          type: 'error',
          message: '请输入充值金额'
        })
        return
      }
      // 根据选择的货币名称找到对应的 rateId
      const selectedRate = rateName.find(item => item.value === Rate.value)
      if (selectedRate) {
        recharge.value.rateId = selectedRate.rateId
      }
      ElMessageBox.confirm('确认添加？')
        .then(() => {
          add()
          console.log('添加成功')
        })
        .catch(() => {
          console.log('取消添加')
        })
    } else {
      //提示
      ElMessage({
        type: 'error',
        message: '请检查输入内容'
      })
    }
  })
}

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


const rules = reactive({
  jwcode: [{ required: true, message: '请输入精网号', trigger: 'blur' }],
  activity: [{ required: true, message: '请选择活动名称', trigger: 'blur' }],
  permanentGold: [{ required: true, message: '请输入永久金币数', trigger: 'blur' },
    {validator: (rule, value, callback) => {
        if (value >= 0) {
          callback()
        } else {
          callback(new Error('输入金额至少为0'))
        }}}],
  freeGold: [{required: true, message: '请输入免费金币数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        // 将值转换为数字(可行吗？？)
        // 好的不可行
        const numValue = Number(value);
        if (isNaN(numValue)) {
          callback(new Error('请输入有效的数字'));
        } else if (numValue >= 0) {
          callback();
        } else {
          callback(new Error('输入金额至少为 0'));
        }
      },
      trigger: 'blur'
    }
  ],
  money: [
    {
      required: true,
      message: '请选择货币名称',
      trigger: 'blur'
    }
  ],
  'recharge.money': [
    {
      required: true,
      message: '请输入充值金额',
      trigger: 'blur'
    }
    
  ],
  payModel: [{ required: true, message: '请选择付款方式', trigger: 'blur' }],
  payTime: [{ required: true, message: '请选择交款时间', trigger: 'blur' }]
})

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

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

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

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

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



//货币条目
const rateName = [
  {
    value: 'USD',
    label: 'USD',
    rateId: 1 
  },
  {
    value: 'HKD',
    label: 'HKD',
    rateId: 2
  },
  {
    value: 'THB',
    label: 'THB',
    rateId: 3
  },
  {
    value: 'VND',
    label: 'VND',
    rateId: 4
  },
  {
    value: 'CAD',
    label: 'CAD',
    rateId: 5
  },
  {
    value: 'MYR',
    label: 'MYR',
    rateId: 6
  },
  {
    value: 'KRW',
    label: 'KRW',
    rateId: 7
  },
  {
    value: 'JPY',
    label: 'JPY',
    rateId: 8
  },
  {
    value: 'CNY',
    label: 'CNY',
    rateId: 9
  }
]


// 上传图片成功的回调函数
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  console.log('图片上传成功', response, uploadFile)
  recharge.value.voucher = `http://39.101.133.168:8828/hljw/api/aws/upload`
  console.log('图片名称', recharge.value.voucher)
}

//充值方式条目
const payModel = [
  {
    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: { activity: row }
//       }
//     })
//     recharge.value.rechargeRatio = result.data[0].rechargeRatio
//     console.log('看看有了吗', recharge.value.rechargeRatio)
//   } catch (error) {
//     console.log('请求失败', error)
//   }
// }
function handleActivityChange(value) {
  // 在这里执行你的逻辑，例如获取选中的值
  console.log('选中的值：', value)
  getActivityById(value)
  console.log('看看', recharge.value)
}
// 监听 permanentGold 的变化
// const calculatedFree = computed(() => {
//   const result = recharge.value.permanentGold / recharge.value.rechargeRatio
//   if (isNaN(result) || result < 1 || recharge.value.rechargeRatio == 0) {
//     return 0
//   } else {
//     return Math.trunc(result)
//   }
// })
// watch(calculatedFree, (newVal) => {
//   recharge.value.freeGold = newVal
// })
// const calculatedRecharge = computed(() => {
//   return recharge.value.permanentGold * Rate.value
// })
// watch(calculatedRecharge, (newVal) => {
//   recharge.value.money = newVal
// })
//这是重置重置表单的方法
const deleteRecharge = function () {
  recharge.value = {
    // adminId: adminData.value.adminId,
    adminId: fixedAdminId,
    market: adminData.value.market,
    voucher: '',
    rechargeWay: '客服充值',
    freeGold: Number(),
    money: null,
    permanentGold: Number(),
    rateId: null
  }
  imageUrl.value = ''
  Rate.value = ''
}


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

<template>
  <div>

  <el-form
    :model="recharge"
    ref="Ref"
    :rules="rules"
    label-width="auto"
    style="max-width: 600px"
    class="add-form"
  >
    <el-form-item prop="jwcode" label="精网号">
      <el-input v-model="recharge.jwcode" style="width: 220px" />
      <el-button
        type="primary"
        @click="getUser(recharge.jwcode)"
        style="margin-left: 20px"
        
        >查询</el-button
      >
    </el-form-item>
    <el-form-item prop="activity" label="活动名称">
      <el-select
        v-model="recharge.activity"
        placeholder="请选择"
        style="width: 300px"
        @change="handleActivityChange"
      >
        <el-option
          v-for="(item, index) in activity"
          :key="index"
          :label="item"
          :value="item"
        />
      </el-select>
    </el-form-item>
    <el-form-item prop="permanentGold" label="永久金币">
      <el-input v-model="recharge.permanentGold" style="width: 100px" />
      <p style="margin-right: 20px">个</p>
      <p>免费金币</p>
      <el-input v-model="recharge.freeGold" style="width: 100px" />
      <p>个</p>
    </el-form-item>
    <el-form-item label="充值金额">
      <el-select
        prop="money"
        v-model="Rate"
        placeholder="货币名称"
        style="width: 95px; margin-right: 5px"
        aria-required="true"
      >
        <el-option
          v-for="item in rateName"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input prop="recharge.money" v-model="recharge.money" style="width: 200px" aria-required="true"/>
    </el-form-item>
    <el-form-item prop="payModel" label="收款方式">
      <el-select
        v-model="recharge.payModel"
        placeholder="请选择"
        style="width: 300px"
      >
        <el-option
          v-for="item in payModel"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item prop="payTime" label="交款时间">
      <!-- 修改 type 属性为 datetime 以支持时分秒选择 -->
      <el-date-picker
        v-model="recharge.payTime"
        type="datetime"
        style="width: 300px"
      />
    </el-form-item>
    <el-form-item
      prop="voucher"
      label="交款凭证"
      style="margin-bottom: 5px"
    >
      <el-upload
        action="http://39.101.133.168:8828/hljw/api/aws/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="recharge.remark"
        style="width: 300px"
        :rows="2"
        maxlength="100"
        show-word-limit
        type="textarea"
      />
    </el-form-item>
    <el-form-item prop="adminId" label="提交人">
      <el-input
        style="width: 300px"
        :value="adminData.adminId"
        disabled
        placeholder="提交人姓名"
      />
    </el-form-item>
    <el-button @click="deleteRecharge" style="margin-left: 280px" type="success"
      >重置</el-button
    >
    <el-button type="primary" @click="addBefore"> 提交 </el-button>
  </el-form>

  <!-- 客户信息栏 -->
  <el-card v-if="user.jwcode"
    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.historySumGold 是否为有效的数字 -->
            <p style="color: #2fa1ff; margin-right: 5px" v-if="!isNaN(Number(user.historySumGold))">
              {{ Number(user.historySumGold ) }}
            </p>
            <span
              style="display: inline; white-space: nowrap; color: #b1b1b1"
              v-if="user.historyPermanentGold !== undefined"
              >(永久金币:{{ user.historyPermanentGold }};免费金币:{{
                (user.historyFreeGold)
              }};任务金币:{{ user.historyTaskGold }})</span>
            <!-- 如果不是有效的数字，显示默认值 -->
            <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.nowPermanentGold !== undefined"
              >{{
                (user.nowSumGold)
              }}</span
            >
            <span
              style="display: inline; white-space: nowrap; color: #b1b1b1"
              v-if="user.nowPermanentGold !== undefined"
              >(永久金币:{{ user.nowPermanentGold}};免费金币:{{
                (user.nowFreeGold)
              }};任务金币:{{ user.nowTaskGold }})</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="首次充值日期">
            <p v-if="user.firstRecharge">
              {{ moment(user.firstRecharge).format('YYYY-MM-DD HH:mm:ss') }}
            </p>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="充值次数">
            <p style="color: #2fa1ff">{{ user.rechargeNum }}</p>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="10">
          <el-form-item label="负责客服">
            <p>{{ adminData.name }}</p>
          </el-form-item>
        </el-col> -->
        <el-col :span="10">
          <el-form-item label="消费次数">
            <p style="color: #2fa1ff">{{ user.consumeNum }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="所属门店">
            <p>{{ user.market }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <!-- <el-form-item label="待审核">
            <p style="color: #2fa1ff">
              {{ user.A }}
            </p>
          </el-form-item> -->
        </el-col>
      </el-row>
    </el-form>
  </el-card>

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