<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.js'
import { uploadFile } from '@/util/request.js';
import request from '@/util/http.js'
import moment from 'moment'
import { e, range, re } from 'mathjs'
import { utils, read } from 'xlsx'
import throttle from 'lodash/throttle'
import { useAdminStore } from "@/store/index.js";
import { storeToRefs } from "pinia";
import _ from 'lodash'
// 国际化
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const user = ref({})

const getUser = async function (jwcode) {
  if (consumeForm.value.jwcode) {
    consumeForm.value.jwcode = consumeForm.value.jwcode.replace(/\s/g, '');
  } else {
    ElMessage.error(t('elmessage.checkJwcode'))
    return false
  }
  try {
    const result = await API({
      url: '/beanUser/userCard',
      data: {
        jwcode: consumeForm.value.jwcode
      }
    })
    if (result.code === 0) {
      ElMessage.error(result.msg);
    } else if (result.data === null) {
      ElMessage.error(t('elmessage.noUser'));
    } else {
      user.value = result.data;
      console.log("用户信息", user.value);
      ElMessage.success(t('elmessage.searchSuccess'));
    }
  } catch (error) {
    console.log("请求失败", error);
    ElMessage.error(t('elmessage.jwcodeError'));
  }
}

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

const consumeForm = ref({
  jwcode: '',
  permanentBean: '',
  freeBean: '',
  remark: '',
  adminName: ''
})
const formRef = ref(null)
const adminStore = useAdminStore()
const { adminData } = storeToRefs(adminStore)
const rules = reactive({
  jwcode: [
    { required: true, message: t('elmessage.checkJwcode'), trigger: 'blur' },
    {
      validator: (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();
      }, trigger: 'blur'
    }],
  permanentBean: [
    { required: true, message: t('elmessage.checkPayBean'), trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          value = 0
        }
        // 检查是否为非负整数
        if (!/^\d+$/.test(value)) {
          callback(new Error(t('elmessage.checkNonNegative')));
          return;
        }

        // 检查位数
        if (value.length > 6) {
          callback(new Error(t('elmessage.limitSix')));
          return;
        }
        callback();
      },

      trigger: 'blur'
    }
  ],
  freeBean: [
    { required: true, message: t('elmessage.checkFreeBean'), trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          value = 0
        }
        // 检查是否为非负整数
        if (!/^\d+$/.test(value)) {
          callback(new Error(t('elmessage.checkNonNegative')));
          return;
        }

        // 检查位数
        if (value.length > 6) {
          callback(new Error(t('elmessage.limitSix')));
          return;
        }
        callback();
      },
      trigger: 'blur'
    }
  ],
  remark: [
    { required: true, message: t('elmessage.checkRemark'), trigger: 'blur' }
  ]
});

//重置表单
const deleteConsumeForm = function () {
  formRef.value.resetFields();
}

