<template>
  <div class="app-container customer-control">
    <div class="container-custom">
      <!-- 搜索栏 -->
      <div ref="searchBarRef" class="search-box">
        <div class="search-bar">
          <div class="search-bar-left">
            <el-form
              ref="searchForm"
              :inline="true"
              :model="formInline"
              class="demo-form-inline"
              :label-width="'auto'"
            >
              <el-form-item label="分类名称" prop="userCategoryName">
                <el-input
                  v-model="formInline.categoryName"
                  placeholder="分类名称"
                  clearable
                />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="formInline.status" placeholder="请选择" clearable>
                  <el-option label="启用" value="1" />
                  <el-option label="禁用" value="0" />
                </el-select>
              </el-form-item>
              <el-form-item
                label="添加时间"
                prop="createTime"
                style="margin-right: 0"
              >
                <el-date-picker
                  v-model="formInline.createTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择添加时间"
                  clearable
                  :disabled-date="disableStartDate"
                  style="width: 160px"
                />
              </el-form-item>
            </el-form>
          </div>
          <div class="search-bar-right">
            <el-button class="el-button-gry" type="primary" icon="Search" @click="onSubmit"
              >查询</el-button
            >
            <el-button
              icon="Refresh"
              style="margin: 16px 0 0 0"
              @click="resetForm"
              >重置</el-button
            >
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-cont" :style="{ height: tableViewportHeight + 'px' }">
        <div class="table-toolbar">
          <el-button icon="delete" @click="batchDelete" :disabled="btnStatus"
            style="margin-right: 10px">批量删除</el-button>
          <el-button type="primary" icon="plus" @click="handleAdd">新增客户</el-button>
        </div>
        <tableComponent :table-data="tableData" :columns="columns" :show-border="false" :show-selection="true"
          :header-cell-class-name="getHeaderClass" @page-change="handlePaginationChange" :loading="tableLoading"
          @selection-change="handleSelectionChange" :total="tableTotal" :current-page="formInline.current"
          :page-size="formInline.size" :showSort="true" :rowkey="'goodId'">
          
          <!-- 自定义 - 序号 -->
          <template #sort="slotProps">
            <span v-if="slotProps.row.goodPrice">￥{{ slotProps.row.goodPrice }}</span>
          </template>

          <!-- 自定义-状态 -->
          <template #status="slotProps">
            <span v-if="slotProps.row.status == 0" class="color-red">禁用</span>
            <span v-else-if="slotProps.row.status == 1" class="color-green">启用</span>
          </template>

          <!-- 自定义-操作 -->
          <template #action="slotProps">
            <el-button text v-if="slotProps.row.status == 0" class="el-button-custom"
              @click="startStop(slotProps.row)">启用</el-button>
            <el-button text v-if="slotProps.row.status == 1" class="el-button-custom"
              @click="startStop(slotProps.row)">禁用</el-button>
            <el-button text class="el-button-custom" @click="handleEdit(slotProps.row)">编辑</el-button>
            <el-button text class="el-button-delete" @click="handleDelete(slotProps.row)">删除</el-button>
          </template>
        </tableComponent>
      </div>
    </div>
    <!-- 添加/编辑商品 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" :close-on-click-modal="false">
      <el-form :model="dialogForm" :label-width="'80'" :rules="dialogFormRules" ref="dialogRef">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="dialogForm.categoryName" autocomplete="off" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSaveCategory">
            保存
          </el-button>
          <el-button @click="cancelDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from "vue";
import tableComponent from "@/components/tableComponent.vue";
import Mock from "mockjs";
import { id } from "element-plus/es/locales.mjs";
import {getCustomerPage,addCustomer,getInfo,updateCustomer,deleteCustomer,updateCustomerEnable} from "@/api/customer/index";
import { ElMessage,ElMessageBox } from 'element-plus'
import { start } from "nprogress";

