<script setup lang="ts">
import type { PlanModel } from '@/model/system.model';
import {  tagMethod } from '@/request/api/system.api';
import { message, notification } from 'ant-design-vue';
import {
  doctorMethod,
  departmentsMethod,
  planEditMethod,
  allTagsSearchMethod,
} from '@/request/api/follow.api';
import { useRequest } from 'alova/client';
import {
  type VxeFormListeners,
  type VxeFormProps,
  VxeUI,
  type VxeFormInstance,
} from 'vxe-pc-ui';
import { list2Groups } from '@/tools/data';
(notification.config as any)({
  zIndex: 10000, // 直接设置层级
});
type FollowModel = Partial<PlanModel>;

const defaultModel = {};

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

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

const { loading, send: load } = useRequest(tagMethod, {
  immediate: false,
  initialData: props.data ?? defaultModel,
}).onSuccess(({ data }) => {
  formProps.data = { ...data };
});
const { loading: submitting, send: submit } = useRequest(planEditMethod, {
  immediate: false,
}).onSuccess(({ data }) => {
  emits('submit');
});
// 获取就诊医生
const { data: doctorData, loading: doctorDataLoading } = useRequest(doctorMethod, {
  initialData: { total: 0, data: [] },
});
// 获取就诊科室
const { data: departmentsData, loading: depDataLoading } = useRequest(departmentsMethod, {
  initialData: { total: 0, data: [] },
});
// 获取患者标签
const { data: tagData, loading: tagDataLoading } = useRequest(allTagsSearchMethod, {
  initialData: { total: 0, data: [] },
});

// 第一步 填写随访计划
const formProps = reactive<VxeFormProps<FollowModel>>({
  titleWidth: 110,
  titleAlign: 'right',
  titleBold: true,
  titleColon: true,
  data: { ...props.data, frequency: props.data?.frequency ? props.data.frequency : 1 },
  // data:{frequency:1},
  items: [
    {
      field: 'name',
      title: '计划名称',
      span: 24,
      itemRender: { name: 'VxeInput', props: { placeholder: '请输入随访计划名称' } },
    },
    {
      field: 'startDate',
      title: '开始日期',
      span: 24,
      itemRender: { name: 'VxeDatePicker', props: { placeholder: '请选择开始时间' } },
    },
    {
      field: 'endDate',
      title: '截止日期',
      span: 24,
      itemRender: { name: 'VxeDatePicker', props: { placeholder: '请选择截止时间' } },
    },
    {
      field: 'purpose',
      title: '随访目的',  
      span: 24,
      itemRender: { name: 'VxeInput', props: { placeholder: '请编辑随访目的' } },
    },
    {
      field: 'arrangeTime',
      align: 'center',
      title: '随访推送时间',
      span: 24,
      slots: { default: 'pushTime' },
    },
    { field: 'frequency', title: '随访次数', span: 24, slots: { default: 'followTimes' } },
    { field: 'secondTimes', title: '', span: 24, slots: { default: 'secondTimes' } },
    {
      field: 'remindTime',
      align: 'center',
      title: '患者未填写，重复提醒时间',
      span: 24,
      slots: { default: 'remindTime' },
    },
    { align: 'center', span: 24, slots: { default: 'active' } },
  ],
  rules: {
    name: [{ required: true, message: '请输入计划名称' }],
    startDate: [{ required: true, message: '请选择开始日期' }],
    endDate: [{ required: true, message: '请选择截止日期' }],
  },
});

function formCheck(data) {
  if (new Date(data?.endDate) < new Date(data?.startDate)) {
    notification.warning({
      message: '结束日期不能晚于开始日期',
    });
    return;
  }
  if (!data.arrangeTime) {
    notification.warning({
      message: '请选择随访推送时间！',
    });
    return;
  }
  if (!data.remindTime) {
    notification.warning({
      message: '请选择提醒时间！',
    });
    return;
  }
  if (compareTime(data.remindTime, data.arrangeTime)) {
    notification.warning({
      message: '推送时间不能晚于提醒时间',
    });
    return;
  }
  current.value++;
}

