<template>
  <view class="container" @click.stop="elementTracker">
    <view class="content">
      <view class="search">
        <view class="search_box">
          <input :class="isFocus ? 'search_input' : 'search_input_none'" placeholder="搜索科室或医生"
            :placeholder-class="isFocus ? 'placeholder' : 'placeholder_none'" :value="searchValue" data-type="focus"
            data-key="searchValue" @focus="focusFn" @input="setVal"></input>
          <image class="search_icon" :class="{ 'search_icon_none': isFocus }" :src="iconUrl.search"></image>
          <image class="remove_icon" v-if="isFocus" :src="iconUrl.cha" @click.stop="focusFn" data-type="blur"></image>
          <view v-if="isFocus" class="search_confirm backgroundCustom_F08"
            :class="{ 'search_confirm_active': isFocus }" @click="searchClick">搜索</view>
        </view>
      </view>

      <view class="search_con" @click="focusFn" data-type="blur" v-if="isFocus">
        <view class="search_con_inner" @click.stop="doNothing">
          <view class="search_con_list">
            <view class="search_con_list_inner">
              <view class="search_con_item border_top" v-for="(item, index) in searchList" :key="index"
                @click="deptClick(item, index, 'search')">
                {{ item.SearchType == '2' ? item.DoctorName + " " + item.DeptName : item.DeptName }}
                <image class="public_right_img" :src="iconUrl.icon_right"></image>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="img_box displayFlexBetween">
        <view class="img_item displayFlexCol" @click="optionClick('ai')" v-if="pageConfig.aiMode && pageConfig.aiMode.showAi">
          <image class="img" :src="iconUrl.ai"></image>
          <view class="text">
            <view>AI智能导诊</view>
            <view style="font-size: 26upx;opacity: 0.6;margin-top: 20upx;">不懂挂哪个科室？</view>
          </view>
        </view>
        <view class="img_item displayFlexCol" @click="optionClick('history')">
          <image class="img" :src="iconUrl.doctor_history"></image>
          <view class="text">
            <view>查看历史医生</view>
            <view style="font-size: 26upx;opacity: 0.6;margin-top: 20upx;">预约看过的医生？ </view>
          </view>
        </view>
      </view>
    </view>
    <view class="dept_list">
      <view class="dept_list_inner">
        <view class="dept_list_fir" :class="{ 'dept_list_fir_short': pageConfig.showDeptSec }">
          <view class="dept_item"
            :class="{ 'dept_item_active colorCustom': index == deptListFirIndex, 'toBoderRadio': index == deptListFirIndex - 1 }"
            v-for="(item, index) in deptListFir" :key="index" @click="deptClick(item, index, 'fir')">
            <view class="dept_item_inner" :class="{ 'border_bottom': !pageConfig.showDeptSec }">
              {{ item.DeptName }}
            </view>
          </view>
        </view>

        <view class="dept_list_sec" v-if="pageConfig.showDeptSec">
          <view class="dept_item border_bottom" v-for="(item, index) in deptListSec" :key="index"
            @click="deptClick(item, index, 'sec')">
            {{ item.DeptName }}
          </view>
        </view>
      </view>
    </view>
    <richTextModal :modalData="modalData" v-if="modalData.showModal" @cancel="modalCancel" @confirm="modalConfirm"
      @noData="modalNoData"></richTextModal>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { common, pagesPatientFn } from '@/utils';
import icon from '@/utils/icon';
import { 
  queryClinicBaseDept, 
  searchClinicDeptAndDoctor, 
  queryDeptList_V2, 
  queryDoctorList_V2 
} from '@/pagesPatient/service/yygh';
import richTextModal from '@/pages/st1/components/richTextModal/richTextModal.vue';

const app = getApp();
const iconUrl = ref(icon);
const isFocus = ref(false); // input是否获取焦点
const searchValue = ref(''); // 搜索值
const searchList = ref<any[]>([]); // 搜索结果 
const deptListFir = ref<any[]>([]); // 一级科室
const deptListFirIndex = ref(-1); // 当前一级科室
const deptListSec = ref<any[]>([]); // 二级科室
const deptListSecIndex = ref(-1); // 当前二级科室
const pageConfig = ref<any>({}); // 页面配置
const serviceId = ref('');
const queryData = ref<any>({
  HosId: '',
  ParentDeptCode: "",
  ServiceId: ""
});
const modalData = ref<any>({});

 onLoad((options: any) => {
  pageConfig.value = common.deepCopy(app.globalData.config.pageConfiguration.yyghDeptList_config);
  serviceId.value = options.serviceId || '';
  queryData.value.HosId = app.globalData.districtId || app.globalData.hosId;
  queryData.value.ServiceId = options.serviceId || '';
  
  main();
});

onShow(() => {

});

