<template>
  <div style="display: flex; justify-content: space-between; height: 90vh" class="app-container">
    <el-card style="width: 30%">
      <template #header>
        <span style="vertical-align: middle">病区</span>
      </template>
      <div style="width: 100%">
        <el-button type="primary" @click="onIncrease" class="mb8"> 新增 </el-button>
        <el-button type="success" plain @click="handleEnableBatch('wardRef')" class="mb8">
          批量启用
        </el-button>
        <el-button type="primary" plain @click="handleUnableBatch('wardRef')" class="mb8">
          批量停用
        </el-button>
        <el-button style="float: right" @click="getWardList()" class="mb8" icon="refresh" />
        <el-table
          max-height="630"
          :data="wardList"
          @cell-click="(row) => clickRow(row, 10, 0)"
          highlight-current-row
          ref="wardRef"
        >
          <el-table-column type="selection" :selectable="checkSelectable" width="55" />
          <el-table-column label="病区" align="center" prop="name" />
          <el-table-column label="病区号" align="center" prop="startTime">
            <template #default="scope">
              {{ getLastPartOfString(scope.row.busNo) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="statusEnum_enumText">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.statusEnum === 1 || scope.row.statusEnum === 6
                    ? 'success'
                    : scope.row.statusEnum === 2
                    ? 'primary'
                    : 'warning'
                "
              >
                {{ scope.row.statusEnum_enumText }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150">
            <template #default="scope">
              <el-button type="primary" link @click.stop="handleEdit(scope.row)"> 编辑 </el-button>
              <el-button
                type="primary"
                link
                :disabled="scope.row.statusEnum === 5"
                @click.stop="
                  () => {
                    handleUnable(scope.row, 10).then(() => {
                      getWardList();
                    });
                  }
                "
                v-if="
                  scope.row.statusEnum === 1 ||
                  scope.row.statusEnum === 6 ||
                  scope.row.statusEnum === 5
                "
              >
                停用
              </el-button>
              <el-button
                type="primary"
                link
                :disabled="scope.row.statusEnum === 5"
                @click.stop="
                  () => {
                    handleEnable(scope.row).then(() => {
                      getWardList();
                    });
                  }
                "
                v-else-if="scope.row.statusEnum === 2"
              >
                启用
              </el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <div style="width: 69%; height: 100%; padding-bottom: 20px">
      <el-card style="margin-bottom: 20px">
        <template #header>
          <span style="vertical-align: middle">病房</span>
        </template>
        <el-button type="success" plain @click="handleEnableBatch('hourseRef')">批量启用</el-button>
        <el-button type="primary" plain @click="handleUnableBatch('hourseRef')">批量停用</el-button>
        <el-table
          height="280"
          :data="houseList"
          @cell-click="(row) => clickRow(row, 8, 0, 1)"
          highlight-current-row
          v-loading="loading"
          ref="hourseRef"
        >
          <el-table-column type="selection" :selectable="checkSelectable" width="55" />
          <el-table-column label="病房" align="center" prop="name" />
          <el-table-column label="病房号" align="center" prop="busNo">
            <template #default="scope">
              {{ getLastPartOfString(scope.row.busNo) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="statusEnum_enumText">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.statusEnum === 1 || scope.row.statusEnum === 6
                    ? 'success'
                    : scope.row.statusEnum === 2
                    ? 'primary'
                    : 'warning'
                "
              >
                {{ scope.row.statusEnum_enumText }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" link @click.stop="handleEdit(scope.row, 4)">
                编辑
              </el-button>
              <el-button
                type="primary"
                link
                :disabled="scope.row.statusEnum === 5"
                @click.stop="
                  () => {
                    handleUnable(scope.row).then(() => {
                      getHouseList();
                    });
                  }
                "
                v-if="
                  scope.row.statusEnum === 1 ||
                  scope.row.statusEnum === 6 ||
                  scope.row.statusEnum === 5
                "
              >
                停用
              </el-button>
              <el-button
                type="primary"
                link
                :disabled="scope.row.statusEnum === 5"
                @click.stop="
                  () => {
                    handleEnable(scope.row).then(() => {
                      getHouseList();
                    });
                  }
                "
                v-else-if="scope.row.statusEnum === 2"
              >
                启用
              </el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card>
        <template #header>
          <span style="vertical-align: middle">床位</span>
        </template>
        <el-button type="success" plain @click="handleEnableBatch('bedRef')">批量启用</el-button>
        <el-button type="primary" plain @click="handleUnableBatch('bedRef')">批量停用</el-button>
        <el-table ref="bedRef" height="270" :data="bedList" v-loading="loading" width="">
          <el-table-column type="selection" :selectable="checkSelectable" width="55" />
          <el-table-column label="病床" align="center" prop="name" />
          <el-table-column label="病床号" align="center" prop="busNo">
            <template #default="scope">
              {{ getLastPartOfString(scope.row.busNo) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="statusEnum_enumText">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.statusEnum === 1 || scope.row.statusEnum === 6
                    ? 'success'
                    : scope.row.statusEnum === 2
                    ? 'primary'
                    : 'warning'
                "
                >{{ scope.row.statusEnum_enumText }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" link @click.stop="handleEdit(scope.row, 10)">
                编辑
              </el-button>
              <el-button
                type="primary"
                link
                :disabled="scope.row.statusEnum === 5"
                @click.stop="
                  () => {
                    handleUnable(scope.row, 10).then(() => {
                      getBedList();
                    });
                  }
                "
                v-if="
                  scope.row.statusEnum === 1 ||
                  scope.row.statusEnum === 6 ||
                  scope.row.statusEnum === 5
                "
              >
                停用
              </el-button>
              <el-button
                type="primary"
                link
                :disabled="scope.row.statusEnum === 5"
                @click.stop="
                  () => {
                    handleEnable(scope.row, 10).then(() => {
                      getBedList();
                    });
                  }
                "
                v-else-if="scope.row.statusEnum === 2"
              >
                启用
              </el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-dialog :title="title" v-model="open" width="600px" @close="cancel" append-to-body>
      <el-form ref="orgRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="id" prop="id" v-show="false">
          <el-input v-model="form.id" placeholder="请输入科室编号" />
        </el-form-item>
        <el-form-item label="科室编号" prop="busNo" v-show="false">
          <el-input v-model="form.busNo" placeholder="请输入科室编号" />
        </el-form-item>
        <el-form-item :label="type + '分类'" prop="formEnum">
          <el-radio-group v-model="form.formEnum" @change="handleRadioChange" :disabled="isEdit">
            <el-radio :label="4">病区</el-radio>
            <el-radio :label="10">病房</el-radio>
            <el-radio :label="8">床位</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="type + '名称'" prop="name">
          <el-input v-model="form.name" :placeholder="'请输入' + type + '名称'" />
        </el-form-item>
        <el-col>
          <el-form-item :label="upLabel" prop="busNoParent">
            <template v-if="form.formEnum == 4">
              <el-tree-select
                clearable
                style="width: 100%"
                v-model="form.busNoParent"
                filterable
                :data="organization"
                :props="{
                  value: 'id',
                  label: 'name',
                  children: 'children',
                }"
                value-key="id"
                check-strictly
                placeholder="请选择上级科室/病区/床位"
              />
            </template>
            <template v-else>
              <el-select
                v-model="form.busNoParent"
                placeholder="请选择上级科室/病区/床位"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in wardListOption"
                  :key="item.busNo"
                  :label="item.name"
                  :value="item.busNo"
                />
              </el-select>
            </template>
          </el-form-item>
        </el-col>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Ward">
import {onMounted, ref} from 'vue';
import {
  addLocation,
  deleteLocation,
  editLocation,
  enableLocation,
  getList,
  getOrgList,
  unableLocation,
} from './components/api';
import {ElMessage} from 'element-plus';

const { proxy } = getCurrentInstance();
// 病区参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 50,
  formEnum: 4, //4 病区 10 病房 8床位
  // locationFormList: [4],
});
// 病房参数
const queryHouseParams = ref({
  pageNum: 1,
  pageSize: 50,
  formEnum: 10, //4 病区 10 病房 8床位
  // locationFormList: [4],
});
// 病床参数
const querybedParams = ref({
  pageNum: 1,
  pageSize: 50,
  formEnum: 8, //4 病区 10 病房 8床位
  // locationFormList: [4],
});
// 病区、病房、病床类型
const type = ref('病区');
// 病区列表
const wardList = ref([]);
// 床位列表
const bedList = ref([]);
// 病房列表
const houseList = ref([]);
const wardListOption = ref([]);
const organization = ref([]);
const loading = ref(false);
const isEdit = ref(false);
const open = ref(false);
// 病区row
const wardRow = ref({});
// 床位row
const bedRow = ref({});
// 病房row
const houseRow = ref({});
// 记录点击的是启用
const clickType = ref(0);
const orgRef = ref();
// 新增数据参数
const form = reactive({
  formEnum: 4,
  busNoParent: '',
  organizationId: '',
  name: '',
  busNo: '',
});
const upLabel = ref('关联科室');
const title = ref('新增');
const rules = ref({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { required: true, min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  busNoParent: [
    {
      required: form.formEnum != 4,
      message: '请选择上级' + type.value,
      trigger: 'blur',
    },
  ],
});
// 获取科室下啦树
function init() {
  getOrgList().then((res) => {
    organization.value = res.data.records;
  });
}
/**
 * 病区列表
 */
function getWardList() {
  houseList.value = [];
  bedList.value = [];
  getList(queryParams.value).then((res) => {
    wardList.value = res.data.records;
  });
}
// 获取病房列表
const getHouseList = () => {
  // 4病区 10病房 8床位
  loading.value = true;
  // 病区号
  queryHouseParams.value.busNo = wardRow.value.busNo;
  bedList.value = [];
  getList(queryHouseParams.value).then((res) => {
    houseList.value = res.data.records;
    loading.value = false;
  });
};
// 获取床位列表
const getBedList = () => {
  // 4病区 10病房 8床位
  loading.value = true;
  querybedParams.value.busNo = houseRow.value.busNo;
  bedList.value = [];
  getList(querybedParams.value).then((res) => {
    bedList.value = res.data.records;
    loading.value = false;
  });
};
// 点击新增按钮
const onIncrease = () => {
  open.value = true;
};

// 查询病房和病区的下拉选
const getHomeOrBed = (formEnum) => {
  const params = {
    formEnum,
    pageNum: 1,
    pageSize: 50,
  };
  getList(params).then((res) => {
    if (formEnum == 10) {
      const datas = res.data?.records || [];
      const optionsList = datas.map((item) => {
        let obj = {
          ...item,
        };
        obj.name = item.parentName + '-' + item.name;
        return obj;
      });
      wardListOption.value = optionsList;
    } else {
      wardListOption.value = res.data?.records || [];
    }
  });
};

function handleRadioChange(val) {
  let formEnum = 4;
  if (val == 4) {
    type.value = '病区';
    upLabel.value = '关联科室';
    return;
  } else if (val == 10) {
    type.value = '病房';
    upLabel.value = '所属病区';
    formEnum = 4;
    // queryParams.value.formEnum = 4;
  } else {
    type.value = '床位';
    upLabel.value = '所属病房';
    formEnum = 10;
    // queryParams.value.formEnum = 10;
  }
  form.organizationId = '';
  form.busNo = '';
  form.busNoParent = '';
  form.name = '';
  getHomeOrBed(formEnum);
}

/**
 * 点击患者列表行 获取处方列表
 */
function clickRow(row, val, type) {
  // 1点击了启用
  clickType.value = type;
  console.log('val=====>', JSON.stringify(row));
  console.log('type=====>', JSON.stringify(type));
  console.log('val=====>', JSON.stringify(val));
  // if (type !== 1) {
  //   if (val == 10) {
  //     wardRow.value = row;
  //     getHouseList();
  //   } else if (val == 8) {
  //     houseRow.value = row;
  //     getBedList();
  //   }
  // } else {
  //   if (val == 10) {
  //     houseRow.value = row;
  //     getHouseList();
  //   } else if (val == 8) {
  //     bedRow.value = row;
  //     getBedList();
  //   }
  // }
  if (val == 10) {
    wardRow.value = row;
    getHouseList();
  } else if (val == 8) {
    houseRow.value = row;
    console.log('houseRow=====>', houseRow.value);

    getBedList();
  }
}

function checkSelectable(row, index) {
  return row.statusEnum !== 5;
}

function handleEnable(row) {
  return enableLocation([row.id]).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('启用成功');
    }
  });
}

function handleUnable(row) {
  return unableLocation([row.id]).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('停用成功');
    }
  });
}

function handleEnableBatch(tableRef) {
  let list = proxy.$refs[tableRef].getSelectionRows().map((item) => {
    return item.id;
  });
  if (list.length == 0) {
    proxy.$modal.msgError('请选择要启用的数据');
    return;
  }
  enableLocation(list).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess(res.message);
    }
  });
}

