<template>
  <j-modal :title="title" :width="720" :visible="visible" @ok="handleOk" @cancel="handleCancel" cancelText="取消">
    <a-form :model="formData" :label-col="{ style: { width: '120px' } }" :wrapper-col="{ span: 16 }">
      <a-form-item label="发起类型">
        <a-radio-group v-model:value="formData.triggerMode">
          <a-radio value="immediate">立即发起</a-radio>
          <a-radio value="recurring">重复发起</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="deptOptions.length" label="牵头部门">
        <a-select
          v-model:value="formData.deptIds"
          mode="multiple"
          :options="deptOptions"
          placeholder="请选择牵头部门"
          allow-clear
          style="width: 100%"
          :getPopupContainer="(node) => node?.parentNode"
        />
      </a-form-item>

      <a-form-item v-if="showDeadlineField" label="事项截止时间">
        <a-date-picker
          v-model:value="formData.deadline"
          valueFormat="YYYY-MM-DD"
          placeholder="请选择事项截止时间"
          style="width: 100%"
          :getPopupContainer="(node) => node?.parentNode"
        />
      </a-form-item>

      <template v-if="showSuoleaderFields">
        <a-form-item label="是否所党委审批">
          <j-switch v-model:value="formData.isNeedAppro" />
        </a-form-item>

        <a-form-item label="所党委领导">
          <a-input
            v-model:value="supDeptleaderName"
            placeholder="请选择所党委领导"
            :disabled="String(formData.isNeedAppro) !== '1'"
            readonly
            allow-clear
            @click="openSdwLeaderModal"
            @clear="handleClearSdwLeader"
          >
            <template #suffix>
              <SearchOutlined @click="openSdwLeaderModal" />
            </template>
          </a-input>
          <SzUserSelectByDeptRoleSecurityModal
            v-model:open="sdwLeaderModalOpen"
            title="请选择所党委领导"
            :deptId="sdwLeaderDeptId"
            :roleId="sdwLeaderRoleId"
            :securityValue="sdwLeaderSecurityValue"
            @confirm="handleSdwLeaderConfirm"
          />
        </a-form-item>
      </template>

      <template v-if="formData.triggerMode === 'recurring'">
        <a-form-item label="重复周期">
          <JDictSelectTag
            v-model:value="formData.intervalType"
            dictCode="sup_interval_type"
            placeholder="重复周期"
            :getPopupContainer="(node) => node?.parentNode"
          />
        </a-form-item>

        <a-form-item label="重复次数">
          <a-input-number v-model:value="formData.startCount" :min="1" :precision="0" placeholder="重复次数" style="width: 100%" />
        </a-form-item>

        <a-form-item label="重复开始日期">
          <a-date-picker
            v-model:value="formData.intervalStartTime"
            show-time
            valueFormat="YYYY-MM-DD HH:mm:ss"
            placeholder="重复开始日期"
            style="width: 100%"
            :getPopupContainer="(node) => node?.parentNode"
          />
        </a-form-item>
      </template>
    </a-form>

    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk">提交</a-button>
    </template>
  </j-modal>
</template>

<script lang="ts" setup>
  import { reactive, ref, watch } from 'vue';
  import JModal from '/src/components/Modal/src/JModal/JModal.vue';
  import JDictSelectTag from '/src/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSwitch from '/src/components/Form/src/jeecg/components/JSwitch.vue';
