<template>
  <xc-table :local-data="data" :height="40">
    <el-table-column label="质控名称" prop="name"/>
    <el-table-column label="时效(小时)" prop="prescription"/>
    <el-table-column label="描述" prop="promptStatement"/>
    <el-table-column label="是否开启" prop="offOrOnRule">
      <template #default="{row}">
        <el-switch
            v-model="row.offOrOnRule"
            :active-value="1"
            :inactive-value="0"
            @change="onOff(row.id,row.offOrOnRule)"
            active-text="开启"
            inactive-text="关闭"/>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="{row}">
        <el-button type="danger" @click="deleteQualityControl(row.id)">删除</el-button>
        <el-button type="warning">修改</el-button>
      </template>
    </el-table-column>
  </xc-table>

  <xc-dialog-v2 v-model="dialog"
                title="病历时效限制">
    <el-form :label-width="120">
      <el-form-item label="入参数据元：">
        <el-select v-model="ruleForm.sql" @change="selectChange" ref="selectRef">
          <el-option v-for="item in ruleDataElement"
                     :label="item.name"
                     :value="item.sql_sentence"
                     :key="item.sql_sentence"
                     :title="item.group_name"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="时效(小时)：">
        <el-input v-model.number="ruleForm.prescription">
          <template #prepend>
            {{ selectRef?.selectedLabel }}
          </template>
          <template #append> 小时后</template>
        </el-input>
      </el-form-item>

      <el-form-item label="病历编码：">
        <el-tree-select
            style="width: 100%"
            class="tree-select"
            v-model="value"
            :data="emrTree"
            @clear=""
            @remove-tag="removeTag"
            multiple
            @node-click="nodeClick"
            :props="defaultProps"
            check-strictly
            :render-after-expand="false">
          <template #default="{data}">
            <div style="display: flex;justify-content: space-between;align-items: center">
              <div>
                {{ data.name }}
              </div>
              <div v-if="data.children && data.children.length > 0">
                <el-button text @click.stop="selectAll(data.children)">全选</el-button>
              </div>
            </div>
          </template>
        </el-tree-select>
      </el-form-item>

      <el-form-item label="提示语：">
        <el-input v-model="ruleForm.promptStatement" show-word-limit maxlength="50"/>
      </el-form-item>

      <el-form-item>
        <el-switch
            v-model="ruleForm.offOrOnRule"
            :active-value="1"
            :inactive-value="0"
            active-text="开启"
            inactive-text="关闭"/>
      </el-form-item>

    </el-form>

    <template #footer>
      <el-button>取消</el-button>
      <el-button @click="confirm">确认</el-button>
    </template>
  </xc-dialog-v2>

</template>

<script setup name='EmrControlRule' lang="ts">
import XcTable from "@/components/xiao-chan/xc-table/XcTable.vue";
import {nextTick, onMounted, Ref, ref} from "vue";
import XcDialogV2 from "@/components/xiao-chan/dialog/XcDialogV2.vue";
import {
  getEmrTree,
} from "@/api/zhu-yuan-yi-sheng/emr-patient";
import {
  addRule,
  getAvailableObjects,
  getRuleList,
  switchQualityControl
} from '@/api/zhu-yuan-yi-sheng/emr-control-rule'
import {ElMessageBox} from "element-plus";

const data: Ref<Array<any>> = ref([])
const dialog: Ref<boolean> = ref(false)
const emrTree = ref([])
const ruleDataElement: Ref<Array<any>> = ref([])

const defaultProps = {
  children: 'children',
  label: 'name',
  value: '_id',
  disabled: (data) => {
    return data.children && data.children.length > 0;
  }
}

interface ruleFormClass {
  medicalRecord: Map<string, any>,
  // 病历编码
  medicalRecordCode: Array<string>,
  type: number,
  data: any,
  offOrOnRule: number
  promptStatement: string
  name: string
  sql: string
  prescription: number
}

const ruleForm: Ref<ruleFormClass> = ref({
  type: 1,
  medicalRecord: {},
  medicalRecordCode: {},
  data: {},
  offOrOnRule: 1,
  promptStatement: '超过了 24 小时无法创建',
  name: '',
  sql: '',
  prescription: 24
})

/**
 * 全选
 * @param list
 */
const selectAll = (list) => {
  list.forEach(data => {
    ruleForm.value.medicalRecord[data._id] = {
      code: data.code,
      name: data.name
    }
    if (value.value.indexOf(data._id) === -1) {
      value.value.push(data._id);
    }
  })
}

/**
 * 编码点击
 * @param data
 */
const nodeClick = (data) => {
  if (data.children) return
  if (ruleForm.value.medicalRecord[data._id]) {
    uncheck(data._id)
  } else {
    ruleForm.value.medicalRecord[data._id] = {
      code: data.code,
      name: data.name
    }
  }
}

/**
 * 移除标签
 * @param data
 */
const removeTag = (data) => {
  uncheck(data)
}

/**
 * 删除数据
 * @param value
 */
const uncheck = (value) => {
  delete ruleForm.value.medicalRecord[value]
}

const selectRef = ref(null)
const selectChange = async () => {
  await nextTick()
}

const confirm = () => {
  let temp = new Set()
  for (let key in ruleForm.value.medicalRecord) {
    temp.add(ruleForm.value.medicalRecord[key].code)
  }
  ruleForm.value.medicalRecordCode = Array.from(temp)
  ruleForm.value.type = 1
  addRule(ruleForm.value)
  console.log(ruleForm.value)
}

const value: Ref<Array<string>> = ref([])


const onOff = async (id, val) => {
  await switchQualityControl(id, val)
}

const deleteQualityControl = (val) => {
  ElMessageBox.confirm('是否要删除该质控！', '提示', {
    type: 'warning'
  }).then((res) => {
    console.log(val)
  }).catch((e) => {

  })
}

onMounted(() => {
  getEmrTree('hosp').then((res) => {
    emrTree.value = res.all[0].children
  })

  getRuleList().then((res) => {
    console.log(res)
    data.value = res
  })

  getAvailableObjects().then((res) => {
    ruleDataElement.value = res
    console.log(res)
  })

})

</script>

<style lang="scss">
.tree-select {
  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background-color: #f5f7fa !important;
    color: black;
  }
}

.select_div {
  min-height: 20px;
  width: 100%;
  border: 1px solid;
  border-radius: 4px;

  table-layout: fixed;
  word-break: break-all;
  overflow: hidden;

  .select_input {
    margin-left: 3px;
  }

  span {
    border-radius: 2px;
    background-color: #f0f2f5;
    padding: 0 5px;
    margin: 4px;

    i {
      cursor: pointer;
      font-size: 12px;
      width: 14px;
      height: 14px;
      border-radius: 50%;
    }
  }
}
</style>
