<template>
  <div>
    <el-dialog title="分组管理" v-model="dialogVisible">
      <div>
        <el-form ref="formRef" :model="form" label-width="120px">
          <el-form-item
            label="分组名称："
            prop="name"
            :rules="[
              {
                required: true,
                message: '请输入管理分组名称',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="form.name"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="适用人群：" prop="scope">
            <el-input
              v-model="form.scope"
              placeholder="请输入该分组适用人群范围，如高血压高危分层人群"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="对应疾病：" prop="diseases">
            <el-select
              multiple
              v-model="form.diseases"
              placeholder="全部已确诊疾病"
              filterable
              :remote-method="getNodeList"
              :loading="loading"
              remote
              reserve-keyword
              clearable
              style="width: 200px"
              class="mr-2"
            >
              <el-option
                v-for="item in nodeList"
                :key="item.id"
                :label="item.properties?.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { request } from "@/utils";
import { ElMessage } from "element-plus";
import { ref, computed, defineProps, defineEmits, watch, reactive } from "vue";
import { cloneDeep } from "@pureadmin/utils";

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  },
  levelId: {
    type: [Number, String],
    default: ""
  }
});
const emits = defineEmits(["update:show", "success"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});

watch(
  () => dialogVisible.value,
  n => {
    if (n) {
      if (props.rowData?.id) {
        form.name = props.rowData.name;
        form.scope = props.rowData.scope;
        form.id = props.rowData.id;
        let deepcloneDiseases = cloneDeep(props.rowData?.diseases);
        form.diseases = deepcloneDiseases?.map(v => JSON.stringify(v));

        nodeList.value = deepcloneDiseases?.map(v => {
          return {
            ...v,
            value: JSON.stringify(v)
          };
        });

        console.log("nodeList", nodeList.value);
        console.log("form.diseases", form.diseases);
      }
    } else {
      formRef.value.resetFields();
      form.id = undefined;
    }
  }
);
const form = reactive({
  name: "",
  scope: "",
  id: undefined,
  diseases: []
});
const loading = ref(false);
const nodeList = ref([]);
const formRef = ref();

const onSubmit = () => {
  formRef.value.validate(valid => {
    if (!valid) return;
    console.log("form.diseases", form.diseases);

    let api = form.id
      ? "dataService/schemeManage/diseaseManageGroup/update"
      : "dataService/schemeManage/diseaseManageGroup";
    request
      .post(api, {
        ...form,
        levelid: props.levelId,
        diseases: form.diseases.map(v => JSON.parse(v))
      })
      .then(resp => {
        ElMessage.success(resp.message);
        dialogVisible.value = false;
        emits("success");
      });
  });
};

const getNodeList = (query: string) => {
  if (!query) {
    return (nodeList.value = []);
  }
  loading.value = true;

  request
    .get("/platformApi/graphService/open/node/paginate", {
      params: {
        pageSize: 10,
        tag: "疾病",
        name: query
      }
    })
    .then(resp => {
      let list = resp.data.list;
      nodeList.value = list.map(v => {
        return {
          ...v,
          // key排序 不然的话key会无序
          value: JSON.stringify(v, (key, value) => {
            if (typeof value === "object" && !Array.isArray(value)) {
              return Object.keys(value)
                .sort()
                .reduce((sorted, key) => {
                  sorted[key] = value[key];
                  return sorted;
                }, {});
            }
            return value;
          })
        };
      });
      console.log("list", nodeList.value);
    })
    .finally(() => {
      loading.value = false;
    });
};
// getNodeList();
</script>
