<template>
  <page-layer>
    <template #header>
      测试用住院号:
      <el-input v-model="editData.data.patNo" @blur="editData.data.patNo = $event.target.value.trim()"
                style="width: 120px;"
                placeholder="请输入住院号"/>
      测试用住院次数:
      <el-input-number style="width: 120px;" :min="1" :precision="0" v-model="editData.data.times"
                       placeholder="请输入住院次数"/>
      <el-button @click="openDialog(true,null)">新增数据</el-button>
      <el-button @click="testWhetherPatientDataIsNormal">测试全部数据</el-button>
    </template>

    <template #main>
      <el-tabs>
        <el-tab-pane label="提取数据">
          <el-button type="primary" @click="extractFunc.newData()">新增数据</el-button>
          <xc-table :local-data="extractList" :height="200">
            <el-table-column label="操作" width="90">
              <template #default="{row,$index}">
                <el-button-group>
                  <el-button type="warning" icon="Edit" @click="extractFunc.open(row)"></el-button>
                  <el-button type="danger" icon="Delete"
                             @click="extractFunc.delete(row.emrCategoryCode,$index)"></el-button>
                </el-button-group>
              </template>
            </el-table-column>
            <el-table-column prop="emrCategoryCode" label="编码"/>
            <el-table-column prop="dataExtract" label="数据元" show-overflow-tooltip/>
            <el-table-column prop="name" label="名称" show-overflow-tooltip/>
          </xc-table>
          <xc-dialog-v2 title="提取数据" v-model="extractFunc.dialog">
            <el-form>
              <el-form-item label="电子病历编码">
                <el-input v-model="extractFunc.data.emrCategoryCode"></el-input>
              </el-form-item>
              <el-form-item label="需要提取的数据元">
                <el-select
                    style="width: 540px"
                    v-model="extractFunc.data.dataExtractObj"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    placeholder="请输入需要提取的数据元名称">
                  <el-option
                      v-for="item in extractFunc.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="病历名称">
                <el-input v-model="extractFunc.data.name"></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="extractFunc.isNewData ? extractFunc.insertData() : extractFunc.save()">保存</el-button>
            </template>
          </xc-dialog-v2>
        </el-tab-pane>
        <el-tab-pane label="数据元">
          <xc-table :data="data" @currentChange="queryChange" @sizeChange="queryChange" :height="200">
            <el-table-column label="默认值">
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button type="warning" round icon="Edit" @click="openDialog(false,scope.row)"></el-button>
                  <el-button type="danger" round icon="Delete" @click="clickDelete(scope.row)"></el-button>
                </template>
              </el-table-column>
              <!--    <el-table-column prop="delFlag" label="删除" width="30"/>-->
              <el-table-column prop="id" label="uuid" width="40"/>
              <el-table-column prop="name" label="数据名称" width="80" show-overflow-tooltip/>
              <el-table-column prop="sqlSentence" label="语句内容" show-overflow-tooltip/>
            </el-table-column>
          </xc-table>
        </el-tab-pane>

      </el-tabs>


      <el-drawer v-model="editData.dialog"
                 :title="editData.title"
                 @closed="close"
                 size="90%">
        <el-row>

          <el-col :span="12">
            <el-form :model="editData.data" :label-width="90" :rules="rules" ref="formRef">

              <el-form-item prop="patNo" label="住院号">
                <el-input v-model="editData.data.patNo" @blur="editData.data.patNo = $event.target.value.trim()"
                          placeholder="请输入住院号"/>
              </el-form-item>

              <el-form-item prop="patNo" label="住院次数">
                <el-input-number style="width: 100%;" :min="1" :precision="0" v-model="editData.data.times"
                                 placeholder="请输入住院次数"/>
              </el-form-item>

              <el-form-item prop="name" label="名称">
                <el-input v-model="editData.data.name" @blur="editData.data.name = $event.target.value.trim()"
                          placeholder="请输入名称"/>
              </el-form-item>

              <el-form-item prop="dataType" label="数据类型">
                <el-radio-group v-model="editData.data.dataType">
                  <el-radio :label="0">对象</el-radio>
                  <el-radio :label="1">数组</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item prop="groupName" label="分组名称" v-if="editData.data.dataType === 1">
                <el-input v-model="editData.data.groupName" @blur="editData.data.groupName = $event.target.value.trim()"
                          placeholder="请输入分组名称"/>
              </el-form-item>

              <el-form-item prop="sqlSentence" label="语句内容">
                <el-input v-model="editData.data.sqlSentence" type="textarea"
                          :autosize="{ minRows: 30, maxRows: 40 }"
                          placeholder="请输入sql语句" @change="editData.passedTheTest = false"/>
              </el-form-item>

            </el-form>
          </el-col>

          <el-col :span="12">
            <JsonViewer :value="checkData" style="height: 100%" copyable :expandDepth="3"/>
          </el-col>

        </el-row>


        <template #footer>
          <div>
            <el-button type="primary" plain @click="testSql">测试sql</el-button>
            <el-button type="primary" @click="confirm">确认</el-button>
            <el-button @click="close">取消</el-button>
          </div>
        </template>
      </el-drawer>

      <el-dialog v-model="returnValue.dialog" title="该患者的数据" draggable>
        <JsonViewer :value="returnValue.data" style="height: 100%" copyable :expandDepth="3"/>
      </el-dialog>
    </template>
  </page-layer>
