
<script setup>
import { onMounted, reactive } from 'vue'
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessageBox } from 'element-plus'
import API from '@/util/http'
import moment from 'moment'
// import _ from 'lodash'

const addRe = ref({
  typeR: '0'
})



//这是获取用户信息的接口
const adminData = ref({})
const getAdminData = async function () {
  try {
    const result = await API({ url: '/admin/userinfo', data: {} })
    adminData.value = result
    addRefund.value.adminId = adminData.value.adminId
    console.log('请求成功', result)
    console.log('用户信息', user.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 精网号去空格
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
})

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


// 这是添加退款信息的接口
const add = async function () {
  try {

    // 更新 refundModel
    addRefund.value.refundModel = parseInt(addRe.value.typeR);


    // 对提交的金币数乘以 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,
      adminId: 1
    }

    // 发送POST请求
    const result = await API({ url: 'http://18.143.76.3:10704/refund/add', 
    data: processedRefund
    })
    if (result.code === 0) {
      ElMessage.error(result.msg)
      return
    }
    console.log('请求成功', result)
    ElMessage.success('添加成功')
    // 重置表单
    cancel()
  } 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 startChange = (val) => {}

const rules = reactive({
  jwcode: [{ required: true, message: '请输入精网号', trigger: 'blur' }],
  refundType: [{ required: true, message: '请选择退款类型', trigger: 'blur' }],
  goodsName: [{ 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 user = ref({
  firstRechargeTime: ''
})
const getUser = async function (jwcode) {
  trimJwCode();
  try {
    // 发送POST请求
    const result = await API({
      url: 'http://18.143.76.3:10704/user/selectUser',
      data: {
        jwcode: addRefund.value.jwcode
      }
    })
    console.log('请求成功', result)

    //在此处错误逻辑的提示做了注释，在后续商品查询接口返回错误时，提示信息会显示在弹窗中
    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) / 100,
        nowSumGold: (Number(result.data.nowSumGold) || 0) / 100,
        nowPermanentGold: (Number(result.data.nowPermanentGold) || 0) / 100,
        nowFreeGold: (Number(result.data.nowFreeGold) || 0) / 100,
        nowTaskGold: (Number(result.data.nowTaskGold) || 0) / 100
      }
      user.value = processedData;
      console.log("用户信息", user.value);
      ElMessage.success(result.msg);
    }
  } catch (error) {
    console.log("请求失败", error);
    ElMessage.error("查询失败，请检查精网号是否正确");
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}




// 退款类型
const refundType = ref([])

// 获取退款类型
const getRefundTypes = async function () {
  try {
    // 发送请求获取退款类型
    const result = await API({ 
      url: 'http://18.143.76.3:10704/refund/refundType', //这里应该写上一个退款类型的接口
      data: {} })
    console.log('退款类型请求成功', result)
    // 检查返回的数据是否为数组
    if (Array.isArray(result.data)) {
      // 将字符串数组转换为 { value, label } 格式
      refundType.value = result.data.map(item => ({ value: item, label: item }));
    } else {
      console.error('退款类型数据格式错误', result)
      ElMessage.error('退款类型数据格式错误，请联系管理员')
    }
    console.log('退款类型', refundType.value)
  } catch (error) {
    console.log('退款类型请求失败', error)
  }
}

// 根据精网号查询商品
const goodsName = ref([])
const getGoods = async function (jwcode) {
  trimJwCode();
  // 只有精网号存在时才发送请求
  if (!addRefund.value.jwcode) {
    goodsName.value = []; // 清空商品数据
    return;
  }
  try {
    // 发送POST请求
    const result = await API({
      // url: 'http://39.101.133.168:8828/live_mall/api/product/all', //需要接口
      url: 'http://18.143.76.3:10704/refund/selectGoods',
      data: {
        jwcode: addRefund.value.jwcode
      }
    })
    console.log('请求成功', result)
    // 检查返回的数据是否为数组
    if (Array.isArray(result.data)) {
      // 将字符串数组转换为 { value, label } 格式
      goodsName.value = result.data.map(item => ({ 
        value: item.goodsName,  // 使用商品名称作为 value
        label: item.goodsName, 
        key: item.goodsName,
        // 保留其他字段
        permanentGold: (Number(item.permanentGold) || 0) / 100,
        freeGold: (Number(item.freeGold) || 0) / 100,
        taskGold: (Number(item.taskGold) || 0) / 100
      }));
    } else {
      console.error('退款类型数据格式错误', result)
      ElMessage.error('退款类型数据格式错误，请联系管理员')
    }
  } catch (error) {
    console.log('请求失败', error)
    ElMessage.error('查询商品失败，请检查精网号是否正确')
    goodsName.value = []; // 请求失败时清空商品数据
  }
}

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

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 validateGoldInput = (type, value) => {
  const maxValue = selectedGoodsGold.value[type];
  const inputValue = Number(value);
  if (isNaN(inputValue)) {
    return 0;
  }
  return Math.min(inputValue, maxValue);
}

// 处理永久金币输入
const handlePermanentGoldInput = (value) => {
  addRefund.value.permanentGold = validateGoldInput('permanentGold', value);
}

// 处理免费金币输入
const handleFreeGoldInput = (value) => {
  addRefund.value.freeGold = validateGoldInput('freeGold', value);
}

// 处理任务金币输入
const handleTaskGoldInput = (value) => {
  addRefund.value.taskGold = validateGoldInput('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 permanentGold + freeGold + taskGold;
})

watch(calculatedRechargeGoods, (newVal) => {
  addRefund.value.sumGold = newVal
  console.log('计算的总金币', newVal)
})
// 绑定两个数据

// 挂载
onMounted(async function () {
  await getAdminData()
  await getRefundTypes()
  // await getGoods()
})
</script>

<template>
  <div >

  <el-form
    :model="addRefund"
    ref="Ref"
    :rules="rules"
    label-width="auto"
    style="max-width: 750px"
    class="form-style"
  >
    <el-form-item prop="jwcode" label="精网号">
      <el-input
        v-model="addRefund.jwcode"
        style="width: 220px"
        @change="getGoods(addRefund.jwcode)"
      />
      <el-button
        type="primary"
        @click="getUser(addRefund.jwcode)"
        style="margin-left: 20px"
        >查询</el-button
      >
    </el-form-item>
    <el-form-item prop="refundType" label="退款类型">
      <el-select
        v-model="addRefund.refundType"
        placeholder="请选择"
        style="width: 300px"
      >
        <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="goodsName" label="商品名">
      <el-select
        v-model="addRefund.goodsName"
        placeholder="请选择"
        style="width: 300px"
        @change="handleSelectionChange"
      >
        <el-option
          v-for="item in goodsName"
          :key="item.key"
    :label="item.label"
    :value="item"
        />
      </el-select>
    </el-form-item>

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

    <div style="display: flex; align-items: center">
      <el-form-item prop="permanentGold" label="永久金币" style="float: left">
        <el-input
          v-model="addRefund.permanentGold"
          style="width: 100px"
          :disabled="addRe.typeR === '0' ? true : false"
          @input="handlePermanentGoldInput($event)"
        >
        </el-input>
        <p>个</p>
      </el-form-item>
      <el-form-item
        prop="freeGold"
        label="免费金币"
        style="margin-left: -20px; float: left"
      >
        <el-input
          v-model="addRefund.freeGold"
          style="float: left; width: 100px"
          :disabled="addRe.typeR === '0' ? true : false"
          @input="handleFreeGoldInput($event)"
        />
        <p>个</p>
      </el-form-item>
      <el-form-item prop="taskGold" label="任务金币" style="margin-left: -20px">
        <el-input
          v-model="addRefund.taskGold"
          style="float: left; width: 100px"
          :disabled="addRe.typeR === '0' ? true : false"
          @input="handleTaskGoldInput($event)"
        />
        <p>个</p>
      </el-form-item>
    </div>
    <el-form-item prop="sumGold" label="退款金币总数">
      <el-input disabled v-model="addRefund.sumGold" style="width: 100px">
      </el-input>
    </el-form-item>
    <el-form-item prop="remark" label="备注">
      <el-input
        v-model="addRefund.remark"
        style="width: 300px"
        :rows="2"
        maxlength="100"
        show-word-limit
        type="textarea"
      />
    </el-form-item>
    <el-form-item prop="adminName" label="提交人">
      <el-input
        style="width: 300px"
        :value="adminData.adminName"
        disabled
        placeholder="提交人姓名"
      />
    </el-form-item>
    <el-button type="success" @click="cancel()" style="margin-left: 280px">重置</el-button>
    <el-button type="primary" @click="addBefore"> 提交 </el-button>
  </el-form>

  <!-- 客户信息栏 -->
  <el-card v-if=user.jwcode style="width: 850px; float: right" class="customer-info">
    <el-form
      :model="user"
      label-width="auto"
      style="max-width: 1000px"
      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.historySumGold))">
              {{ Number(user.historySumGold) }}
            </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.nowSumGold !== 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-col>
      </el-row>
    </el-form>
  </el-card>
  </div>
</template>

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

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

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

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}

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

.form-style2 {
  max-width: 60%;
}

p {
  font-size: 13px;
  transform: scale(1);
}
</style>
