<template>
  <el-dialog :model-value="props.visible" :width="width" :title="`${props.project._id ? '编辑' : '新增'}项目`"
    @close="close()">
    <el-scrollbar wrap-class="el-dialog-body-full-scroll">
      <el-form class="p-15px" label-suffiix="：" :label-width="160" label-suffix="：">
        <el-form-item class="is-required" label="项目名称">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item class="is-required" label="项目编号">
          <div class="flex-grow">
            <el-input v-model="form.projectNo" placeholder="请输入项目编号" :disabled="project._id" />
            <div class="text-12px text-gray-500 mt-12px">项目编号可以为数字或者字母组合，请勿重复</div>
          </div>
        </el-form-item>
        <el-form-item label="项目类型">
          <el-select v-model="form.projectType" placeholder="请选择项目类型" class="w-full">
            <el-option v-for="item in ProjectType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="form.unit" placeholder="请选择单位" class="w-full">
            <el-option v-for="item in unitList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price" @input="priceFormatInput" placeholder="请输入项目价格" />
        </el-form-item>
        <el-form-item class="is-required" label="关联开单科室分类">
          <el-cascader v-model="form.projectCateIdGroup" :show-all-levels="false" :options="cateTree"
            :props="{ checkStrictly: true, value: '_id',multiple: true,emitPath:false }" class="w-full" clearable
            placeholder="请选择分类" />
        </el-form-item>
        <el-form-item label="关联治疗科室">
          <div
            class="mt-10px p-10px flex items-center w-full border border-gray-200 min-h-32px cursor-pointer rounded hover:border-gray-300"
            @click="showDeptPicker()">
            <div v-if="depts.length == 0" class="flex-shrink-0 text-gray-400 text-14px">请选择</div>
            <div class="flex-grow flex flex-wrap -mb-5px">
              <div
                class="flex items-center rounded border border-gray-200 px-10px py-6px mr-5px mb-5px group bg-gray-50"
                v-for="(dept, i) in depts" :key="i" @click.stop="">
                <div color-normal class="text-13px">{{ dept.deptName }}</div>
                <el-icon class="ml-5px text-gray-500 hover:text-red-500" :size="14" @click.stop="removeDept(i)">
                  <CloseBold />
                </el-icon>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="是否生成治疗单">
          <el-switch v-model="form.createTreatmentOrder" size="large" inline-prompt active-text="生成"
            inactive-text="不生成" />
        </el-form-item>
        <el-form-item label="折扣设置">
          <div class="flex items-center flex-wrap">
            <el-checkbox v-model="form.isGift">支持赠送</el-checkbox>
            <el-checkbox v-model="form.isDiscount">支持折扣</el-checkbox>
            <div class="flex items-center flex-shrink-0 ml-30px">
              <div>请输入最低折扣</div>
              <el-input v-model="form.lowestDiscount" @input="validateDiscount" placeholder="请输入1-10的折扣"
                class="w-140px mx-10px" />
              <div>折</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="项目描述">
          <el-input type="textarea" v-model="form.description" placeholder="请输入项目描述" maxlength="500"
            :autosize="{ minRows: 6, maxRows: 10 }" resize="none" show-word-limit></el-input>
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div text-center>
        <el-button plain class="w-100px" type="primary" :icon="Plus" @click="close()">取消</el-button>
        <el-button plain class="w-100px" type="danger" :icon="Plus" @click="detele()"
          v-if="props.project._id">删除</el-button>
        <el-button class="w-100px" :loading="loading" type="primary" :icon="Plus" @click="confirm()">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <dept-picker-modal ref="deptPickerRef" :value="deptIds" :visible="deptVisible" :width="deptPickerWidth"
    @change="deptChange" @close="closeDeptPicker" />
</template>
<script setup>
import { ElMessage } from "element-plus";
import { computed, nextTick, ref, watch } from "vue";
import { ProjectType, unitList } from "@/baseData";
import useModal from "@/hooks/useModal";
import { addProject, deleteProject, updateProject } from "@/api/project-manage";
import deptPickerModal from "@/components/dept-picker-modal/dept-picker-modal.vue";

import { ElMessageBox } from "element-plus";
const emits = defineEmits(["close", "change", "success"]);
const props = defineProps({
  cateId: { type: String, default: "" },
  visible: { type: Boolean, default: false },
  cateTree: { type: Array, default: () => [] },
  cateList: { type: Array, default: () => [] },
  width: { type: String, default: "500px" },
  id: { type: String, default: "" },
  project: { type: Object, default: () => ({}) },
});
const form = ref({});
const { close: closeDeptPicker, show: showDeptPicker, visible: deptVisible, width: deptPickerWidth } = useModal(640);
const depts = ref([]);
const deptIds = computed(() => depts.value.map((item) => item._id));
const deptPickerRef = ref();
const cateDepts = ref([]);