</template>

<script setup name='EmrDataMaintenance'>
import XcTable from "@/components/xiao-chan/xc-table/XcTable.vue";
import {
  addData, deleteById, deleteExtractDataSource,
  fetchCountryDictionary,
  getEmrInpatientData, getExtractDataSource, insertExtractDataSource,
  testSqlAPi, updateData, updateExtractDataSource
} from "@/api/dictionary/emr-data-maintenance-api";
import {ElMessage, ElMessageBox} from "element-plus";
import PageLayer from "@/layout/PageLayer";
import XcDialog from "@/components/xiao-chan/dialog/XcDialog.vue";
import XcDialogV2 from "@/components/xiao-chan/dialog/XcDialogV2.vue";
import {BizException, ExceptionEnum} from "@/utils/BizException";

let data = $ref({
  data: [],
  currentPage: 1,
  pageSize: 30,
  total: 0
})

let editData = $ref({
  dialog: false,
  title: '新增数据',
  isEdit: false,
  passedTheTest: false,
  data: {
    id: '',
    delFlag: '',
    name: '',
    sqlSentence: '',
    patNo: '0409327',
    times: 1,
    dataType: 0,
    groupName: ''
  }
});

let returnValue = $ref({
  dialog: false,
  data: ''
})

let extractList = $ref([])

let checkData = $ref('')

onMounted(() => {
  queryData()
  getExtractDataSource().then(res => {
    extractList = res
  })
})


const queryData = () => {
  fetchCountryDictionary(data.currentPage, data.pageSize, data.total).then((res) => {
    data.data = res.records
    data.total = data.total === 0 ? res.total : data.total
  })
}

const queryChange = () => {
  queryData()
}

const testWhetherPatientDataIsNormal = () => {
  getEmrInpatientData({patNo: editData.data.patNo, times: editData.data.times}).then((res) => {
    returnValue.dialog = true
    returnValue.data = res
  })
}

const openDialog = (isAdd, row) => {
  checkData = ''
  if (isAdd) {
    editData = {
      dialog: true,
      title: '新增数据',
      isEdit: false,
      data: {
        id: '',
        delFlag: '',
        name: '',
        sqlSentence: '',
        patNo: editData.data.patNo,
        times: editData.data.times,
        dataType: 0,
        groupName: ''
      }
    }
  } else {
    editData = {
      dialog: true,
      isEdit: true,
      title: '编辑数据',
      data: {
        id: row.id,
        delFlag: row.delFlag,
        name: row.name,
        sqlSentence: row.sqlSentence,
        patNo: editData.data.patNo,
        times: editData.data.times,
        dataType: row.dataType,
        groupName: row.groupName
      }
    }
  }
}


