<script setup lang="ts">
import { type VxeFormListeners, type VxeFormProps, type VxeGridInstance, type VxeGridListeners, type VxeGridProps, VxeUI } from 'vxe-pc-ui';
import { usePagination, useRequest } from 'alova/client';
import { getDictionaryMethod } from '@/request/api/dictionary.api';
import dayjs from 'dayjs';
import EditConfigured from '@/service/EditConfigured.vue';
// model
import type { ConditioningSchemeModel, ConditioningSchemeQuery } from '@/model/care.model';

// 接口数据
import { getConditioningSchemeMethod } from '@/request/api/care.api';
import { branchMethod } from '@/request/api/system.api';

// 获取组织名称
const { data: branch, loading: branchLoading } = useRequest(branchMethod(0, 1, 1));

const model = shallowRef<ConditioningSchemeQuery>();

// 获取设备类型
const deviceTypes = ref<{ id: string; name: string }[]>([]);
const deviceTypesLoading = ref(false);

// 日期验证
const configTimeStart = ref<string>('');
const configTimeEnd = ref<string>('');
// 禁用结束时间的日期（早于开始时间的日期）
function disabledEndDate(current: any) {
  if (!configTimeStart.value) return false;
  return current && current < dayjs(configTimeStart.value);
}

const searchFormProps = reactive<VxeFormProps<ConditioningSchemeQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {
    // isConfig: 'Y',
  },
  items: [
    {
      field: 'orgId',
      title: '组织名称',
      span: 5,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          loading: computed(() => branchLoading.value),
          options: computed(() => branch.value),
          optionProps: { value: 'id', label: 'label' },
          clearable: true,
        },
        events: {
          change(val: any) {
            insArr.value = [];
            if (val.data.orgId) {
              // 清空表单中的机构名称字段
              if (model.value) {
                // model.value.institutionId = '';
                model.value.insId = '';
              }
              getInstitution(val.data.orgId);
            }
          },
        },
      },
    },
    {
      field: 'insId',
      title: '机构名称',
      span: 6,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          loading: computed(() => insLoading.value),
          options: computed(() => insArr.value),
          optionProps: { value: 'id', label: 'label' },
          clearable: true,
        },
      },
    },
    {
      field: 'configTimeStart',
      title: '配置时间',
      span: 10,
      slots: {
        default: 'createTimes',
      },
    },
    {
      field: 'isConfig',
      title: '是否配置',
      span: 6,
      itemRender: {
        name: 'VxeRadioGroup',
        options: [
          { label: '已配置', value: 'Y' },
          { label: '未配置', value: 'N' },
        ],
        props: {
          strict: false,
        },
      },
    },
    {
      span: 3,
      itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { name: 'submits', type: 'submit', content: '查询', status: 'primary' },
          { name: 'reset', type: 'reset', content: '清空', status: 'warning' },
        ],
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<ConditioningSchemeQuery> = {
  // 查询设备登记
  submit({ data }) {
    model.value = {
      ...data,
      configTimeStart: configTimeStart.value ? dayjs(configTimeStart.value).format('YYYY-MM-DD HH:mm:ss') : '',
      configTimeEnd: configTimeEnd.value ? dayjs(configTimeEnd.value).format('YYYY-MM-DD HH:mm:ss') : '',
    } as any;
  },
  // 重置
  reset({ data }) {
    model.value = { ...data } as any;
    configTimeStart.value = '';
    configTimeEnd.value = '';
  },
};
// 设备列表
const gridRef = ref<VxeGridInstance<ConditioningSchemeModel>>();
const gridOptions = reactive<VxeGridProps<ConditioningSchemeModel>>({
  id: 'tag-list',
  border: true,
  showOverflow: true,
  height: 'auto',
  autoResize: false,
  syncResize: true,
  scrollY: { enabled: true, gt: 0 },
  toolbarConfig: {
    custom: true,
    zoom: true,
    slots: {
      tools: 'toolbar-extra',
    },
  },
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    storage: true,
  },
  columns: [
    { field: 'orgName', title: '组织名称' },
    { field: 'insName', title: '机构名称' },
    // {
    //   field: 'isHaveForInfer',
    //   title: '是否定制项目',
    //   slots: {
    //     default: 'isHaveForInferSlot',
    //   },
    // },
    // { field: 'forInferCount', title: '定制项目数' },

    {
      field: 'isConfig',
      title: '是否配置',
      slots: {
        default: 'isConfiguredSlot',
      },
    },
    { field: 'updateBy', title: '修改人' },
    { field: 'updateTime', title: '修改时间' },
    {
      field: 'action',
      title: '操作',
      align: 'center',
      width: 120,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [{ content: '编辑', status: 'primary', name: 'EditConfigured' }],
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if (name === 'EditConfigured') {
              method = editConfigured;
            }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

// 获取设备分页列表
const { loading, page, pageSize, total, onSuccess, replace, refresh, remove, send: sendRefresh } = usePagination((page, size) => getConditioningSchemeMethod(page, size, model.value), {
  initialData: { data: [], total: 0 },
  initialPage: 1,
  initialPageSize: 100,
  watchingStates: [model],
  immediate: false,
});
onSuccess(({ data: { data } }) => {
  gridRef.value?.loadData(data);
});

// 获取设备类型
async function getDeviceType() {
  deviceTypesLoading.value = true;
  const res = await getDictionaryMethod('fdhb_device_type');
  if (res && res.length > 0) {
    deviceTypes.value = res.map((item: any) => ({
      id: item.label,
      name: item.label,
    }));
  }
  deviceTypesLoading.value = false;
}
const insLoading = ref(false);
const insArr = ref<any[]>([]);
async function getInstitution(orgId: string | number) {
  insLoading.value = true;
  const res = await branchMethod(1, 0, Number(orgId));
  if (res && res.length > 0) {
    insArr.value = res;
  }
  insLoading.value = false;
}
onMounted(() => {
  getDeviceType();
  model.value = toRaw(searchFormProps.data);
});

// 编辑配置
function editConfigured(model?: ConditioningSchemeModel, index?: number) {
  VxeUI.modal.open({
    title: model?.id ? `修改配置` : `新增配置`,
    height: 750,
    width: 1100,
    escClosable: true,
    destroyOnClose: true,
    id: `configured-modal`,
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(EditConfigured, <any>{
          data: model,
          onSubmit(success: boolean, data?: ConditioningSchemeModel) {
            console.log(success, 'success');
            // 只有成功时才刷新列表
            if (success) {
              // 使用 sendRefresh 强制刷新，避免页面闪烁
              sendRefresh();
            }
            VxeUI.modal.close(`configured-modal`);
          },
        });
      },
    },
  });
}
</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none mt-4">
      <vxe-form v-bind="searchFormProps" v-on="searchFormEmits">
        <template #createTimes>
          <div class="date-range-container">
            <a-date-picker v-model:value="configTimeStart" placeholder="请选择开始时间" style="flex: 1" :show-time="{ format: 'HH:mm' }" />
            <span class="date-separator">至</span>
            <a-date-picker v-model:value="configTimeEnd" placeholder="请选择结束时间" style="flex: 1" :disabledDate="disabledEndDate" :show-time="{ format: 'HH:mm' }" />
          </div>
        </template>
      </vxe-form>
    </header>
    <main class="flex-auto overflow-hidden">
      <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" :loading="loading">
        <template #isConfiguredSlot="{ row }">
          <div :class="row.isConfig === 'Y' ? 'text-green-500' : 'text-red-500'">{{ row.isConfig === 'Y' ? '已配置' : '未配置' }}</div>
        </template>
        <template #isHaveForInferSlot="{ row }">
          <div>{{ row.isHaveForInfer === 'Y' ? '定制' : '无定制' }}</div>
        </template>
        <template #toolbar-extra>
          <vxe-button style="margin-right: 12px" icon="vxe-icon-repeat" circle @click="refresh(page)"></vxe-button>
        </template>
      </vxe-grid>
    </main>
    <footer class="flex-none">
      <vxe-pager
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :layouts="['Home', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
      />
    </footer>
  </div>
</template>
<style scoped lang="scss">
.page-container {
  padding: 0 24px;
  max-height: var(--page-main-container);
}
.date-range-container {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;

  .vxe-input {
    flex: 1;
    min-width: 0;
  }

  .date-separator {
    color: #666;
    font-size: 14px;
    font-weight: 500;
    white-space: nowrap;
    padding: 0 8px;
  }
}
</style>