const handleConsumeForm = async () => {
  try {
    if (!consumeForm.value.permanentBean) {
      consumeForm.value.permanentBean = 0
    }
    if (!consumeForm.value.freeBean) {
      consumeForm.value.freeBean = 0
    }
    await new Promise((resolve, reject) => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (Number(consumeForm.value.permanentBean) === 0 && Number(consumeForm.value.freeBean) === 0) {
            reject(new Error(t('elmessage.noPayBeanFreeBeanZero')));
          }
          resolve(); // 验证通过，继续执行后续代码
        } else {
          reject(new Error(t('elmessage.checkFormInfo'))); // 验证失败，抛出错误
        }
      });
    });
    console.log('adminData', adminData.value);

    // 新增验证逻辑，判断输入数量是否超过用户拥有数量
    const inputPermanentBean = Number(consumeForm.value.permanentBean);
    const inputFreeBean = Number(consumeForm.value.freeBean);
    const userPermanentBean = Number(user.value.permanentBean) || 0;
    const userFreeBean = Number(user.value.freeBean) || 0;

    // if (inputPermanentBean > userPermanentBean) {
    //   throw new Error('付费金豆数量超过用户当前所拥有');
    // }
    // if (inputFreeBean > userFreeBean) {
    //   throw new Error('免费金豆数量超过用户当前所拥有');
    // }

    await ElMessageBox.confirm(
      t('consume.confirmConsume'),
      t('consume.prompt'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: "primary",
        lockScroll: false,
      }
    )
    addDisabled.value = true
    const result = await request({
      url: '/beanConsume/reduce',
      data: {
        jwcode: consumeForm.value.jwcode,
        permanentBean: consumeForm.value.permanentBean,
        freeBean: consumeForm.value.freeBean,
        remark: consumeForm.value.remark,
        adminName: adminData.value.adminName
      }
    })
    addDisabled.value = false
    if (result.code == 200) {
      ElMessage.success(t('elmessage.addsuccess'))
      deleteConsumeForm()
      user.value = {}
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    console.log('金豆新增充值失败');
    ElMessage.error(error.message || t('elmessage.operationFailed'));
  }
}
const throttledHandleConsumeFormt = _.throttle(handleConsumeForm, 5000, {
  trailing: false
})
</script>
<template>
  <div class="userAndform">
    <div class="left">
      <el-form :model="consumeForm" :rules="rules" ref="formRef" label-width="auto" style="max-width: 600px"
        class="add-form">
        <el-form-item prop="jwcode" :label="t('common_add.jwcode')" label-position="left">
          <el-input v-model="consumeForm.jwcode" style="width: 220px" @keyup.enter="getUser(consumeForm.jwcode)"/>
          <el-button type="primary" @click="getUser(consumeForm.jwcode)" style="margin-left: 20px">{{ t('common.search') }}</el-button>
        </el-form-item>
        <el-form-item prop="permanentBean" :label="t('common_add.permanentBean')" label-position="left">
          <el-input v-model="consumeForm.permanentBean" placeholder="0" style="width: 100px" />
        </el-form-item>
        <el-form-item prop="freeBean" :label="t('common_add.freeBean')" label-position="left">
          <el-input v-model="consumeForm.freeBean" placeholder="0" style="width: 100px" />
        </el-form-item>
        <el-form-item prop="remark" :label="t('common_add.remark')" label-position="left">
          <el-input v-model="consumeForm.remark" style="width: 300px" :rows="5" maxlength="100" show-word-limit
            type="textarea" />
        </el-form-item>
        <el-button @click="deleteConsumeForm" style="margin-left: 9vw;margin-top:1vw" type="success">{{ t('common.reset') }}</el-button>
        <el-button type="primary" :disabled="addDisabled" @click="handleConsumeForm" style="margin-top:1vw"> {{ t('common.submit') }}
        </el-button>
      </el-form>
    </div>

    <!-- 客户信息栏 -->
    <div class="right">
      <el-card v-if="user.jwcode" class="customer-info">
        <el-form :model="user" label-width="auto" label-position="left">
          <el-text size="large" style="margin-left: 5vw">{{ t('common_add_user.customerInfo') }}</el-text>
          <!-- 第一行：姓名 + 当前付费金豆 -->
          <div style="margin-top: 0.5vw;display:flex;">
            <p style="min-width:6vw;">{{ t('common_add_user.name') }}:</p>
            <p style="color: #2fa1ff;width:6vw;">{{ user.name }}</p>
            <p style="width:7vw;">{{ t('common_add_user.permanentBean') }}:</p>
            <p v-if="!isNaN(Number(user.permanentBean))" style="color: #2fa1ff;">{{ Number(user.permanentBean) }}</p>
            <!-- 如果不是有效的数字，显示默认值 -->
            <p v-else></p>
          </div>

          <!-- 第二行：精网号 + 免费金豆 -->
          <div style="display:flex">
            <p style="width:6vw;">{{ t('common_add_user.jwcode') }}:</p>
            <p style="color: #2fa1ff;width:6vw;">{{ user.jwcode }}</p>
            <p style="width:7vw;">{{ t('common_add_user.freeBean') }}:</p>
            <p v-if="user.freeBean !== undefined" style="color: #2fa1ff;">{{ user.freeBean }}</p>
          </div>

          <!-- 第三行：消费次数 + 所属门店 -->
          <div style="display:flex">
            <p style="width:6vw;">{{ t('common_add_user.store') }}:</p>
            <p style="color: #2fa1ff;width:6vw;">{{ user.market }}</p>
            <p style="width:7vw;">{{ t('common_add_user.consumeTotalBean') }}:</p>
            <p style="color: #2fa1ff;" v-if="user.consumeSum != null">{{ user.consumeSum }}</p>
            <p style="color: #2fa1ff;" v-else>{{ 0 }}</p>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<style scoped lang="scss">
.userAndform {
  width: 80vw;
  height: 80vh;
  display: flex;

  .left {
    width: 35vw;
    height: 80vh;
    display: flex;

    .add-form {
      width: 40vw;
      margin-top: 5vh;
    }
  }

  .right {
    flex: 1;
    display: flex;
    // float: left;

    .customer-info {
      min-width: 35vw;
      height: 28vh;
      margin-top: 5vh;
      // display: flex;
      justify-content: center;
    }
  }
}
</style>