function close() {
  emits("close");
}
const loading = ref(false);
async function confirm() {
  let query = JSON.parse(JSON.stringify(form.value));
  query.deptIds = [...deptIds.value];
  const { projectName, projectNo } = query;
  if (!projectName) {
    ElMessage.error("项目名称不能为空");
    return;
  }
  if (!projectNo) {
    ElMessage.error("项目编号不能为空");
    return;
  }
  if (!Array.isArray(form.value.projectCateIdGroup) || form.value.projectCateIdGroup.length === 0) {
    ElMessage.error("请选择关联开单科室分类");
    return;
  }
  loading.value = true;
  const { success, message } = props.project._id ? await updateProject({ id: props.project._id, params: query }) : await addProject({ params: query });
  if (success) {
    ElMessage.success(message);
    close();
    emits("success");
  } else {
    ElMessage.error(message);
  }
  loading.value = false;
}
const priceFormatInput = () => {
  // 移除非数字和小数点的字符
  let value = form.value.price.replace(/[^\d.]/g, "");
  // 确保只有一个小数点
  if (value.split(".").length > 2) {
    value = value.replace(/\.+$/, "");
  }
  // 保留两位小数
  if (value.includes(".")) {
    const [integerPart, decimalPart] = value.split(".");
    value = `${integerPart}.${decimalPart.slice(0, 2)}`;
  }
  // 更新输入值
  // 验证输入值是否为有效金额
  if (isNaN(value) || Number(value) <= 0) {
    form.value.price = "";
  } else {
    form.value.price = value;
  }
};

const validateDiscount = () => {
  const value = form.value.lowestDiscount;
  const num = Number(value);
  if (!Number(num) || num < 1 || num > 10) {
    form.value.lowestDiscount = "";
  } else {
    form.value.lowestDiscount = value;
  }
};

async function detele() {
  if (!props.project._id) return;
  ElMessageBox.confirm("是否删除该项目?", "提示", { type: "warning" }).then(async () => {
    const { success, message } = await deleteProject({ id: props.project._id });
    if (success) {
      ElMessage.success("删除成功");
      close();
      emits("success");
    } else {
      ElMessage.error(message);
    }
  });
}

function deptChange(val) {
  depts.value = val;
  closeDeptPicker();
}

function removeDept(index) {
  depts.value.splice(index, 1);
}

watch(
  () => props.visible,
  async (n) => {
    if (n) {
      form.value = {
        projectName: props.project.projectName || "",
        projectNo: props.project.projectNo || "",
        projectType: props.project.projectType || "",
        unit: props.project.unit || "",
        price: props.project.price || "",
        description: props.project.description || "",
        isGift: props.project.isGift || false,
        isDiscount: props.project.isDiscount || false,
        lowestDiscount: props.project.lowestDiscount || "",
        projectCateIdGroup: Array.isArray(props.project.projectCateIdGroup) ? props.project.projectCateIdGroup : [],
        createTreatmentOrder: Boolean(props.project.createTreatmentOrder),
      };
      if (form.value.projectCateIdGroup.length === 0 && !props.project._id) {
        form.value.projectCateIdGroup = [props.cateId];
      }
      await nextTick();
      depts.value = await deptPickerRef.value.getDeptsByIds(props.project.deptIds);
      cateDepts.value = await deptPickerRef.value.getDeptsByIds(Array.isArray(props.project.billDeptIds) ? props.project.billDeptIds : []);
    }
  }
);
watch(() => form.value.projectCateIdGroup, async n => {
  if (props.visible && Array.isArray(n) && n.length > 0) {
    await nextTick();
    const cates = props.cateList.filter(i => n.includes(i._id));
    const level1Cates = cates.map(i => {
      if (i.level === 1) return i._id;
      if (Array.isArray(i.parentGroup)) return i.parentGroup[0];
    }).filter(Boolean); //  获取对应的一级分类的id (只有一级分类才能设置 开单科室)
    const deptIds = props.cateList.filter(i => i.level === 1 && level1Cates.includes(i._id)).map(i => i.deptId).filter(Boolean);
    cateDepts.value = await deptPickerRef.value.getDeptsByIds(deptIds);
    form.value.billDeptIds = cateDepts.value.map(dept => dept._id);
  }
})
</script>