<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'
const user = ref({})
const getUser = async function (jwcode) {
  if (consumeForm.value.jwcode) {
    consumeForm.value.jwcode = consumeForm.value.jwcode.replace(/\s/g, '');
  } else {
    ElMessage.error('请先输入精网号')
    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("用户不存在");
    } else {
      user.value = result.data;
      console.log("用户信息", user.value);
      ElMessage.success("查询成功");
    }
  } catch (error) {
    console.log("请求失败", error);
    ElMessage.error("精网号错误");
  }
}
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: '请输入精网号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('精网号不能为空'));
          return;
        }
        if (/[^0-9]/.test(value)) {
          callback(new Error('精网号只能包含数字'));
          return;
        }
        callback();
      }, trigger: 'blur'
    }],
  permanentBean: [
    { required: true, message: '请输入永久金豆数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        // 检查是否为非负整数
        if (!/^\d+$/.test(value)) {
          callback(new Error('请输入非负整数'));
          return;
        }

        // 检查位数
        if (value.length > 6) {
          callback(new Error('整数位数不能超过6位'));
          return;
        }
        callback();
      },

      trigger: 'blur'
    }
  ],
  freeBean: [
    { required: true, message: '请输入免费金豆数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        // 检查是否为非负整数
        if (!/^\d+$/.test(value)) {
          callback(new Error('请输入非负整数'));
          return;
        }

        // 检查位数
        if (value.length > 6) {
          callback(new Error('整数位数不能超过6位'));
          return;
        }
        callback();
      },
      trigger: 'blur'
    }
  ],
  remark: [
    { required: true, message: '请输入备注', trigger: 'blur' }
  ]
});

//重置表单
const deleteConsumeForm = function () {
  consumeForm.value = {
    jwcode: '',
    permanentBean: '',
    freeBean: '',
    remark: '',
    adminName: ''
  }
}

const handleConsumeForm = async () => {
  try {
    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('永久金豆和付费金豆不能同时为0'));
          }
          resolve(); // 验证通过，继续执行后续代码
        } else {
          reject(new Error('请检查并完善表单信息')); // 验证失败，抛出错误
        }
      });
    });
    console.log('adminData', adminData.value);

    await ElMessageBox.confirm(
      '确认消耗吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: "primary",
        lockScroll: false,
      }
    )
    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
      }
    })
    if (result.code == 200) {
      ElMessage.success('新增成功')
      consumeForm.value = {
        jwcode: "",
        permanentBean: '',
        freeBean: '',
        remark: '',
        adminName: ''
      }
    }else{
      ElMessage.error(result.msg)
    }
  } catch (error) {
    console.log('金豆新增充值失败');
    ElMessage.error(error.message || '操作失败');
  }
}
const throttledHandleConsumeFormt = _.throttle(handleConsumeForm, 5000, {
  trailing: false
})
</script>
<template>
  <div>
    <el-form :model="consumeForm" :rules="rules" ref="formRef" label-width="auto" style="max-width: 600px" class="consume-form">
      <el-form-item prop="jwcode" label="精网号" label-position="left">
        <el-input v-model="consumeForm.jwcode" style="width: 220px" />
        <el-button type="primary" @click="getUser(consumeForm.jwcode)" style="margin-left: 20px">查询</el-button>
      </el-form-item>
      <el-form-item prop="permanentBean" label="付费金豆" label-position="left">
        <el-input v-model="consumeForm.permanentBean" style="width: 100px" />
      </el-form-item>
      <el-form-item prop="freeBean" label="免费金豆" label-position="left">
        <el-input v-model="consumeForm.freeBean" style="width: 100px" />
      </el-form-item>
      <el-form-item prop="remark" label="备注" 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-form-item prop="adminName" label="提交人">
        <el-input style="width: 300px" :value="adminData.adminName" disabled placeholder="提交人姓名" />
      </el-form-item> -->
      <el-button @click="deleteConsumeForm" style="margin-left: 280px" type="success">重置</el-button>
      <el-button type="primary" @click="handleConsumeForm"> 提交 </el-button>
    </el-form>

    <!-- 客户信息栏 -->
    <el-card v-if="user.jwcode" style="width: 800px; 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="9">
            <el-form-item label="姓名:">
              <p style="color: #2fa1ff; margin-right: 5px">{{ user.name }}</p>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="当前付费金豆:">
              <p style="color: #2fa1ff; margin-right: 5px" v-if="!isNaN(Number(user.permanentBean))">
                {{ Number(user.permanentBean) }}
              </p>
              <!-- 如果不是有效的数字，显示默认值 -->
              <p v-else></p>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：精网号 + 免费金豆 -->
        <el-row >
          <el-col :span="9">
            <el-form-item label="精网号">
              <p style="color: #2fa1ff; margin-right: 5px">{{ user.jwcode }}</p>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="当前免费金豆:">
              <span style="color: #2fa1ff; margin-right: 5px" v-if="user.freeBean !== undefined">{{ user.freeBean }}
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行：消费次数 + 所属门店 -->
        <el-row>
          <el-col :span="9">
            <el-form-item label="所属门店">
              <p style="color: #2fa1ff">{{ user.market }}</p>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="消费次数">
              <p style="color: #2fa1ff; margin-right: 5px" v-if="user.consumeNum!=null">{{ user.consumeNum }}</p>
              <p style="color: #2fa1ff; margin-right: 5px" v-else>{{ 0 }}</p>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>


  </div>
</template>
<style scoped>
.consume-form {
  margin-top: 50px;
  max-width: 50%;
  float: left;
}

.customer-info {
  max-width: 60%;
}

p {
  margin: 0px;
}

.el-form-item {
  margin-left: 50px;
}
</style>