<template>
  <el-dialog v-model="show" title="新建报告" @close="dialogClose">
    <el-form label-width="120px">
      <el-form-item label="报告所属渠道" required>
        <el-select
          v-model="state.channelId"
          filterable
          @change="getChannelMedicalDate"
        >
          <el-option
            v-for="(item, index) in channelList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报告名称" required>
        <el-input v-model="state.name" placeholder="请输入报告名称"></el-input>
      </el-form-item>
      <el-form-item label="报告体检日期" required>
        <div>
          <el-date-picker
            v-model="date"
            type="daterange"
            value-format="YYYY-MM-DD"
            placeholder="请选择"
            :disabled-date="disabledDate"
            :disabled="!state.minDate || !state.maxDate"
          />
        </div>
      </el-form-item>
      <!-- <el-form-item label="忽略报告编号">
        <el-select
          v-model="state.ignoreMedicalIds"
          :disabled="!state.channelId || !date.length"
          multiple
          filterable
        >
          <el-option
            v-for="(item, index) in reportList"
            :key="index"
            :label="item.sn"
            :value="item.sn"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="单位名称" required>
        <el-input v-model="state.groupName"></el-input>
      </el-form-item>
      <el-form-item label="报告日期" required>
        <div>
          <el-date-picker
            v-model="state.date"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="state.isAnalyzeDepartment"
          >进行部门级数据分析</el-checkbox
        >
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="createReport">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { watch } from "vue";
import { ref, computed } from "vue";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { request } from "@/utils";
const props = defineProps({
  channelList: {
    type: Array,
    default: []
  },
  visible: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["update:visible", "confirm"]);
const show = computed({
  get() {
    return props.visible;
  },
  set(v) {
    emit("update:visible", v);
  }
});

const state = ref({
  minDate: "",
  maxDate: "",
  channelId: "",
  ignoreMedicalIds: [],
  name: "",
  groupName: "",
  date: "",
  isAnalyzeDepartment: false
});

const dialogClose = () => {
  state.value = {
    minDate: "",
    maxDate: "",
    channelId: "",
    ignoreMedicalIds: [],
    name: "",
    groupName: "",
    date: "",
    isAnalyzeDepartment: false
  };
};
const channelMedicalDetail = ref()
const getChannelMedicalDate = async () => {
  const { data } = await request.get(
    `/idcService/mechanism/channelMedicalReport/getMedicalDataList`,
    {
      params: {
        channelId: state.value.channelId
      }
    }
  );
  if (!data.detail.minDate || !data.detail.maxDate) {
    return ElMessage.error("该渠道没有可分析报告");
  }
  channelMedicalDetail.value = data.detail
  state.value.minDate = dayjs(
    new Date(data.detail.minDate.replace(/-/g, "/"))
  ).format("YYYY-MM-DD");
  state.value.maxDate = dayjs(
    new Date(data.detail.maxDate.replace(/-/g, "/"))
  ).format("YYYY-MM-DD");
  date.value = [
    dayjs(state.value.minDate).format("YYYY-MM-DD"),
    dayjs(state.value.maxDate).format("YYYY-MM-DD")
  ];
};

const disabledDate = time => {
  return (
    time.getTime() < state.value.minDate || time.getTime() > state.value.maxDate
  );
};
const date = ref([
  dayjs(new Date()).format("YYYY-MM-DD"),
  dayjs(new Date()).format("YYYY-MM-DD")
]);
watch(
  () => date.value,
  () => {
    if (date.value?.length && date.value[0]) {
      state.value.minDate = date.value[0];
      state.value.maxDate = date.value[1];
    }
  },
  {
    immediate: true
  }
);
const fetchChannelList = ref([]);
const channelList = computed(() => {
  return props.channelList?.length ? props.channelList : fetchChannelList.value;
});

const getChannelList = async () => {
  if (!props.channelList.length) return;
  const { data } = await request.get(
    "/archivesService/mechanism/channel/paginate",
    {
      params: {
        pageSize: 9999
      }
    }
  );
  fetchChannelList.value = data.list;
};
getChannelList();
let lock = false
const createReport = async () => {
  if (!channelMedicalDetail.value?.medicalDataList.length) {
    return ElMessageBox.confirm('您设置的体检日期下无任何报告，请检查后重新设置', '提示')
  }
  if (channelMedicalDetail.value?.medicalDataList.filter(v => v.status <= 4).length) {
    return ElMessageBox.confirm('您选择的体检日期范围下有报告还未确认，无法分析', '提示')
  }
  await ElMessageBox.confirm(`您本次选中了${channelMedicalDetail.value?.archivesIds.length}人，共${channelMedicalDetail.value?.medicalDataList.length}份报告，确定要开始分析吗? `, '提示')
  console.log(channelMedicalDetail.value)
  if (lock) return;
  lock = true
  const req = {
    ...state.value
  };

  // req.medicalDataIds = reportList.value
  //   .filter(v => !state.value.ignoreMedicalIds.includes(v.sn))
  //   .map(v => v.sn);
  try {
    await request.post(`/idcService/mechanism/channelMedicalReport/create`, req);
    ElMessage.success("创建成功");
    show.value = false;
    emit("confirm");
  } catch (e) {
    ElMessage.error(e.message)
  } finally {
    lock = false
  }
};
</script>

<style lang="scss" scoped></style>