function handleUnableBatch(tableRef) {
  let list = proxy.$refs[tableRef].getSelectionRows().map((item) => {
    return item.id;
  });
  if (list.length == 0) {
    proxy.$modal.msgError('请选择要停用的数据');
    return;
  }
  unableLocation(list).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess(res.message);
    }
  });
}

// 新增病床拆分"busNo": "LOC055.LOC056",
const splitBusNo = (busNo) => {
  const busNoArr = busNo.split('.') || [];
  let busNoParent = '';
  if (busNoArr.length > 1) {
    busNoParent = busNoArr[0];
  }
  return busNoParent;
};
function submitForm() {
  if (!orgRef) return;
  const params = {
    ...form,
  };
  console.log('form========>', JSON.stringify(form));
  console.log('params11========>', JSON.stringify(params));
  orgRef.value.validate((valid) => {
    if (valid) {
      console.log('表单验证通过，准备提交数据');

      if (form.busNoParent) {
        if (form.formEnum == 4) {
          params.organizationId = form.busNoParent;
        } else {
          if (!isEdit.value) {
            params.busNo = form.busNoParent;
            // params.busNoParent = splitBusNo(form.busNoParent);
          }
        }
      } else {
        if (form.formEnum == 4) {
          if (!(params.organizationId && params.organizationId.length > 0)) {
            ElMessage({
              type: 'error',
              message: '请选择关联科室!',
            });
            return;
          }
        } else if (form.formEnum == 10) {
          if (!(params.busNo && params.busNo.length > 0)) {
            ElMessage({
              type: 'error',
              message: '请选择所属病区!',
            });
            return;
          }
        } else {
          if (!(params.busNo && params.busNo.length > 8)) {
            ElMessage({
              type: 'error',
              message: '请选择所属病房!',
            });
            return;
          }
        }
      }
      // console.log('params========>', JSON.stringify(form));
      console.log('params========>', JSON.stringify(params));
      // console.log('params========>', isEdit.value);
      if (!isEdit.value) {
        addLocation(params).then((res) => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('操作成功');
            if (params.formEnum == 4) {
              cancel();
              getWardList();
            } else if (params.formEnum == 10) {
              getHouseList();
              open.value = false;
            } else if (params.formEnum == 8) {
              getBedList();
              open.value = false;
            }
          }
        });
      } else {
        editLocation(params).then((res) => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('操作成功');
            if (params.formEnum == 4) {
              cancel();
              getWardList();
            } else if (params.formEnum == 10) {
              getHouseList();
              open.value = false;
            } else if (params.formEnum == 8) {
              getBedList();
              open.value = false;
            }
          }
        });
      }
    }
  });
}

