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

const emit = defineEmits(["updateDialog"]);
const formRef = ref();
const drawer = ref(false);
const disabledShow = ref<any>(true);
const direction = ref<DrawerProps["direction"]>("rtl");

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

// 抽屉逻辑
const open = async row => {
  await getPageListApi();
  await getIndustryListApi();
  if (row.deptCode) {
    await handleDept(row.deptCode);
  }
  Object.assign(formLabelAlign, row);
  drawer.value = true;
};
defineExpose({
  open
});
const handleClose = (done: () => void) => {
  if (disabledShow.value) {
    disabledShow.value = true;
    drawer.value = false;
  } else {
    ElMessageBox.confirm("配置项未保存，确认关闭", {
      type: "warning"
    }).then(() => {
      formRef.value.clearValidate(); // 清除验证错误
      formRef.value.resetFields(); // 重置表单字段
      disabledShow.value = true;
      drawer.value = false;
    });
  }
};
const cancelClick = () => {
  formRef.value.validate(valid => {
    if (valid) {
      disabledShow.value = true;
    }
  });
};
const editClick = () => {
  disabledShow.value = false;
};

// 确认
const saveLoading = ref(false);
const confirmClick = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      saveLoading.value = true;
      if (formLabelAlign.specificTime) {
        formLabelAlign.specificTime = dayjs(
          formLabelAlign.specificTime
        ).valueOf();
      }
      const { code, msg } = await editListApi({ ...formLabelAlign });
      saveLoading.value = false;
      if (code === 200) {
        ElMessage({
          message: "修改成功",
          type: "success"
        });
        disabledShow.value = true;
        drawer.value = false;
        emit("updateDialog");
      }
    }
  });
};

// 指标名称
const restaurants = ref([]);
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value;
  cb(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 => {
  formLabelAlign.deptId = data.hospitalCode;
  formLabelAlign.deptName = data.deptName;
};

// 员工名称
const userSelect = ref([]);
const handleDept = async val => {
  formLabelAlign.userId = "";
  formLabelAlign.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 => {
  formLabelAlign.userId = val;
  userSelect.value.forEach(item => {
    if (item.hospitalCode === val) {
      formLabelAlign.userName = item.realName;
    } else {
      formLabelAlign.userName = "";
    }
  });
  if (!val) {
    formLabelAlign.userId = "";
  }
};

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

<template>
  <div>
    <el-drawer
      v-model="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <template #header>
        <h4>数据详情</h4>
      </template>
      <template #default>
        <div>
          <el-form
            ref="formRef"
            label-position="top"
            label-width="auto"
            :rules="rules"
            :model="formLabelAlign"
          >
            <el-form-item
              label="指标名称"
              label-position="top"
              prop="sourceValue"
            >
              <el-autocomplete
                v-model="formLabelAlign.sourceValue"
                value-key="sourceValue"
                :fetch-suggestions="querySearch"
                :trigger-on-focus="false"
                clearable
                placeholder="请输入"
                :disabled="disabledShow"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="部门名称" label-position="top" prop="deptCode">
              <el-tree-select
                v-model="formLabelAlign.deptCode"
                :disabled="disabledShow"
                :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="员工名称" label-position="top">
              <el-select
                v-model="formLabelAlign.userId"
                :disabled="disabledShow"
                clearable
                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="分子" label-position="top">
              <el-input
                v-model="formLabelAlign.numerator"
                :disabled="disabledShow"
                autocomplete="off"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="分母" label-position="top">
              <el-input
                v-model="formLabelAlign.denominator"
                :disabled="disabledShow"
                autocomplete="off"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="值" label-position="top">
              <el-input
                v-model="formLabelAlign.dataValue"
                :disabled="disabledShow"
                autocomplete="off"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item
              label="数据时间"
              prop="specificTime"
              label-position="top"
            >
              <el-date-picker
                v-model="formLabelAlign.specificTime"
                type="month"
                :disabled="disabledShow"
                placeholder="请选择日期"
              />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button v-if="disabledShow" type="warning" @click="editClick"
          >编辑</el-button
        >
        <div v-else>
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" :loading="saveLoading" @click="confirmClick"
            >确认</el-button
          >
        </div>
      </template>
    </el-drawer>
  </div>
</template>