const arrangeTime = ref<string>('');
const remindTime = ref<string>('');
const follow = shallowRef<PlanModel>();
const frequencyArr = ref<any[]>([]);
const formEmits: VxeFormListeners<PlanModel> = {
  submit({ data }) {
    if (!arrangeTime.value) {
      data.arrangeTime = currentPushTime.value;
    } else {
      data.arrangeTime = arrangeTime.value;
    }
    if (remindTime.value) {
      data.remindTime = remindTime.value;
    }

    frequencyArr.value = [];
    if (followTimesArr.value.length > 0) {
      followTimesArr.value.forEach((item) => frequencyArr.value.push(item.data));
      data.frequencyDays = frequencyArr.value?.join(',');
    }
    formCheck(data);
    follow.value = { ...data };
  },
};
// 第二步 填写筛选病人表单
const patientsForm = reactive<VxeFormProps<PlanModel['filter']>>({
  titleWidth: 110,
  titleAlign: 'right',
  titleBold: true,
  titleColon: true,
  data: { ...props.data?.filter },
  items: [
    {
      field: 'tagIds',
      title: '患者标签',
      span: 24,
      itemRender: {
        name: 'VxeSelect',
        props: {
          placeholder: '患者标签',
          loading: tagDataLoading,
          optionGroups: computed(() =>
            list2Groups(
              tagData.value.data.filter((tag) => !tag.disabled),
              'category',
              (key) => ({ 1: '系统标签', 2: '个人标签' })[key]!
            )
          ),
          optionProps: { value: 'id', label: 'name' },
          optionGroupProps: { options: 'groups' },
          clearable: true,
          multiple: true,
          filterable: true,
        },
      },
    },
    {
      field: 'departments',
      title: '就诊科室',
      span: 24,
      itemRender: {
        name: 'VxeSelect',
        props: {
          loading: depDataLoading,
          options: computed(() => departmentsData.value.departmentsData),
          optionProps: { value: 'name', label: 'name' },
          clearable: true,
          multiple: true,
          filterable: true,
        },
      },
    },
    {
      field: 'doctors',
      title: '就诊医生',
      span: 24,
      itemRender: {
        name: 'VxeSelect',
        props: {
          loading: doctorDataLoading,
          options: computed(() => doctorData.value.doctorData),
          optionProps: { value: 'name', label: 'name' },
          clearable: true,
          multiple: true,
          filterable: true,
        },
      },
    },
    { align: 'center', span: 24, slots: { default: 'patientsBtn' } },
  ],
});
const tagNames = ref<any[]>([]);
const submitData = ref({});
const patientsEmits: VxeFormListeners<PlanModel['filter']> = {
  async submit({ data }) {
    if (data?.tagIds?.length > 0) {
      const tagMap = new Map(tagData.value?.data?.map(tag => [tag.id, tag.name]) || []);
      
      const tagIds = Array.isArray(data.tagIds) ? data.tagIds : [data.tagIds];
      tagNames.value = tagIds
        .map(tagId => tagMap.get(tagId))
        .filter(Boolean); // 过滤掉 undefined 值
    } else {
      tagNames.value = [];
    }
    const tagIdsArr = Array.isArray(data.tagIds)
      ? data.tagIds
      : data.tagIds
        ? [data.tagIds]
        : [];
    const filterPayload = {
      ...data,
      tagIds: tagIdsArr,
      tagNames: tagNames.value,
    };
    submitData.value = { ...formProps.data, filter: filterPayload };
    await submit(submitData.value);
    // 关闭弹窗
    VxeUI.modal.close(`plan-modal`);
  },
};

// 步骤条样式
const stepStyle = {
  width: '100%',
  marginBottom: '20px',
  boxShadow: '0px -1px 0 0 #e8e8e8 inset',
};
// 点击下一步
const current = ref<number>(0);

onBeforeMount(() => {
  changeFrequency();
});

const timeArr = Array.from({ length: 16 }, (_, i) =>
  i + 6 >= 10 ? `${6 + i}:00` : `0${6 + i}:00`
);

// 随访计划填写取消
function cancel() {
  VxeUI.modal.close(`plan-modal`);
}

const followTimesArr = ref<any[]>([]);

function changeFrequency() {
  const length = followTimesArr.value.length;
  const diff = (formProps.data?.frequency ?? 0) - length;
  if (diff > 0) {
    for (var i = 0; i < diff; i++) {
      followTimesArr.value.push({
        field: 'secondTimes',
        title: `第${length + i + 1}随访时间`,
        span: 8,
        slots: { default: 'secondTimes' },
        data: formProps?.data?.frequencyDays?.split(',')[i]
          ? formProps?.data?.frequencyDays?.split(',')[i]
          : props.data?.frequency === undefined
            ? length + i + 1
            : 1,
      });
    }
  } else {
    followTimesArr.value = followTimesArr.value.slice(0, formProps.data?.frequency);
  }
}

function compareTime(t1, t2) {
  var date = new Date();
  var a = t1.split(':');
  var b = t2.split(':');
  return date.setHours(a[0], a[1]) < date.setHours(b[0], b[1]);
}

const form1 = ref<VxeFormInstance>();

