<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { postListTree } from "@/api/department";
import { addListApi, getPageList } from "@/api/indexData";
import { postOrganizationUserPage } from "@/api/userSetting";
import dayjs from "dayjs";

// 表单状态
const ruleFormRef = ref(null);
const form = reactive({
  sourceValue: "",
  deptCode: "",
  deptId: "",
  deptName: "",
  userId: "",
  userName: "",
  numerator: "",
  denominator: "",
  dataValue: "",
  specificTime: ""
});
const rules = reactive({
  sourceValue: [{ required: true, message: "请输入指标名称", trigger: "blur" }],
  deptCode: [{ required: true, message: "请选择部门名称", trigger: "change" }],
  specificTime: [{ required: true, message: "请选择日期", trigger: "change" }]
});

// 弹窗逻辑
const emit = defineEmits(["updateDialog"]);
const visible = ref(false);
const open = () => {
  // 打开弹框
  Object.assign(form, {
    sourceValue: "",
    deptCode: "",
    deptId: "",
    deptName: "",
    userId: "",
    userName: "",
    numerator: "",
    denominator: "",
    dataValue: "",
    specificTime: ""
  });
  visible.value = true;
  getPageListApi();
  getIndustryListApi();
};
defineExpose({
  open
});
const close = () => {
  visible.value = false;
  ruleFormRef.value.resetFields();
};

// 指标名称
const restaurants = ref([]);
const filterDuplicateSourceValues = arr => {
  const seen = new Map();
  return arr.filter(item => {
    const sourceValue = item.sourceValue;
    if (!seen.has(sourceValue)) {
      seen.set(sourceValue, true);
      return true;
    }
    return false;
  });
};
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value;
  cb(filterDuplicateSourceValues(results));
};
const createFilter = (queryString: string) => {
  return restaurant => {
    return restaurant.sourceValue.indexOf(queryString) === 0;
  };
};
const getPageListApi = async () => {
  const { code, data, msg } = await getPageList({
    pageNumber: 1,
    pageSize: 99999,
    sourceValue: "",
    deptName: "",
    userName: ""
  });
  if (code == 200) {
    if (data.records && data.records.length) {
      restaurants.value = data.records;
    } else {
      restaurants.value = [];
    }
  }
};

// 部门名称
const defaultProps = {
  children: "childrenRes",
  label: "deptName",
  value: "deptCode"
};
const deptSelect = ref([]);
const getIndustryListApi = async () => {
  const { code, data } = await postListTree();
  if (code == 200) {
    deptSelect.value = data || [];
  }
};
const handleNodeDeptClick = data => {
  form.deptId = data.hospitalCode;
  form.deptName = data.deptName;
};

// 员工名称
const userSelect = ref([]);
const handleDept = async val => {
  form.userId = "";
  form.userName = "";
  const { code, data, msg } = await postOrganizationUserPage({
    pageNumber: 1,
    pageSize: 99999,
    organizationCode: val,
    organizationType: "dept",
    realName: ""
  });
  if (code == 200) {
    userSelect.value = data.records;
  }
};
const handleUser = val => {
  userSelect.value.forEach(item => {
    if (item.hospitalCode === val) {
      form.userName = item.realName;
    }
  });
};

// 保存
const saveLoading = ref(false);
const addSave = async () => {
  ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      saveLoading.value = true;
      if (form.specificTime) {
        form.specificTime = dayjs(form.specificTime).valueOf();
        form.sourceTime = dayjs(form.specificTime).valueOf();
      }
      const { code, msg } = await addListApi(form);
      saveLoading.value = false;
      if (code === 200) {
        ElMessage({
          message: "添加成功",
          type: "success"
        });
        close();
        emit("updateDialog");
      }
    }
  });
};

// 数据时间，只能选每月第一天
const disabledFirstDayOfMonth = time => {
  const date = new Date(time);
  // 获取当前月的第一天
  const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
  // 检查选择的日期是否是当前月的第一天
  return !(date.getTime() === firstDayOfMonth.getTime());
};
</script>

<template>
  <el-dialog
    v-model="visible"
    title="添加数据"
    width="480"
    :close-on-click-modal="false"
    :before-close="close"
  >
    <div class="m-auto w-full">
      <el-form
        ref="ruleFormRef"
        :model="form"
        label-position="right"
        label-width="auto"
        :rules="rules"
        style="max-width: 600px"
      >
        <el-form-item label="指标名称" prop="sourceValue">
          <el-autocomplete
            v-model="form.sourceValue"
            value-key="sourceValue"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            clearable
            placeholder="请输入"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptCode">
          <el-tree-select
            v-model="form.deptCode"
            :data="deptSelect"
            :props="defaultProps"
            default-expand-all
            check-strictly
            :render-after-expand="false"
            @change="handleDept"
            @node-click="handleNodeDeptClick"
          />
        </el-form-item>
        <el-form-item label="员工名称">
          <el-select
            v-model="form.userId"
            filterable
            placeholder="请选择"
            @change="handleUser"
          >
            <el-option
              v-for="(item, index) in userSelect"
              :key="index"
              :label="item.realName"
              :value="item.hospitalCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分子">
          <el-input
            v-model="form.numerator"
            autocomplete="off"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="分母">
          <el-input
            v-model="form.denominator"
            autocomplete="off"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="值">
          <el-input
            v-model="form.dataValue"
            autocomplete="off"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="数据时间" prop="specificTime">
          <el-date-picker
            v-model="form.specificTime"
            type="month"
            placeholder="请选择日期"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="addSave"
          >保存</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>