const formInline = reactive({
  categoryName: "",
  createTime: "",
  status: null,
  current: 1,
  size: 10,
});

let isADD = ref(true);
const dialogFormVisible = ref(false);
const dialogRef = ref(null);
const dialogTitle = ref("添加客户");
let dialogForm = reactive({
    categoryName: "",

});
const dialogFormRules = ref({
    categoryName:  [
        { required: true, message: "请输入分类名称", trigger: "blur" },
    ]
});

// 禁用开始日期的逻辑（不能晚于已选的结束日期）
const disableStartDate = (time) => {
  if (!formInline.endDate) return false;
  const endDate = new Date(formInline.endDate);
  return time.getTime() > endDate.getTime();
};

// 禁用结束日期的逻辑（不能早于已选的开始日期）
const disableEndDate = (time) => {
  if (!formInline.startDate) return false;
  const startDate = new Date(formInline.startDate).setHours(0, 0, 0, 0);
  const currentDate = new Date(time).setHours(0, 0, 0, 0);
  return currentDate < startDate;
};

const searchForm = ref(null);
const onSubmit = () => {
   formInline.current = 1;
   if  (formInline.startDate && !formInline.endDate) {
    ElMessage.warning("请选择结束日期！");
    return;
  }
  if (formInline.endDate && !formInline.startDate) {
     ElMessage.warning("请选择开始日期！");
    return;
  }
  console.log( formInline);
  loadData();
};
const resetForm = () => {
formInline.categoryName = "";
  formInline.createTime = "";
  formInline.status = null;
  formInline.current = 1;
  formInline.size = 10;
  searchForm.value.resetFields();
  loadData();
};

// 表格数据
const tableData = ref([]);
const tableLoading = ref(false);
const tableTotal = ref(0);
const selectedIds = ref([]);
const btnStatus = computed(() => {
  return selectedIds.value.length <= 0;
});
// 列配置
const columns = ref([
  { prop: "id", label: "ID" },
  { prop: "categoryName", label: "分类名称" },
  { prop: "createTime", label: "添加时间" },
  { prop: "status", label: "状态", slotName: "status" },
  { prop: "action", label: "操作", slotName: "action",width: "140",align: "center" },
]);

// 生成模拟数据
const generateMockData = () => {

  try {
    getCustomerPage(formInline).then(res=>{
      // console.log(res);
      if(res.code == 200){
        tableData.value = res.data.records;
        tableTotal.value = res.data.total;
      }
    })
  } catch (error) {
    console.log(error);
  }

  // return Mock.mock({
  //   "list|10": [
  //     {
  //       "id|+1": 10000,
  //       nickname: () => generateFoodNickname(), //昵称
  //       userName: "@cname", //姓名
  //       accountNumber: "@integer(1000000000, 9999999999)", //账号
  //       phoneNumber: "@integer(13000000000, 18999999999)", //手机号
  //       sex: '@pick(["男", "女"])', //性别
  //       "userStatus|1": [0, 1], //0异常 1正常
  //       "userCategory|1":
  //         '@pick(["活跃/低消费", "活跃/中消费", "活跃/高消费"])', //用户分类
  //       unitPrice: "@float(10, 200, 2, 2)", //客单价
  //       ordersNums: "@integer(10, 200)",
  //     },
  //   ],
  // }).list;
};
// 加载数据
const loadData = () => {
  generateMockData()
  // // 模拟API请求延迟
  // setTimeout(() => {
  //   tableData.value = generateMockData();
  //   tableTotal.value = tableData.value.length;
  // }, 500);
};
// 自定义表头类名,也可以在columns指定列中添加headerClassName: 'custom-header'
const getHeaderClass = ({ column }) => {
  return "custom-header";
};
// 分页变化
const handlePaginationChange = ({ page, pageSize }) => {
  // console.log("分页变化:", page, pageSize);
  formInline.current = page;
  formInline.size = pageSize;
  // 这里可以调用API获取新数据
  loadData();
};
// 多选框变化
const handleSelectionChange = (selection) => {
  // console.log("选中项:", selection);
  selectedIds.value = [];
  selection.forEach(element => {
    selectedIds.value.push(element.id);
  });
};

