<template>
  <my-layout bg-fff common-shadow>
    <layout-item>
      <!-- <div title-bar class="p-15">团队管理</div> -->
      <div p-15 flex items-center justify-between>
        <div flex items-center>
          <el-input class="mr-10" placeholder="输入诊断名称搜索" v-model="searchName" @input="inputChange" />
          <el-button type="primary" @click="search()">查询</el-button>
        </div>
        <el-button type="primary" plain @click="add()">新增</el-button>
      </div>
    </layout-item>
    <layout-main :scroll="false">
      <el-table stripe height="100%" :data="list" :header-cell-style="{ background: '#ecf4ff' }">
        <el-table-column property="index" label="序号" />
        <el-table-column property="name" label="诊断名称"></el-table-column>
        <el-table-column fixed="right" class-name="el-table-fixed-column--shadow" label="操作" width="120">
          <template #default="{ row }">
            <el-button text class="table-action-btn" type="primary" size="small" @click="edit(row)">编辑</el-button>
            <el-button text class="table-action-btn" type="danger" size="small" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </layout-main>
    <layout-item>
      <pagination :totalRow="total" :pageSize="pageSize" :currentPage="currentPage" @handle-size-change="onSizeChange"
        @handle-current-change="onCurrentChange" />
    </layout-item>
  </my-layout>
  <el-dialog :title="oldName ? '编辑诊断' : '新增诊断'" v-model="visible" width="500">
    <div p-15>
      <el-input v-model="searchDiseases" placeholder="请填写诊断" clearable />
      <!-- <el-select class="select-disease" v-model="searchDiseases" filterable remote allow-create default-first-option reserve-keyword placeholder="请填写诊断" :remote-method="findDisease" :loading="loading" :remote-show-suffix="true">
        <el-option v-for="item in diseaseList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select> -->
    </div>
    <template #footer>
      <div text-center>
        <!-- <el-button v-if="oldName" class="w-100px" @click="remove()">删除</el-button> -->
        <el-button class="w-100px" @click="onClose">取消</el-button>
        <el-button class="w-100px" type="primary" @click="saveDiagnosis">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { watchDebounced } from "@vueuse/core";
import { ElMessage } from "element-plus";
import { debounce } from "@/utils/common";
import { memberStore } from "@/store/member";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import { ElMessageBox } from "element-plus";
import { updateCorpInfo, addCorpDisease } from "@/api/corp";
import { updateDiagnosisCategory } from '@/api/hlw';
import { getDisease } from "@/api/knowledgeBase";

const { corpInfo } = memberStore();
const corpDisease = ref(corpInfo.diseases || []);
const diseases = ref(corpInfo.diseases || []);
const searchName = ref("");
const diseaseList = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const visible = ref(false);
const searchDiseases = ref("");
const list = computed(() => {
  let arr = diseases.value.map((item, index) => {
    return {
      name: item,
      index: index + 1,
    };
  });
  return arr.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
});
const total = computed(() => {
  return diseases.value.length;
});
function onSizeChange(e) {
  currentPage.value = 1;
  pageSize.value = e;
}
function onCurrentChange(e) {
  currentPage.value = e;
}
function search() {
  if (!searchName.value) {
    return;
  }
  currentPage.value = 1;
  let pattern = new RegExp(searchName.value, "i");
  diseases.value = corpDisease.value.filter((item) => pattern.test(item));
}

function add() {
  searchDiseases.value = "";
  oldName.value = "";
  visible.value = true;
}
function inputChange(e) {
  if (!e) {
    diseases.value = corpInfo.diseases;
  }
}
const oldName = ref("");
function edit({ name }) {
  oldName.value = name;
  searchDiseases.value = name;
  visible.value = true;
}
async function remove({ name }) {
  await ElMessageBox.confirm("是否删除常用诊断?", { type: "warning" })
  let index = diseases.value.findIndex((i) => i === name && name);
  if (index >= 0) {
    await asyncCategory(name, '');
    await updateCorp();
    diseases.value.splice(index, 1);
    visible.value = false;
    ElMessage.success("删除成功!");
  }
}
// 更新corp表, 更新常用诊断
async function updateCorp() {
  const res = await updateCorpInfo({ diseases: diseases.value });

}

function onClose() {
  visible.value = false;
}

async function saveDiagnosis() {
  const name = searchDiseases.value.trim();
  if (diseases.value.indexOf(name) !== -1) {
    ElMessage.error("该病种已添加!");
    return;
  }
  if (!name) {
    ElMessage.error("请填写诊断!");
    return;
  }
  await addCorpDisease({ disease: name, oldDisease: oldName.value });
  await asyncCategory(oldName.value, name);
  if (oldName.value) {
    const index = diseases.value.findIndex((i) => i == oldName.value);
    diseases.value.splice(index, 1, name);
  } else {
    diseases.value.unshift(name);
  }
  visible.value = false;
}

const loading = ref(false);
const searchText = ref("");
function findDisease(val) {
  if (val.trim()) {
    loading.value = true;
    searchText.value = val.trim();
  }
}

async function getDieaseList(diseaseName) {
  const { data } = await getDisease(diseaseName);
  const list = data.data
    .map((item) => {
      return {
        value: item.diseaseName,
        label: item.diseaseName,
      };
    })
    .filter((i) => i.label !== diseaseName);
  diseaseList.value = [{ value: diseaseName, label: diseaseName }, ...list];
}

async function asyncCategory(oldCategory, newCategory) {
  if (!oldCategory) return
  const { success, message } = await updateDiagnosisCategory({ oldCategory, newCategory })
  if (!success) {
    ElMessage.error(message);
    return false;
  }
  return true
}

watchDebounced(
  searchText,
  async () => {
    if (searchText.value) {
      await getDieaseList(searchText.value);
    }
    loading.value = false;
  },
  { debounce: 1000 }
);
</script>
<style scoped>
.w-200 {
  width: 200px;
}

.mr-10 {
  margin-right: 10px;
}

.table-action-btn {
  padding-left: 0;
  padding-right: 0;
}

.select-disease {
  display: block;
}
</style>