const clickDelete = (row) => {
  ElMessageBox.alert('您确定要删除改sql语句', '提示', {
    type: "warning"
  }).then(() => {
    deleteById(row.id).then(() => {
      queryData()
    })
  }).catch(() => {

  })
}

let formRef = $ref(null)

const rules = ref({
  patNo: [{required: true, message: '请输入住院号', trigger: 'blur'}],
  times: [{required: true, message: '请输入住院次数', trigger: 'blur'}],
  name: [{required: true, message: '请输入名称', trigger: 'blur'}],
  sqlSentence: [{required: true, message: '请输入sql语句', trigger: 'blur'}],
  groupName: [{required: true, message: '请输入分组名称', trigger: 'blur'}]
})

const testSql = () => {
  if (!formRef) return
  formRef.validate(async (valid) => {
    if (valid) {
      testSqlAPi(editData.data).then((res) => {
        if (res) {
          checkData = res;
        }
        editData.passedTheTest = true
      }).catch(e => {
        editData.passedTheTest = false
      })
    }
  })
}

const confirm = () => {
  if (!formRef) return
  formRef.validate(async (valid) => {
    if (valid) {
      if (editData.passedTheTest) {
        ElMessageBox.confirm('请确认返回数据的准确性。', '提示', {
          type: 'warning',
        }).then(async () => {
          if (editData.isEdit) {
            await updateData(editData.data)
            queryData()
          } else {
            await addData(editData.data);
            queryData()
          }
          editData.dialog = false
        }).catch(() => {

        })
      } else {
        ElMessage.error("请先通过数据测试.")
      }
    }
  })
}

const close = () => {
  editData.dialog = false
  editData.passedTheTest = false
}

const extractFunc = $ref({
  dialog: false,
  data: {
    emrCategoryCode: '',
    dataExtract: '',
    name: '',
    dataExtractObj: []
  },
  isNewData: false,
  options: [],
  open: (row) => {
    extractFunc.isNewData = false
    extractFunc.dialog = true
    extractFunc.data = row
    extractFunc.data.dataExtractObj = JSON.parse(extractFunc.data.dataExtract)
  },
  save: () => {
    extractFunc.data.dataExtract = JSON.stringify(extractFunc.data.dataExtractObj);
    extractFunc.checkData()
    updateExtractDataSource(extractFunc.data)
  },
  delete: (code, index) => {
    ElMessageBox.confirm('是否删除，操作不可逆。', '提示', {
      type: 'warning'
    }).then(() => {
      deleteExtractDataSource(code).then(() => {
        extractList.splice(index, 1)
      })
    }).catch(() => {
    })
  },
  newData: () => {
    extractFunc.isNewData = true
    extractFunc.data = {
      emrCategoryCode: '',
      dataExtract: '',
      name: '',
      dataExtractObj: []
    }
    extractFunc.dialog = true
  },
  checkData: () => {
    if (!extractFunc.data.emrCategoryCode) {
      BizException(ExceptionEnum.MESSAGE_ERROR, '编码不能为空。')
    }
    if (extractFunc.data.dataExtractObj.length === 0) {
      BizException(ExceptionEnum.MESSAGE_ERROR, '提取数据元不能为空。')
    }
    if (!extractFunc.data.name) {
      BizException(ExceptionEnum.MESSAGE_ERROR, '名称不能为空。')
    }
  },
  insertData: () => {
    extractFunc.data.dataExtract = JSON.stringify(extractFunc.data.dataExtractObj);
    extractFunc.checkData()
    insertExtractDataSource(extractFunc.data).then(() => {
      extractList.push(extractFunc.data)
    })
  }
})

</script>

<style scoped>

</style>