//  添加
const handleAdd = () => {
  dialogTitle.value = "添加客户分类";
  isADD.value = true;
  dialogFormVisible.value = true;
  // console.log(formInline);
};

// 编辑操作
const handleEdit = async(row) => {
  isADD.value = false;
  dialogFormVisible.value = true;
  let response = await getInfo(row.id);
  if (response.code === 200) {
    Object.assign(dialogForm, response.data); // 保持响应性
    dialogTitle.value = "编辑客户分类";
  } else {
    ElMessage.error(response.message);
  }
};
//提交保存
const onSaveCategory = async () => { 
  dialogRef.value.validate(async (valid) => { 
    if (valid) { 
        if(isADD.value){
            let response = await addCustomer(dialogForm);
            if (response.code === 200) {
                dialogFormVisible.value = false;
                ElMessage.success("新增成功！");
                dialogRef.value.resetFields();
                loadData();
            } else {
                ElMessage.error(response.message);
            }
        }else{ 
            let response = await updateCustomer(dialogForm);
            if (response.code === 200) {
                dialogFormVisible.value = false;
                ElMessage.success("编辑成功！");
                dialogRef.value.resetFields();
                loadData();
            } else {
                ElMessage.error(response.message);
            }
        }
    }
  });
};
// 删除操作
const handleDelete = (row) => {
  //提示一下是否确定删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let response = await deleteCustomer(row.id);
      if (response.code === 200) {
        ElMessage.success("删除成功！");
        loadData();
      } else {
        ElMessage.error(response.message);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    })
};
// 批量删除
const batchDelete = async () => {
  // deleteGoods(selectedIds.value.join(","));
  ElMessageBox.confirm("确定要删除选中的数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
       deleteCustomer(selectedIds.value);
       loadData();
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    })
  
};

//启用停用
const startStop = async (row) => {
  let status = row.status == 1 ? 0 : 1;
  let params = { id: row.id, status: status };
  let response = await updateCustomerEnable(params);
  if (response.code === 200) {
    ElMessage.success("操作成功！");
    loadData();
  } else {
    ElMessage.error(response.message);
  }
};

//取消弹框
const cancelDialog = () => {
  dialogFormVisible.value = false;
  dialogRef.value?.resetFields(); // 重置表单验证状态
};

const titleRef = ref(null);
const searchBarRef = ref(null);
const tableViewportHeight = ref(0);
// 精确计算可用高度
const calculateTableHeight = () => {
  // 获取窗口总高度
  const windowHeight = window.innerHeight;

  // 获取各组件高度
  const headerHeight = titleRef.value?.$el?.offsetHeight || 0;
  const searchBarHeight = searchBarRef.value?.offsetHeight || 0;

  // 计算容器内边距补偿（根据实际样式调整）
  const paddingCompensation = 130;

  // 最终计算
  tableViewportHeight.value =
    windowHeight - headerHeight - searchBarHeight - paddingCompensation;
  // console.log(tableViewportHeight.value);
};
// 组件挂载时加载数据
onMounted(() => {
  loadData();

  calculateTableHeight();

  // 添加响应式监听
  window.addEventListener("resize", calculateTableHeight);

  // 监听DOM变化（适用于动态变化的header/searchbar）
  const observer = new ResizeObserver(calculateTableHeight);
  if (titleRef.value?.$el) observer.observe(titleRef.value.$el);
  if (searchBarRef.value) observer.observe(searchBarRef.value);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", calculateTableHeight);
});
</script>
<style lang="scss" scoped>
.table-toolbar {
  width: 300px;
  height: 50px;
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  justify-content: end;
  padding: 14px 16px 0 0;
}
</style>