const main = async () => {
  let pConfig = pageConfig.value;
  // 获取一级科室
  let dListFir: any[] = [];
  let dListSec: any[] = [];
  let qData = queryData.value;
  
  let deptListFirResp = await queryClinicBaseDept(qData);
  if (!common.isEmpty(deptListFirResp)) {
    dListFir = deptListFirResp;
    if (pConfig.showDeptSec) {
      // 如果有二级科室 默认取第一个一级科室 
      qData.ParentDeptCode = dListFir[0].DeptCode;
      let deptListSecResp = await queryClinicBaseDept(qData);
      if (!common.isEmpty(deptListSecResp)) {
        dListSec = deptListSecResp;
      }
    }
  }
  
  deptListFir.value = dListFir;
  deptListSec.value = dListSec;
  deptListFirIndex.value = pConfig.showDeptSec ? 0 : -1;
  modalData.value = pConfig.modalData;
};

/**
 * 科室点击
 */
const deptClick = async (item: any, index: number, type: string) => {
  let pageType = "";
  let pConfig = pageConfig.value;
  
  if (type == 'fir') {
    // 如果点击一级科室
    deptListFirIndex.value = index;
    if (pConfig.showDeptSec) {
      // 如果医院有二级科室  
      deptListSec.value = [];
      let qData = queryData.value;
      qData.ParentDeptCode = item.DeptCode;
      let resp = await queryClinicBaseDept(qData);
      if (!common.isEmpty(resp)) {
        deptListSec.value = resp;
        deptListSecIndex.value = -1;
      }
    } else {
      pageType = 'yyghDoctorList';
    }
  } else if (type == 'sec') {
    // 如果点击二级科室
    deptListSecIndex.value = index;
    pageType = 'yyghDoctorList';
  } else {
    // 搜索结果点击
    pageType = 'yyghDoctorList';
    if (item.SearchType == '2') {
      /**如果点击医生 跳转到挂号页面*/
      pageType = "yyghClinicMsg";
    }
  }
  
  // 模拟事件对象，用于 handleRouter
  let e = {
    currentTarget: {
      dataset: {
        item: item
      }
    }
  };

  // 判断如果不为空就是跳转
  if (common.isNotEmpty(pageType)) {
    // 判断等于跳转医生列表页 且有配置特殊科室续弹窗显示内容
    if (pageType == 'yyghDoctorList' && pConfig.deptShowMode && pConfig.deptShowMode[item.DeptCode]) {
      common.showModal(pConfig.deptShowMode[item.DeptCode], () => {
        pagesPatientFn.handleRouter(e, pageType, serviceId.value);
      });
    } else {
      pagesPatientFn.handleRouter(e, pageType, serviceId.value);
    }
  }
};

/**
 * 点击搜索
 */
const searchClick = async () => {
  let pConfig = pageConfig.value;
  let sValue = searchValue.value;
  if (common.isEmpty(sValue)) {
    common.showModal('请输入搜索科室或医生');
    return;
  }
  let result: any[] = [];
  let qData = {
    HosId: app.globalData.districtId || app.globalData.hosId,
    SearchLike: sValue,
    ServiceId: serviceId.value,
    QueryLocal: "1",
    UseBaseInfo: true,
    ExcludeOneLv: pConfig.showDeptSec ? 1 : 0, // 是否过滤一级科室，
  };
  let resp = await searchClinicDeptAndDoctor(qData);
  if (!common.isEmpty(resp)) {
    result = resp;
  }
  searchList.value = result;
};

// 搜索科室 (Seems unused in original code but kept for completeness if needed)
const queryDeptList = async (sValue: string) => {
  let qData = {
    dept: {
      hospitalId: app.globalData.districtId || app.globalData.hosId,
      deptNameOrPingyinLike: sValue,
      status: 1
    },
    deptdoctor: {
      doctorServiceGh: 1,
      displaystatus: 1,
    },
    doctor: {},
  };
  let resp: any = await queryDeptList_V2(qData);
  if (!common.isEmpty(resp)) {
    if (pageConfig.value.showDeptSec) {
      resp = resp.filter((item: any) => item.parientId != -1);
    }
    resp = common.changeObj(resp);
    return resp;
  }
  return [];
};

// 搜索医生 (Seems unused in original code but kept for completeness if needed)
const queryDoctorList = async (sValue: string) => {
  let qData = {
    isQueryDeptList: "1", // "是否返回医生的科室列表",
    doctor: {
      doctorNameOrPingYinLike: sValue, // "拼音检索-模糊"
      status: 1
    },
    dept: {
      hospitalId: app.globalData.districtId || app.globalData.hosId,
      status: 1
    },
    deptdoctor: {
      doctorServiceGh: 1, // "是否开通挂号服务"
      displaystatus: "1" // "是否启用"
    }
  };
  let resp: any = await queryDoctorList_V2(qData);
  if (!common.isEmpty(resp)) {
    let doctorList: any[] = [];
    resp.map((item: any) => {
      item.searchType = '2'; // 医生数据做一个标识
      item.deptList.map((ele: any) => { // 方向把当前医生所有的坐诊科室排列出来
        doctorList.push({ ...ele, ...item });
      });
    });
    doctorList = common.changeObj(doctorList);
    return doctorList;
  }
  return [];
};