// 点击下一步
function changeStep(currentStep) {
  // debugger
  if (currentStep === 1) {
    if (arrangeTime.value) {
      formProps.data.arrangeTime = arrangeTime.value;
    }
    if (remindTime.value) {
      formProps.data.remindTime = remindTime.value;
    }
    form1.value?.validate().then((haveValidate) => {
      if (haveValidate) {
        current.value = 0;
      } else {
        if (new Date(formProps?.data?.endDate) < new Date(formProps?.data?.startDate)) {
          message.error('结束日期不能晚于开始日期');
          current.value = 0;
          return;
        }
        if (!formProps.data.arrangeTime) {
          message.error('请选择随访推送时间！');
          current.value = 0;
          return;
        }
        if (!formProps.data.remindTime) {
          message.error('请选择提醒时间！');
          current.value = 0;
          return;
        }
        if (compareTime(formProps.data.remindTime, formProps.data.arrangeTime)) {
          message.error('推送时间不能晚于提醒时间');
          current.value = 0;
          return;
        }
        
        // 验证通过后，保存第一步的数据到 follow.value
        follow.value = { ...formProps.data };
      }
    });
  }
}

// 推送时间
const currentPushTime = ref<string>(timeArr[0]);

function selectPushTime(item, pushIndex) {
  arrangeTime.value = item;
  currentPushTime.value = item;
}

// 提醒时间
const currentRemindTime = ref<string>();

function selectRemindTime(item, remindIndex) {
  remindTime.value = item;
  currentRemindTime.value = item;
}
onMounted(() => {
  if(formProps.data.arrangeTime){
    currentPushTime.value = formProps.data.arrangeTime;
  }
})  
</script>
<template>
  <div>
    <a-steps
      @change="changeStep"
      v-model:current="current"
      size="small"
      :style="stepStyle"
      type="navigation"
      :items="[
        {
          title: '填写随访计划',
        },
        {
          title: '筛选病人',
        },
      ]"
    >
    </a-steps>
  </div>
  <vxe-form
    v-bind="formProps"
    v-on="formEmits"
    :loading
    v-show="current != 1"
    class="flex flex-col"
    ref="form1"
  >
    <template #active="{ data }">
      <vxe-button
        type="submit"
        status="primary"
        content="下一步"
        :loading="submitting"
      ></vxe-button>
    </template>

    <template #followTimes>
      <div class="flex items-center">
        <vxe-input
          type="integer"
          v-model="formProps.data!.frequency"
          @change="changeFrequency"
          min="1"
        ></vxe-input>
        <div class="ml-3">次</div>
      </div>
    </template>

    <template #secondTimes>
      <div class="flex items-center mb-3" v-for="item in followTimesArr" :key="item.title">
        <div style="width: 110px" class="flex justify-end pr-1 font-bold">{{ item.title }}：</div>
        <div class="mr-2">就诊后第</div>
        <div>
          <vxe-input type="integer" min="0" v-model="item.data"></vxe-input>
        </div>
        <div class="ml-3">天</div>
      </div>
    </template>
    <!--随访推送时间-->
    <template #pushTime>
      <div class="flex flex-wrap border border-solid border-gray-200">
      
        <div
          class="flex-none border border-solid border-gray-200 text-xs"
          style="width: 25%; height: 50px; line-height: 50px"
          v-for="(pushTime, pushIndex) in timeArr"
          :key="pushTime"
          @click="selectPushTime(pushTime, pushIndex)"
          :class="
           currentPushTime === pushTime
              ? 'bg-blue color-white'
              : ''
          "
        >
          {{ pushTime }}
        </div>
      </div>
    </template>
    <!--重复提醒时间-->
    <template #remindTime="{ data }">
      <div class="flex flex-wrap border border-solid border-gray-200">
        <div
          class="flex-none border border-solid border-gray-200 text-xs"
          style="width: 25%; height: 50px; line-height: 50px"
          v-for="(remindTime, remindIndex) in timeArr"
          :key="remindTime"
          @click="selectRemindTime(remindTime, remindIndex)"
          :class="
            (currentRemindTime ? currentRemindTime : data.remindTime) === remindTime
              ? 'bg-blue color-white'
              : ''
          "
        >
          {{ remindTime }}
        </div>
      </div>
    </template>
  </vxe-form>

  <!--筛选病人  -->
  <vxe-form v-bind="patientsForm" v-on="patientsEmits" :loading v-show="current === 1">
    <template #patientsBtn>
      <div class="tips">请按照需求选择纳入随访的病人</div>
      <vxe-button
        content="取消"
        :loading="submitting"
        name="cancel"
        class="mr-2"
        @click="cancel"
      ></vxe-button>
      <vxe-button type="submit" content="完成" :disabled="submitting" status="primary"></vxe-button>
    </template>
  </vxe-form>
</template>
<style scoped lang="scss">
.tips {
  text-align: center;
  margin: 40px auto 100px auto;
  font-weight: bold;
  font-size: 14px;
}

.mesh-grid {
  border-collapse: collapse;
}

.mesh-grid td {
  border: 1px solid black;
  width: 100px;
  padding: 20px 20px;
  text-align: center;
}
</style>
