<script setup lang="ts">
import { VxeUI, type VxeFormProps, type VxeFormListeners } from 'vxe-pc-ui';
import { useRequest } from 'alova/client';
import { branchMethod } from '@/request/api/system.api';
import { notification } from 'ant-design-vue';
import type { EquirementModel } from '@/model/device.model';
type FollowModel = Partial<EquirementModel>;
  (notification.config as any)({
  zIndex: 10000, // 直接设置层级
});
const defaultModel = {};

const props = defineProps<{ data: FollowModel }>();

const emits = defineEmits<{
  submit: [data?: EquirementModel];
}>();

const model = ref<EquirementModel>({ ...defaultModel });

watchEffect(() => {
  if (props.data) {
    model.value = { ...defaultModel, ...props.data };
  }
});
// 获取组织名称
const branch = ref<any[]>([]);
const { loading: branchLoading } = useRequest(branchMethod(0, 1, 1)).onSuccess(({ data }) => {
  const to = (data?: any[]): any[] => {
    return Array.isArray(data)
      ? data.map((item) => {
          return {
            ...item,
            value: item.id,
            key: item.id.toString(),
            children: to(item.children),
          };
        })
      : [];
  };
  branch.value = to(data);
});
// 获取机构名称
const insArr = ref<any[]>([]);
const insLoading = ref(false);
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;
}
const showDept = ref(false);
watch(
  () => model.value.orgId,
  async (newVal) => {
    showDept.value = !!newVal;
    if (showDept.value) {
      // 请求获取机构
      getInstitution(newVal ?? '');
    }
    if (!newVal || newVal !== model.value.institutionId) {
      model.value.institutionId = ''; // 或者 ''
    }
  }
);
// 表单配置
const formItems = computed(() => {
  const items = [
    {
      field: 'orgId',
      title: '组织修改为',
      span: 24,
      itemRender: {
        name: 'VxeSelect',
        props: {
          placeholder: '请选择',
          options: computed(() => branch.value), // 组织列表
          optionProps: {
            value: 'value', // 组织id
            label: 'label', // 组织名称
          },
          clearable: true,
        },
      },
    },
  ];

  // 只有当选择了组织后才添加机构字段
  if (model.value.orgId) {
    items.push({
      field: 'institutionId',
      title: '机构修改为',
      span: 24,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          placeholder: '请选择',
          options: computed(() => insArr.value),
          optionProps: { value: 'id', label: 'label' },
          clearable: true,
        },
      },
    });
  }

  items.push(
    {
      field: 'devices',
      title: '',
      span: 24,
      slots: {
        default: 'devicesSlot',
      },
    },
    { align: 'center', span: 24, slots: { default: 'active' } }
  );

  return items;
});

const formProps = reactive<VxeFormProps>({
  // titleWidth: 120,
  titleAlign: 'right',
  titleColon: true,
  data: computed(() => model.value),
  items: formItems,
});

const formEmits: VxeFormListeners = {
  submit({ data }) {
    if (!data?.orgId) {
      notification.error({ message: '请选择需要修改的组织' });
      return;
    }
    if (!data?.institutionId) {
      notification.error({ message: '请选择需要修改的机构' });
      return;
    }
    // const selectedOrg = branch.value.find((item) => item.value === model.value.orgId);

    emits('submit', {
      orgId: data?.orgId,
      institutionId: data?.institutionId,
    } as any);
    // 或者先调接口再 emit
  },
};

// 取消
function cancel() {
  VxeUI.modal.close('import-organization');
}
const submitting = ref(false);
</script>

<template>
  <div class="form-container">
    <vxe-form v-bind="formProps" v-on="formEmits" :loading="submitting">
      <template #devicesSlot>
        <div class="devices-section">
          <div class="section-title">待修改设备</div>
          <div class="table-container">
            <table class="devices-table">
              <thead>
                <tr>
                  <th>设备ID</th>
                  <th>原组织</th>
                  <th>原机构</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(device, index) in props.data" :key="index">
                  <td>{{ device?.deviceCode }}</td>
                  <td>{{ device?.orgName }}</td>
                  <td>{{ device?.institutionName }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </template>

      <template #active>
        <div class="button-container">
          <vxe-button content="取消" :disabled="submitting" @click="cancel"></vxe-button>
          <vxe-button type="submit" status="warning" content="确定" :loading="submitting"></vxe-button>
        </div>
      </template>
    </vxe-form>
  </div>
</template>

<style scoped lang="scss">
.form-container {
  padding: 20px;
}

.devices-section {
  margin-top: 20px;

  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
  }

  .table-container {
    border: 1px solid #e8e8e8;
    border-radius: 6px;
    overflow: hidden;

    .devices-table {
      width: 100%;
      border-collapse: collapse;
      background-color: #fff;

      thead {
        background-color: #fafafa;

        th {
          padding: 12px 16px;
          text-align: left;
          font-weight: 500;
          color: #333;
          border-bottom: 1px solid #e8e8e8;
          font-size: 14px;
        }
      }

      tbody {
        tr {
          border-bottom: 1px solid #f0f0f0;

          &:last-child {
            border-bottom: none;
          }

          td {
            padding: 12px 16px;
            color: #666;
            font-size: 14px;
          }
        }
      }
    }
  }
}

.button-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 30px;
  padding-top: 20px;

  .vxe-button {
    min-width: 80px;
    height: 36px;
    font-size: 14px;
    border-radius: 6px;

    &:first-child {
      background-color: #fff;
      border: 1px solid #d9d9d9;
      color: #666;

      &:hover {
        border-color: #40a9ff;
        color: #40a9ff;
      }
    }

    &:last-child {
      background-color: #fa8c16;
      border: 1px solid #fa8c16;
      color: #fff;

      &:hover {
        background-color: #ff9c2a;
        border-color: #ff9c2a;
      }

      &:disabled {
        background-color: #f5f5f5;
        border-color: #d9d9d9;
        color: #bfbfbf;
      }
    }
  }
}
</style>