/**
 * 输入框聚焦
 */
const focusFn = (e: any) => {
  let type = e.currentTarget.dataset.type;
  isFocus.value = type == 'focus' ? true : !isFocus.value;
  if (type != 'focus') {
     // Blur or other action, maybe clear search value?
     // Original logic: searchValue: type == 'focus' ? this.data.searchValue : '',
     searchValue.value = '';
     searchList.value = [];
  }
};

/**
 * 输入值获取
 */
const setVal = (e: any) => {
  // let key = e.currentTarget.dataset.key; // unused in ref
  let value = e.detail.value;
  searchValue.value = value;
};

/**
 * 空函数 阻止搜索结果点击冒泡
 */
const doNothing = () => {

};

/**
 * ai导诊 历史医生点击
 */
const optionClick = (type: string) => {
  if (type == 'ai') {
    // 点击ai导诊
    // 跳转密影  根目录加公众号appid
    uni.navigateToMiniProgram({
      appId: pageConfig.value.aiMode.appId,
      // appid=:   需要自行对接配置相应医院的公众号appId
      path: pageConfig.value.aiMode.path
    });
  } else {
    // 点击历史医生
    common.goToUrl('/pagesPatient/st1/business/yygh/yyghHistoryDoctor/yyghHistoryDoctor');
  }
};

// 就诊须知弹窗关闭
const modalCancel = () => {
  common.navigateBack(1);
};

const modalConfirm = () => {
  modalData.value.showModal = false;
};

const modalNoData = () => {
  common.navigateBack(1);
};

const elementTracker = () => {
  // Placeholder for elementTracker if needed
};
</script>

<style scoped>
@import "@/pagesPatient/st1/static/css/search.css";

.content {
  padding-top: 110upx;
  position: relative;
  z-index: 10;
}

.search_con {
  width: 100%;
  position: fixed;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  top: 0;
  left: 0;
  z-index: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}

.search_con_inner {
  width: 100%;
  background-color: #fff;
  padding: 0 0 10upx 30upx;
}

.search_con_list {
  overflow: auto;
  padding-top: 110upx;
  -webkit-overflow-scrolling: touch;
}

.search_con_list_inner {
  width: 100%;
  display: inline-block;
  margin-top: -1px;
}

.search_con_item {
  font-size: 32upx;
  padding: 36upx 0;
  color: #222326;
}

.public_right_img {
  right: 30upx;
}

/* =============== */
.img_box {
  width: 100%;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  padding: 10upx 30upx 30upx;
  background-color: #fff;
}

.img_item {
  width: 333upx;
  height: 160upx;
  position: relative;
  align-items: flex-start;
  padding: 0 30upx;
}

.img_item .img {
  position: absolute;
  top: 0;
  left: 0;
}

.img_item .text {
  position: relative;
  font-size: 32upx;
  font-family: PingFang SC;
  font-weight: 800;
  color: #FFFFFF;
}

/* =============== */
.dept_list {
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 95%;
  padding: 330upx 30upx 0;
}

.dept_list_inner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  overflow: hidden;
  border-radius: 24upx;
  height: 100%;
}

.dept_list_fir {
  height: 100%;
  overflow: auto;
  width: 100%;
  -webkit-overflow-scrolling: touch;
  background-color: #fff;
}

.dept_list_fir_short {
  max-width: 316upx;
}

.dept_list_fir_short .dept_item {
  background: #F7F7FC;
}

.dept_list_sec {
  height: 100%;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  width: 410upx;
  background-color: #fff;
}

.dept_list_sec .dept_item {
  text-indent: 30upx;
  display: flex;
  align-items: center;
  justify-content: start;
  padding: 34upx 0 34upx 30upx;
  line-height: 44upx;
}

.dept_item {
  font-size: 28upx;
  position: relative;
  color: #222326;
  padding-left: 30upx;
  padding-right: 30upx;
}

.dept_item_inner {
  padding: 34upx 0;
  line-height: 44upx;
}

.dept_item_active {
  font-size: 32upx;
  font-weight: bold;
}

.dept_list_fir_short .dept_item_active {
  background-color: #fff;
}

.dept_list_fir_short .dept_item_active+.dept_item {
  border-radius: 0 30upx 0 0;
}

.toBoderRadio {
  border-radius: 0 0 30upx 0;
}
</style>