function handleDelete(row) {
  deleteLocation(row.busNo).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('删除成功');
      if (row.formEnum == 4) {
        getWardList();
      } else if (row.formEnum == 10) {
        getHouseList();
      } else {
        getBedList();
      }
    }
  });
}

function getLastPartOfString(str) {
  const parts = str.split('.');
  return parts.pop();
}

function handleEdit(row, val) {
  console.log('editRow=========>', JSON.stringify(row));

  form.id = row.id;
  form.name = row.name;
  form.formEnum = row.formEnum;
  form.busNo = row.busNo;
  if (row.organizationId) {
    form.busNoParent = row.organizationId;
    form.organizationId = row.organizationId;
  } else {
    form.busNoParent = row.busNo.split('.').slice(0, -1).join('.');
  }
  isEdit.value = true;
  title.value = '编辑';
  open.value = true;
  console.log('editRow1=========>', JSON.stringify(form));
  if (val == 4) {
    getHomeOrBed(4);
  } else if (val == 10) {
    getHomeOrBed(10);
  }
}

function cancel() {
  open.value = false;
  form.id = undefined;
  form.name = '';
  form.formEnum = 4;
  form.busNo = '';
  form.busNoParent = '';
  form.organizationId = '';
  isEdit.value = false;
  title.value = '新增';
}
// 页面挂在成功
onMounted(() => {
  // 获取所有科室
  init();
  // 获取病区列表
  getWardList();
});
</script>

<style scoped></style>
