<template>
  <div>
    <template v-if="!hideTrigger">
      <a-input
        v-if="triggerMode === 'input'"
        :value="selectedUser ? selectedUser.realname : ''"
        placeholder="请选择人员"
        readonly
        style="width: 100%; cursor: pointer"
        @click="openModal()"
      >
        <template v-if="selectedUser" #suffix>
          <CloseCircleOutlined @click.stop="handleClear" style="color: rgba(0,0,0,0.45)" />
        </template>
      </a-input>
      <a-row v-else class="j-select-row" type="flex" :gutter="8">
        <a-col class="left">
          <a-input
            :value="selectedUser ? selectedUser.realname : ''"
            placeholder="请选择人员"
            readonly
            @click="openModal()"
          >
            <template v-if="selectedUser" #suffix>
              <CloseCircleOutlined @click.stop="handleClear" style="color: rgba(0,0,0,0.45)" />
            </template>
          </a-input>
        </a-col>
        <a-col class="right">
          <a-button type="primary" @click="openModal()" :disabled="disabled">选择</a-button>
        </a-col>
      </a-row>
    </template>
    <a-modal
      :width="1000"
      :title="title"
      v-model:open="visible"
      centered
      :destroyOnClose="true"
      :okButtonProps="{ disabled: !tempSelectedUser }"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <SzSingleDeptUserSelect
        ref="selectRef"
        :departId="innerDepartId"
        :secLevel="secLevel"
        :role="role"
        :isSpecial="isSpecial"
        :checkedUser="tempSelectedUser"
        @select="onUserSelect"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useUserStore } from '/@/store/modules/user';
import { CloseCircleOutlined } from '@ant-design/icons-vue';
import SzSingleDeptUserSelect from '/@/components/semri/singleDeptUserComponent/SzSingleDeptUserSelect.vue';
import type { UserItem } from './types';

const props = withDefaults(
  defineProps<{
    value?: string;
    departId?: string;
    secLevel?: any;
    role?: string | number;
    isSpecial?: number;
    disabled?: boolean;
    valueKey?: 'id' | 'username';
    title?: string;
    hideTrigger?: boolean;
    triggerMode?: 'button' | 'input';
  }>(),
  {
    value: '',
    departId: '',
    secLevel: 0,
    role: 1,
    isSpecial: 0,
    disabled: false,
    valueKey: 'username',
    title: '选择人员',
    hideTrigger: false,
    triggerMode: 'button',
  }
);

const emit = defineEmits(['update:value', 'change', 'confirm']);

const userStore = useUserStore();
const selectRef = ref();
const visible = ref(false);
const selectedUser = ref<UserItem | null>(null);
const tempSelectedUser = ref<UserItem | null>(null);

const innerDepartId = computed(() => {
  return props.departId || userStore.getUserInfo?.orgCode || '';
});

watch(
  () => props.value,
  (newVal) => {
    if (newVal) {
      loadUserByKey(newVal);
    } else {
      selectedUser.value = null;
    }
  },
  { immediate: true }
);

async function loadUserByKey(valueStr: string) {
  try {
    const paramKey = props.valueKey === 'id' ? 'id' : 'username';
    const res: any = await defHttp.get({
      url: '/sys/user/queryUserComponentData',
      params: { [paramKey]: valueStr, pageNo: 1, pageSize: 9999 },
    });
    const users = (res.records || res).filter((u: UserItem) => !u.username.toLowerCase().includes('admin'));
    selectedUser.value = users.length > 0 ? users[0] : null;
  } catch {
    selectedUser.value = null;
  }
}

function handleClear() {
  selectedUser.value = null;
  emit('update:value', '');
  emit('change', '');
}

function openModal() {
  if (props.disabled) return;
  tempSelectedUser.value = selectedUser.value ? { ...selectedUser.value } : null;
  visible.value = true;
}

function onUserSelect(user: UserItem | null) {
  tempSelectedUser.value = user;
}

function handleOk() {
  if (!tempSelectedUser.value) return;
  selectedUser.value = tempSelectedUser.value;
  const keyValue = selectedUser.value[props.valueKey];
  const nameValue = selectedUser.value.realname;
  emit('update:value', keyValue);
  emit('change', keyValue);
  emit('confirm', keyValue, nameValue);
  visible.value = false;
}

function handleCancel() {
  visible.value = false;
}
</script>

<style lang="less" scoped>
.j-select-row {
  @width: 82px;

  .left {
    width: calc(100% - @width - 8px);
  }

  .right {
    width: @width;
  }
}
</style>
