<template>
  <div class="page-calibration-ocr">
    <div class="mb-2 flex items-center justify-between">
      <div>
        <el-button type="primary" class="ml-2 mr-4" @click="editItem()"
          >添加</el-button
        >
        <el-button
          type="primary"
          plain
          class="ml-2 mr-4"
          @click="showAgencyDialog"
          >检查机构管理</el-button
        >
      </div>
      <div>
        <el-input
          v-model="filter.name"
          class="w-64 mx-2"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="onSearch"
        ></el-input>
        <el-button :icon="Search" type="primary" @click="onSearch"
          >搜索</el-button
        >
      </div>
    </div>
    <el-row class="py-4">
      <el-col :span="24">
        <el-table :data="list">
          <el-table-column
            label="模板名称"
            prop="templateName"
          ></el-table-column>
          <el-table-column
            label="所属机构"
            prop="institutionName"
          ></el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="primary" link @click="editItem(row)"
                >编辑</el-button
              >
              <el-button type="danger" link @click="removeItem(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="mt-4 justify-end"
          background
          @current-change="onPageChange"
          :current-page.sync="filter.page"
          layout="total, prev, pager, next"
          :total="count"
        >
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog v-model="editTemplateVisible" title="编辑模板" width="80%">
      <el-form label-position="top">
        <el-form-item label="检查机构" required>
          <!-- 虚拟滚动机构列表 getAgencyFillList -->
          <el-select-v2
            v-model="editTemplate.institutionId"
            placeholder="请选择"
            filterable
            :options="agencyFillList"
            :props="{
              label: 'institutionName',
              value: 'id'
            }"
          />
          <!-- <el-select
            v-model="editTemplate.agencyId"
            placeholder="请选择检查机构"
            filterable
            clearable
            @change="getAgencyFillList"
          >
            <el-option
              v-for="item in agencyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="模板名称" required>
          <el-input
            v-model="editTemplate.name"
            placeholder="请输入模板名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="模板项目" required>
          <el-table :data="editTemplate.list">
            <el-table-column label="项目名称(必填)">
              <template #default="{ row }">
                <el-input v-model="row.name"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="默认结果">
              <template #default="{ row }">
                <el-input v-model="row.defaultValue"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="单位">
              <template #default="{ row }">
                <el-input v-model="row.unit"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="范围">
              <template #default="{ row }">
                <el-input v-model="row.scope"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="排序">
              <template #default="{ row }">
                <el-input v-model.number="row.sort"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="身体物质/部位(必填)">
              <template #default="{ row }">
                <el-select
                  v-model="row.node"
                  placeholder="请输入搜索后选择"
                  filterable
                  clearable
                  remote
                  :remote-method="query => searchBodyNodes(query, row)"
                  @change="matchNodeChange(row, $event)"
                >
                  <el-option
                    v-for="(node, nodeIdx) in row.nodes"
                    :key="node.id"
                    :label="node.properties?.name"
                    :value="node.id"
                    class="h-auto"
                  >
                    <div class="">
                      <div>{{ node.properties?.name }}</div>
                      <div v-if="node.matched" class="text-gray-500 text-xs">
                        匹配名称：{{ node.matched }}
                      </div>
                    </div>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="检查项目(必填)">
              <template #default="{ row }">
                <el-select
                  v-model="row.project"
                  placeholder="请输入搜索后选择"
                  filterable
                  clearable
                  remote
                  :disabled="!row.node"
                >
                  <el-option
                    v-for="(project, projectIdx) in row.projects"
                    :key="project.id"
                    :label="project.properties?.name"
                    :value="project.id"
                    class="h-auto"
                  >
                    <div class="">
                      <div>{{ project.properties?.name }}</div>
                      <div v-if="project.matched" class="text-gray-500 text-xs">
                        匹配名称：{{ project.matched }}
                      </div>
                    </div>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row, $index }">
                <el-button
                  type="danger"
                  link
                  @click="
                    removeEditTemplateItem(editTemplate.list.splice($index, 1))
                  "
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="mt-2">
            <el-button type="primary" link @click="appendEditTemplateItem">
              + 新增</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="saveEditTemplate">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="agencyVisible" title="检查机构管理">
      <el-form inline>
        <el-form-item label="检查机构名称">
          <el-input v-model="appendAgencyName" placeholder="请输入机构名称">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="!appendAgencyName"
            @click="appendAgency"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-table :data="agencyList">
        <el-table-column label="机构名称">
          <template #default="{ row }">
            <el-input
              v-model="row.institutionName"
              @blur="editAgencyName(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="danger" link @click="removeAgency(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        class="mt-2 justify-end"
        :current-page="agencyQuery.page"
        :page-size="agencyQuery.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="agencyTotal"
        @current-change="
          p => {
            agencyQuery.page = p;
            getAgencyList();
          }
        "
      ></el-pagination>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from "vue";
import { request } from "@/utils";
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
const filter = ref({
  name: "",
  page: 1,
  pageSize: 10
});
const list = ref([]);

const count = ref(0);
const onPageChange = page => {
  filter.value.page = page;
  getList();
};
const onSearch = () => {
  filter.value.page = 1;
  getList();
};

const getList = async () => {
  const { data } = await request.get(
    `/dataService/dataTemplate/mechanism/paginate`,
    {
      params: filter.value
    }
  );
  list.value = data.list;
  count.value = data.total;
};
const editItem = async row => {
  if (row) {
    const { data } = await request.get(`/dataService/dataTemplate/mechanism`, {
      params: {
        id: row.id
      }
    });
    editTemplate.value.id = row.id;
    editTemplate.value.institutionId = row.institutionId;
    editTemplate.value.name = data.templateName;
    editTemplate.value.list = data.templateItems.map(v => {
      return {
        ...v,
        node: v.body.id,
        nodes: [v.body],
        project: v.item.id,
        projects: [v.item]
      };
    });
  } else {
    editTemplate.value = {
      id: undefined,
      name: "",
      list: []
    };
  }
  getAgencyFillList();
  editTemplateVisible.value = true;
};
const removeItem = row => {
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(
    () => {
      request
        .post("/dataService/dataTemplate/delete", { id: row.id })
        .then(response => {
          getList();
          ElMessage.success("删除成功");
        });
    },
    () => {}
  );
};
onMounted(() => {
  getList();
});

const editTemplateVisible = ref(false);
const editTemplate = ref({
  id: undefined,
  institutionId: "",
  name: "",
  list: []
});
const appendEditTemplateItem = () => {
  editTemplate.value.list.push({
    name: "",
    defaultValue: "",
    unit: "",
    scope: "",
    sort: 0,
    node: "",
    body: "",
    nodes: [],
    project: "",
    item: "",
    projects: []
  });
};

const recognitionType = ["身体物质/部位", "医学检查项目"];
const relatedRelationship = ["异常属于", "可检测"];
const searchNodes = async (key = "", isAddSearch = true, opt) => {
  if (!key) return;
  const { data } = await request.get(`/graphService/open/node/paginate`, {
    params: {
      pageSize: 500,
      name: key,
      tag: recognitionType[
        !isAddSearch && opt ? opt.type : addIndicatorType.value
      ],
      ...(!isAddSearch && opt ? opt.params || {} : {})
    }
  });
  if (isAddSearch) {
    addIndicatorQuery.value = "";
    allIndicators.value = data.list;
  }
  return data.list || [];
};
const searchBodyNodes = async (key, row) => {
  if (!key) return;
  const nodes =
    (await searchNodes(key, false, {
      type: 0
    })) || [];
  const dataIds = nodes.map(v => v.id);
  row.nodes = nodes;
};

const searchRelateNodes = async (id, relationship) => {
  const { data } = await request.get(`/graphService/open/node/related`, {
    params: { id, relationship: relatedRelationship[relationship] }
  });
  return data || [];
};
const matchNodeChange = async row => {
  const projects = await searchRelateNodes(row.node, 1);
  row.projects = projects;
};
const saveEditTemplate = async () => {
  if (!editTemplate.value.name) return ElMessage.error("请填写模板名称");
  if (!editTemplate.value.list.length) return ElMessage.error("请添加模板项目");
  if (
    editTemplate.value.list.filter(v => v.name && v.project && v.node).length !=
    editTemplate.value.list.length
  )
    return ElMessage.error("请填写模板项目必填项");
  await request.post(
    `/dataService/dataTemplate/mechanism${
      editTemplate.value.id ? "/update" : ""
    }`,
    {
      id: editTemplate.value.id,
      institutionId: editTemplate.value.institutionId,
      templateName: editTemplate.value.name,
      templateItems: editTemplate.value.list.map(v => {
        const temp = { ...v };
        temp.body = temp.nodes.find(n => n.id == temp.node);
        delete temp.node;
        delete temp.nodes;
        temp.item = temp.projects.find(n => n.id == temp.project);
        delete temp.project;
        delete temp.projects;
        return temp;
      })
    }
  );
  ElMessage.success("操作成功");
  editTemplateVisible.value = false;
  getList();
};


const agencyVisible = ref(false);
const appendAgencyName = ref("");
const agencyList = ref([]);
const agencyTotal = ref(0);
const agencyQuery = ref({
  page: 1,
  pageSize: 10,
  name: ""
});
const showAgencyDialog = () => {
  agencyVisible.value = true;
  agencyQuery.value.page = 1;
  agencyQuery.value.name = "";
  getAgencyList();
};
const getAgencyList = async () => {
  const { data } = await request.get(
    `/dataService/dataTemplate/mechanism/institution/paginate`,
    {
      params: agencyQuery.value
    }
  );
  agencyList.value = data.list.map(v => {
    return {
      ...v,
      originName: v.institutionName
    };
  });
  agencyTotal.value = data.total;
};

const appendAgency = async () => {
  if (!appendAgencyName.value) return ElMessage.error("请填写机构名称");
  await request.post(`/dataService/dataTemplate/mechanism/institution`, {
    name: appendAgencyName.value
  });
  ElMessage.success("操作成功");
  getAgencyList();
  appendAgencyName.value = "";
};
const removeAgency = async row => {
  ElMessageBox.confirm("确定删除吗？", "提示", {
    type: "warning"
  }).then(async () => {
    await request.post(
      "/dataService/dataTemplate/mechanism/institution/delete",
      { id: row.id }
    );
    getAgencyList();
    ElMessage.success("删除成功");
  });
};
const editAgencyName = async row => {
  if (row.originName == row.institutionName) return;
  if (!row.institutionName) return ElMessage.error("请填写机构名称");
  await request.post(`/dataService/dataTemplate/mechanism/institution/update`, {
    id: row.id,
    name: row.institutionName
  });
  ElMessage.success("操作成功");
  getAgencyList();
};

const agencyFillList = ref([]);
const getAgencyFillList = async () => {
  const { data } = await request.get(
    `/dataService/dataTemplate/mechanism/institution/paginate`,
    {
      params: {
        page: 1,
        pageSize: 1000
      }
    }
  );
  agencyFillList.value = data.list;
};
</script>

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