<script setup lang="ts">
import { ref } from 'vue';
import { Page } from '@vben/common-ui';
import { useVbenVxeGrid, type VxeGridProps } from '#/adapter/vxe-table';
import { columns } from './config-data';
import CreateClasses from './components/CreateClasses.vue';
import {
  addClassesApi,
  queryrclassesApilist,
  updateClassesApi,
  deleteClassesApi,
} from '#/api/schedule/work/classes';
import dayjs from 'dayjs';
const ClassName = ref('');
const isdrawertitle = ref('');
const isdrawer = ref(false);
const isdrawerloading = ref(false);
const editdata = ref({});
// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
    checkMethod: ({ row }) => row?.roleId !== 1,
  },
  columns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        console.log(formValues);

        const resp = await queryrclassesApilist({
          // ...formValues,
          shiftName: ClassName.value,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'roleId',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-role-index',
};
const [BasicTable, BasicTableApi] = useVbenVxeGrid({
  gridOptions,
});
//新增
const handleAddClick = () => {
  isdrawertitle.value = '新增班次';
  isdrawer.value = true;
};
// 将"X小时Y分钟"格式转换为小时的小数形式（如7.59）
const convertDurationToDecimal = (duration: string): number => {
  if (!duration) return 0;

  const hoursMatch = duration.match(/(\d+)小时/) as any;
  const minutesMatch = duration.match(/(\d+)分钟/) as any;

  const hours = hoursMatch ? parseInt(hoursMatch[1], 10) : 0;
  const minutes = minutesMatch ? parseInt(minutesMatch[1], 10) : 0;

  // 转换为小时的小数形式，保留两位小数
  return Number((hours + minutes / 60).toFixed(2));
};

const handleSubmit = async (data: any) => {
  console.log(data);

  try {
    isdrawerloading.value = true;

    // 构建请求参数
    const requestData = {
      applicableStations: data.stationIds.join(','),
      firstStartTime: dayjs(data.firstWorkTime).format('YYYY-MM-DD HH:mm:ss'),
      firstEndTime: dayjs(data.lastWorkTime).format('YYYY-MM-DD HH:mm:ss'),
      firstDuration: convertDurationToDecimal(data.firstWorkDuration),
      isCommon: data.common,
      secondStartTime: data.secondWorkTime
        ? dayjs(data.secondWorkTime).format('YYYY-MM-DD HH:mm:ss')
        : null,
      secondEndTime: data.secondLastWorkTime
        ? dayjs(data.secondLastWorkTime).format('YYYY-MM-DD HH:mm:ss')
        : null,
      secondDuration: convertDurationToDecimal(data.secondWorkDuration),
      shiftName: data.name,
    };
    if (data.id) {
      // 编辑操作
      await updateClassesApi({
        ...requestData,
        id: data.id,
      });
    } else {
      // 新增操作
      await addClassesApi(requestData);
    }
    if (BasicTableApi) {
      await BasicTableApi.reload();
    }

    // 关闭抽屉
    isdrawer.value = false;

    // 清空编辑数据
    editdata.value = {};
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    isdrawerloading.value = false;
  }
};
const editbtn = (row: any) => {
  console.log(row);

  isdrawertitle.value = '编辑班次';
  isdrawer.value = true;
  editdata.value = { ...row };
};
const handleSearchClick = () => {
  if (BasicTableApi) {
    BasicTableApi.reload();
  }
};
const handleResetClick = () => {
  ClassName.value = '';
  if (BasicTableApi) {
    BasicTableApi.reload();
  }
};
const deletebtn = async (row: any) => {
  try {
    await deleteClassesApi(row?.id);
    if (BasicTableApi) {
      await BasicTableApi.reload();
    }
  } catch (error) {
    console.error('操作失败:', error);
  }
};
</script>
<template>
  <Page :auto-content-height="true">
    <template #description>
      <div style="display: flex; justify-content: space-between" ;>
        <div>
          <span style="font-size: 14px; margin-right: 8px">班次名称</span
          ><el-input
            v-model="ClassName"
            style="width: 240px"
            placeholder="请输入班次名称"
          />
        </div>
        <div>
          <el-button type="primary" @click="handleAddClick">添加</el-button
          ><el-button type="primary" @click="handleSearchClick">搜索</el-button
          ><el-button type="primary" @click="handleResetClick">重置</el-button>
        </div>
      </div>
    </template>
    <BasicTable>
      <template #action="{ row }">
        <el-button size="small" type="primary" plain @click="editbtn(row)"
          >编辑</el-button
        >
        <el-button size="small" plain @click="deletebtn(row)">删除</el-button>
      </template>
      <template #isCommon="{ row }">
        {{ row.isCommon == '0' ? '否' : '是' }}
      </template>
    </BasicTable>
    <CreateClasses
      v-model="isdrawer"
      @submit="handleSubmit"
      :isdrawertitle="isdrawertitle"
      :isdrawerloading="isdrawerloading"
      :editdata="editdata"
    />
  </Page>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