import { PARTY_COMMITTEE_DEPT_ID, SDW_LEADER_ROLE_ID } from '/@/constant/supervision';
  import SzUserSelectByDeptRoleSecurityModal from '/src/components/semri/userComponent/modal/SzUserSelectByDeptRoleSecurityModal.vue';
  import { SearchOutlined } from '@ant-design/icons-vue';
  import { getUserList } from '/src/api/common/api';
  import { useMessage } from '/src/hooks/web/useMessage';

  interface ModalPayload {
    title?: string;
    payload?: Record<string, any>;
    deptOptions?: DeptOption[];
    showSuoleaderFields?: boolean;
    isNeedAppro?: string | number;
    supDeptleaderid?: string | string[];
    supDeptleaderName?: string;
    showDeadlineField?: boolean;
    deadline?: string | Date;
  }

  interface DeptOption {
    label: string;
    value: string;
  }

  const emit = defineEmits(['confirm']);
  const { createMessage } = useMessage();

  const title = ref('发起流程');
  const visible = ref(false);
  const contextData = ref<Record<string, any>>({});
  const deptOptions = ref<DeptOption[]>([]);
  const showSuoleaderFields = ref(false);
  const showDeadlineField = ref(false);

  // 所党委领导选人弹窗
  const sdwLeaderModalOpen = ref(false);
  const supDeptleaderName = ref('');
  const sdwLeaderDeptId = ref(PARTY_COMMITTEE_DEPT_ID);
  const sdwLeaderRoleId = ref(SDW_LEADER_ROLE_ID);
  const sdwLeaderSecurityValue = ref(5);

  function openSdwLeaderModal() {
    if (String(formData.isNeedAppro) !== '1') return;
    sdwLeaderModalOpen.value = true;
  }

  function handleClearSdwLeader() {
    formData.supDeptleaderid = '';
    supDeptleaderName.value = '';
  }

  function handleSdwLeaderConfirm(rows: Array<{ id: string; realname: string }>) {
    if (rows && rows.length > 0) {
      formData.supDeptleaderid = rows.map((r) => r.username).join(',');
      supDeptleaderName.value = rows.map((r) => r.realname).join(',');
    } else {
      formData.supDeptleaderid = '';
      supDeptleaderName.value = '';
    }
  }

  async function resolveSdwLeaderNames(ids: string) {
    try {
      const res = await getUserList({ username: ids, pageSize: 999 });
      const records = res?.records || res?.result?.records || [];
      supDeptleaderName.value = records.map((u: any) => u.realname).join(',');
    } catch {
      supDeptleaderName.value = '';
    }
  }

  const formData = reactive({
    triggerMode: 'immediate',
    intervalType: undefined as number | string | undefined,
    startCount: undefined as number | undefined,
    intervalStartTime: undefined as string | undefined,
    deptIds: [] as string[],
    isNeedAppro: '0',
    supDeptleaderid: '' as string | string[],
    deadline: undefined as string | undefined,
  });

  function resetForm() {
    formData.triggerMode = 'immediate';
    formData.intervalType = undefined;
    formData.startCount = undefined;
    formData.intervalStartTime = undefined;
    formData.deptIds = [];
    formData.isNeedAppro = '0';
    formData.supDeptleaderid = '';
    supDeptleaderName.value = '';
    formData.deadline = undefined;
    deptOptions.value = [];
    showSuoleaderFields.value = false;
    showDeadlineField.value = false;
  }

  function normalizeDeptOptions(options: DeptOption[] = []) {
    const optionMap = new Map<string, DeptOption>();
    options.forEach((item) => {
      const value = String(item?.value || '').trim();
      if (!value || optionMap.has(value)) {
        return;
      }
      optionMap.set(value, {
        value,
        label: item?.label || value,
      });
    });
    return Array.from(optionMap.values());
  }

  function normalizeDeadlineValue(value?: string | Date) {
    if (!value) {
      return undefined;
    }
    if (typeof value === 'string') {
      return value.length >= 10 ? value.substring(0, 10) : value;
    }
    const year = value.getFullYear();
    const month = String(value.getMonth() + 1).padStart(2, '0');
    const day = String(value.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  function open(data: ModalPayload = {}) {
    resetForm();
    title.value = data.title || '发起流程';
    contextData.value = data.payload || {};
    deptOptions.value = normalizeDeptOptions(data.deptOptions || []);
    formData.deptIds = deptOptions.value.map((item) => item.value);
    showSuoleaderFields.value = !!data.showSuoleaderFields;
    formData.isNeedAppro = String(data.isNeedAppro ?? '0');
    formData.supDeptleaderid = data.supDeptleaderid || '';
    supDeptleaderName.value = data.supDeptleaderName || '';
    if (!supDeptleaderName.value && formData.supDeptleaderid) {
      resolveSdwLeaderNames(formData.supDeptleaderid as string);
    }
    showDeadlineField.value = !!data.showDeadlineField;
    formData.deadline = normalizeDeadlineValue(data.deadline);
    if (String(formData.isNeedAppro) !== '1') {
      formData.supDeptleaderid = '';
    }
    visible.value = true;
  }

  function handleCancel() {
    visible.value = false;
  }

  function handleOk() {
    if (formData.triggerMode === 'recurring') {
      if (!formData.intervalType) {
        createMessage.warning('Please select interval type');
        return;
      }
      if (!formData.startCount) {
        createMessage.warning('Please input repeat count');
        return;
      }
      if (!formData.intervalStartTime) {
        createMessage.warning('Please select start time');
        return;
      }
    }
    if (deptOptions.value.length && !formData.deptIds.length) {
      createMessage.warning('请选择责任部门');
      return;
    }

    if (showDeadlineField.value && !formData.deadline) {
      createMessage.warning('请选择事项截止时间');
      return;
    }

    emit('confirm', {
      payload: contextData.value,
      options: {
        triggerType: formData.triggerMode === 'recurring' ? 2 : 1,
        intervalType: formData.triggerMode === 'recurring' ? Number(formData.intervalType) : undefined,
        startCount: formData.triggerMode === 'recurring' ? Number(formData.startCount) : undefined,
        intervalStartTime: formData.triggerMode === 'recurring' ? formData.intervalStartTime : undefined,
        deptId: formData.deptIds.join(','),
        deptIds: [...formData.deptIds],
        isNeedAppro: showSuoleaderFields.value ? formData.isNeedAppro : undefined,
        supDeptleaderid: showSuoleaderFields.value ? (String(formData.isNeedAppro) === '1' ? formData.supDeptleaderid : '') : undefined,
        deadline: showDeadlineField.value ? formData.deadline : undefined,
      },
    });
    handleCancel();
  }

  watch(
    () => formData.isNeedAppro,
    (value) => {
      if (String(value) !== '1') {
        formData.supDeptleaderid = '';
        supDeptleaderName.value = '';
      }
    }
  );

  defineExpose({
    open,
  });
</script>
