<script setup lang="tsx">
import {
  clinicalPathwayType,
  key,
  keyName,
  execute,
  execType,
} from "@/views/dictionary/clinical-pathway/index";
import { ViewPathwayStage, WorkType } from "@/ts-type/clinical-pathway";
import { CyMessageBox } from "@/utils/cy-message-box";
import {
  addWorkItem,
  deleteWorkItem,
  getOrderTemplateByWorkId,
  updateDay,
  updateWorkItem,
} from "@/api/dictionary/clinical-pathway/clinical-pathway";
import { useDialog } from "@/components/cy/CyDialog/index";
import YzTable from "./compoents/YzTable.vue";
import XEUtils from "xe-utils";

const { store, mutation } = inject(key) as clinicalPathwayType;

const tmpData = computed<ViewPathwayStage["execute"]>(() => {
  const json = store.stageJson[store.currentDay];
  return json?.execute;
});

function handleEditorWork(row) {
  row._isEditor = true;
}

function handleSaveWork(row) {
  updateWorkItem(row).then(res => {
    mutation.renderingData();
    row._isEditor = false;
  });
}

async function handleDeleteWork(exec: any[], index, row) {
  await CyMessageBox.confirm({
    type: "delete",
    message: "是否删除删除后无法找回",
  });

  deleteWorkItem(row.id).then(() => {
    exec.splice(index, 1);
    mutation.renderingData();
  });
}

async function addType(value) {
  CyMessageBox.prompt({
    message: "项目名称",
  }).then(res => {
    const json = store.stageJson[store.currentDay];

    addWorkItem(json.id, res.value, value).then(res => {
      if (!json.execute[execute[value]]) {
        json.execute[execute[value]] = [];
      }
      json.execute[execute[value]].push(res);
      mutation.renderingData();
    });
  });
}

async function addWorkContent(value, type) {
  if (type === "zhenliao" || type === "huli") {
    return;
  }

  const orderTemplate = await getOrderTemplateByWorkId(value.id);

  useDialog(YzTable, {
    dialogProps: {
      title: "编辑医嘱",
      fullscreen: true,
    },
    params: {
      wordId: value.id,
      wordType: type,
      defaultOrder: orderTemplate,
    },
  }).catch(XEUtils.noop);
}

function updateDayExecutionDays() {
  const json = store.currentDayJson;
  if (store.tmpExecutionDay === json.executionDay) {
    return;
  }
  updateDay({
    id: json.id,
    executionDay: store.tmpExecutionDay,
  })
    .then(() => {
      store.currentDayJson.executionDay = store.tmpExecutionDay;
      mutation.renderingData();
    })
    .catch(() => {
      store.tmpExecutionDay = json.executionDay;
    });
}
</script>

<template>
  <div v-if="store.currentDay !== -1">
    <el-button type="danger" @click="mutation.delDay()">删除天</el-button>
    <el-divider direction="vertical" />
    <el-button @click="addType(WorkType.MAIN_DIAGNOSIS)"
      >新增主要诊疗
    </el-button>
    <el-button @click="addType(WorkType.LONG_TERM_ORDER)">长期医嘱</el-button>
    <el-button @click="addType(WorkType.TEMPORARY_ORDER)">临时医嘱</el-button>
    <el-button @click="addType(WorkType.MAIN_NURSING)">主要护理</el-button>
    <el-divider direction="vertical" />
    执行天数：
    <el-input-number
      :min="1"
      :controls="false"
      v-model="store.tmpExecutionDay"
      @blur="updateDayExecutionDays"
    />

    <hr />
    <table class="pathway_editor-table">
      <colgroup>
        <col style="width: 90px" />
        <col style="width: 400px" />
        <col style="width: 170px" />
        <col style="width: 170px" />
      </colgroup>

      <thead>
        <tr>
          <th>分类</th>
          <th>内容</th>
          <th>执行方式</th>
          <th>操作</th>
        </tr>
      </thead>

      <template v-for="item in execute">
        <tr v-if="tmpData[item]">
          <td
            :rowspan="tmpData[item].length + 1"
            style="text-align: center; vertical-align: middle"
          >
            {{ keyName[item] }}
          </td>
        </tr>

        <tr v-for="(value, index) in tmpData?.[item] ?? []" :key="key">
          <td>
            <el-input v-model="value.workContent" v-if="value._isEditor" />
            <el-button
              v-else
              @click="addWorkContent(value, item)"
              text
              type="primary"
            >
              {{ value.workContent }}
            </el-button>
          </td>
          <td>
            <select v-if="value._isEditor" v-model="value.execType">
              <option v-for="(optitem, optIndex) in execType" :value="optIndex">
                {{ optitem }}
              </option>
            </select>
            <span v-else>
              {{ execType[value.execType] }}
            </span>
          </td>
          <td>
            <el-button
              v-if="value._isEditor"
              type="success"
              @click="handleSaveWork(value)"
            >
              保存
            </el-button>
            <el-button v-else @click="handleEditorWork(value)" type="primary"
              >编辑
            </el-button>
            <el-button
              type="danger"
              @click="handleDeleteWork(tmpData[item], index, value)"
              >删除
            </el-button>
          </td>
        </tr>
      </template>
    </table>
  </div>
</template>

<style lang="scss">
.pathway_editor-table {
  letter-spacing: 1px;
  width: max-content;
  word-break: break-all;
  margin: 0;
  padding: 0;
  text-align: start;
  border-collapse: collapse;
  border-spacing: 0;
  border: 1px solid #000;

  td {
    border: 1px black solid;
    margin: 0;
    vertical-align: top;
    padding: 10px;
  }

  tr {
    padding: 0;
    margin: 0;
  }
}
</style>
