<script setup lang="ts">
import IframeEditor from "./iframe-editor.vue";
import { useCompShallowRef } from "@/utils/useCompRef";
import { magicApi } from "@/utils/database/magic-api-request";
import { getAllWards } from "@/api/login";
import XcElOption from "@/components/xiao-chan/xc-el-option/XcElOption.vue";
import * as api from "@/api/dashboardEditor/dashboardEditor";
import { type TDashboardTemplate } from "@/api/dashboardEditor/dashboardEditor";
import { BizException, ExceptionEnum } from "@/utils/BizException";
import { stringIsBlank } from "@/utils/blank-utils";
import SystemDeptSelect from "@/components/system/dept-select/SystemDeptSelect.vue";
import { getDept } from "@/api/public-api";

const dashboardEditorRef = useCompShallowRef(IframeEditor);

const store = reactive({
  dataSource: [] as { code: string; name: string; group: string }[],
  group: {},
  currentWard: null,
  wardList: [],
  currentTemplate: {} as null | TDashboardTemplate,
  collapseValue: "",
  templateType: 0,
  templateTypeList: [] as { code: number; name: string; url: string }[],
});

const tmpGroupDataSource = computed(() => {
  const tmp = {};
  store.dataSource.forEach(item => {
    if (tmp[item.group]) {
      tmp[item.group].push(item);
    } else {
      tmp[item.group] = [item];
    }
  });
  return tmp;
});

async function handleWardChange() {
  const { currentWard, templateType } = store;

  store.currentTemplate = await api.getDashboardTemplateByWardCode(
    currentWard,
    templateType
  );
  dashboardEditorRef.value.clearHtml();
  if (store.currentTemplate == null) {
    dashboardEditorRef.value.insertTable(17, 11);
  } else {
    dashboardEditorRef.value.setHtml(
      store.currentTemplate.htmlDataTemp || store.currentTemplate.htmlData || ""
    );
  }
}

function handleTemplateTypeChange() {
  queryDataSource();
  handleWardChange();
}

function queryDataSource() {
  const tmp = store.templateTypeList.find(item => {
    return item.code === store.templateType;
  });

  magicApi({
    url: tmp.url,
    method: "post",
    data: { isSource: true },
  })
    .then(res => {
      store.dataSource = res.data;
      store.group = res.group;
    })
    .catch(() => {
      store.dataSource = [];
      store.group = {};
    });
}

onMounted(() => {
  magicApi({
    url: "/public/dashboard/getTemplateType",
    method: "get",
  }).then(res => {
    store.templateTypeList = res;
    queryDataSource();
  });

  getDept()
    .then(res => {
      store.wardList = res;
      store.wardList.unshift({
        code: "defaultTemp",
        name: "默认模板",
      });
    })
    .catch(() => {
      store.wardList = [];
    });
});

async function handleSave(htmlData) {
  if (store.currentWard == null) {
    BizException(ExceptionEnum.MESSAGE_ERROR, "请先选择病区");
  }
  if (store.currentTemplate == null) {
    store.currentTemplate = {
      wardCode: store.currentWard,
      htmlDataTemp: htmlData,
      templateType: store.templateType,
    };
  } else {
    store.currentTemplate.htmlDataTemp = htmlData;
    store.currentTemplate.wardCode = store.currentWard;
    store.currentTemplate.templateType = store.templateType;
  }
  store.currentTemplate = await api.saveTemplate(store.currentTemplate);
}

async function handleRelease() {
  if (stringIsBlank(store.currentTemplate?.htmlDataTemp)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, "请先设置模板");
  }
  if (stringIsBlank(store.currentTemplate?.id)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, "请先保存");
  }
  await api.release(store.currentTemplate.id);
}

function handlePreview() {
  if (stringIsBlank(store.currentTemplate?.id)) {
    BizException(ExceptionEnum.MESSAGE_ERROR, "请先打开模板");
  }
  window.open(
    `${location.origin}/inpatientBoardV2?tempId=${store.currentTemplate.id}&ward=${store.currentWard}`,
    "_blank"
  );
}

defineOptions({
  name: "dashboardEditor",
});
</script>

<template>
  <div class="layout_container layout-horizontal">
    <aside style="width: 15vw" class="layout_card">
      <div class="layout_container">
        <header>
          <el-alert
            type="error"
            effect="dark"
            title="列宽可能拖动，但是列高不行，因为高度是不确定的，发布后才能看到效果。"
            :closable="false"
          ></el-alert>
          <el-form style="width: 100%">
            <el-form-item label="病区：">
              <el-select
                style="width: 100%"
                v-model="store.currentWard"
                @change="handleWardChange"
              >
                <xc-el-option :data="store.wardList" />
              </el-select>
            </el-form-item>
            <el-form-item label="类型：">
              <el-select
                v-model="store.templateType"
                @change="handleTemplateTypeChange"
              >
                <xc-el-option :data="store.templateTypeList" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleRelease">发布</el-button>
            </el-form-item>
          </el-form>
        </header>
        <div class="layout_main layout_container">
          <el-divider>数据源</el-divider>
          <div style="padding: 10px" class="layout_main">
            <el-collapse>
              <el-collapse-item
                v-for="(value, key) in store.group"
                :title="value"
              >
                <el-row :gutter="10">
                  <el-col
                    style="margin-top: 8px"
                    :span="24 / 3"
                    v-for="item in tmpGroupDataSource[key]"
                    @click="
                      () => {
                        dashboardEditorRef.insert(item);
                      }
                    "
                  >
                    <el-tag size="large" style="width: 100%">
                      {{ item.name }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </div>
    </aside>
    <div class="layout_main">
      <IframeEditor ref="dashboardEditorRef" @save="handleSave" />
    </div>
  </div>
</template>

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