<template>
  <view class="container" :class="{ 'fixed': dialogIsShow }" :hidden="!showCon">
    <view class="content">
      <view class="userInfoTopFixe">
        <view class="date_list" v-if="serviceId != '009'">
          <view class="date_item date_item_hasList date_item_all" :class="{ 'backgroundCustom': timeActive === '' }"
            @click="timeClick" v-if="pageConfig.hasAllSchedules">
            全部
          </view>
          <view class="date_item date_item_hasList" :class="{ 'backgroundCustom': timeActive === index, 'colorCustom_999': item.HasSchedule != 1 }"
            v-for="(item, index) in timeList" :key="index" @click="item.HasSchedule == 1 ? timeClick($event, item, index) : null">
            <text>{{ item.WeekName }}</text>
            <text class="month">{{ item.RegDateNotYear }}</text>
          </view>
        </view>

        <view class="nav">
          <view class="nav_inner">
            <view class="nav_tit_val">是否仅显示可约医生</view>
            <switch class="public_switch" :checked="reducibleOnly" color="var(--dominantColor)" @change="switchChange"></switch>
          </view>
        </view>
      </view>
      <view class="doctor_list" :class="{ 'doctor_list100': serviceId == '009' }" v-if="!showNoData">
        <view class="doctor_item" v-for="(doctorItem, doctorIndex) in doctorList" :key="doctorIndex">
          <view class="doctor_item_nav" @click="doctorInfoClick(doctorItem)">
            <view class="doctor_item_nav_img">
              <image :src="doctorItem.PhotoUrl || iconUrl.icon_doctor" mode="widthFix"></image>
            </view>
            <view class="doctor_item_nav_tit">
              <view class="doctor_item_nav_subtit">
                <text class="doctor_item_nav_subtit_val">{{ doctorItem.DoctorName }}</text>
                <text v-if="doctorItem.DoctorTitle || doctorItem.Title" class="doctor_item_nav_subtit_txt">{{ doctorItem.DoctorTitle || doctorItem.Title }}</text>
              </view>
              <view v-if="doctorItem.Spec" class="doctor_item_nav_info">
                {{ doctorItem.Spec }}
              </view>
            </view>
          </view>
          <view class="scheduling_box" v-for="(schedulItem, schedulIndex) in doctorItem.Scheduling" :key="schedulIndex">
            <view class="scheduling_dept_box displayFlexBetween" @click="foldList(doctorIndex, schedulIndex)">
              <view class="scheduling_deptName_box displayFlexRow">
                <view class="backgroundCustom "></view>
                <text>{{ schedulItem.DeptName }}</text>
              </view>
              <image class="arrow" :class="{ 'transform_rotate_90': schedulItem.Check }" :src="iconUrl.icon_right"></image>
            </view>
            <view class="time_list" v-if="schedulItem.Check">
              <view class="time_item displayFlexCol" :class="{ 'time_item_stop': (item.IsHalt == 7 && item.WaitLeaveCount <= 0) || item.IsHalt == 2 }"
                v-for="(item, index) in (schedulItem.showAllSchedu ? schedulItem.Data_1 : schedulItem.Data_1_Diy)" :key="index"
                @click="toClinic(item, index, schedulItem)">
                <view>{{ item.RegDateDiy }}</view>
                <view style="margin-top: 12upx;">{{ item.WeekName }} {{ item.TimeSliceStr }}</view>
                <image v-if="item.IsHalt == 7" class="time_item_img" :src="iconUrl.full2"></image>
                <image v-if="item.IsHalt == 2" class="time_item_img" :src="iconUrl.stop"></image>
                <image v-if="item.IsHalt == 7 && item.WaitLeaveCount > 0" class="time_item_img" :src="iconUrl.yyghWait"></image>
              </view>
              <view class="time_item colorCustom" @click="showAll(doctorIndex, schedulIndex)" v-if="schedulItem.Data_1.length > 6">
                {{ schedulItem.showAllSchedu ? '收起' : '全部排班' }}
              </view>
            </view>
          </view>
          <view class="other_dept_box" v-if="!doctorItem.ShowDeptSwitch">
            <view class="displayFlexRow border_top displayFlexBetween">
              <text>本院所有科室排班</text>
              <switch color="var(--dominantColor)" class="public_switch" @change="queryScheduleList($event, doctorIndex, doctorItem)" />
            </view>
          </view>
          <view class="other_dept_box displayFlexRow border_top" v-if="doctorItem.Scheduling.length == 1 && doctorItem.ShowDeptSwitch">
            <text class="non_schedul">暂无其他科室排班</text>
          </view>
        </view>
      </view>
      <view v-else class="noData">
        <noData :value="noDataTip"></noData>
      </view>
    </view>
    <doctorInfoComp :doctorInfoIsShow="doctorInfoIsShow" :doctorInfo="doctorInfo"></doctorInfoComp>
  </view>

  <!-- AI数智客服入口-->
  <aiCustomerEntry :currentUser="currentUser"></aiCustomerEntry>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { common, pagesPatientFn } from '@/utils';
import icon from '@/utils/icon';
import { REQUEST_CONFIG } from '@/config';
import { 
  queryClinicScheduleDate, 
  queryClinicDoctorSchedule, 
  queryClinicBaseDoctor, 
  queryScheduleList as queryScheduleListApi
} from '@/pagesPatient/service/yygh';

import noData from '@/pages/st1/components/noData/noData.vue';
import doctorInfoComp from '@/pagesPatient/st1/components/doctorInfo/doctorInfo.vue';
import aiCustomerEntry from '@/pages/st1/components/pagesAICustomerService/st1/components/aiCustomerEntry/aiCustomerEntry.vue';

// Define components locally if needed, but imported components are automatically available in <script setup>
// We rename doctorInfo import to avoid conflict with doctorInfo ref
const doctorInfo = ref({});

const iconUrl = ref(icon);
const dialogIsShow = ref(false);
const showNoData = ref(false);
const timeList = ref<any[]>([]);
const timeActive = ref<string | number>('');
const doctorList = ref<any[]>([]);
const noDataTip = ref('暂无排班数据');
const showCon = ref(false);
const titleInfoList = ref([]);
const titleSelect = ref<any>({});
const titleClickVal = ref<any>({}); // Renamed from titleClick to avoid conflict with method
const reducibleOnly = ref(false);
const doctorInfoIsShow = ref(false);
const pageConfig = ref<any>({});
const serviceId = ref('');
const queryBean = ref<any>({});
const currentUser = ref({}); // Added for aiCustomerEntry

const app = getApp();

onLoad((options: any) => {
  if (options.DistrictId) {
    app.globalData.districtId = options.DistrictId;
  }
  
  // 当前页面配置信息
  let config = common.deepCopy(app.globalData.config?.pageConfiguration?.yyghDoctorList_config || {});
  let qBean = options.queryBean ? JSON.parse(options.queryBean) : app.globalData.queryBean ? app.globalData.queryBean : {};
  console.log(qBean, 'queryBean');
  
  if (options.deptName) qBean.DeptName = options.deptName;
  if (options.deptCode) qBean.DeptCode = options.deptCode;
  
  queryBean.value = qBean;
  serviceId.value = options.serviceId || '';
  pageConfig.value = config;
  timeActive.value = (config.hasAllSchedules && options.serviceId != '009') ? '' : 0;
  
  uni.setNavigationBarTitle({
    title: queryBean.value.DeptName || '排班',
  });
  
  main();
});

const main = async () => {
  let tList: any[] = [];
  
  // 获取排班日期列表 
  let queryData = {
    HosId: app.globalData.districtId || app.globalData.hosId,
    DeptCode: queryBean.value.DeptCode
  };
  
  let timeListResp = await queryClinicScheduleDate(queryData);
  if (timeListResp && Array.isArray(timeListResp)) {
    timeListResp.map((item: any) => {
      if (item.RegDate == common.newDay()) item.WeekName = '今天';
    });
    tList = !common.isEmpty(timeListResp) ? timeListResp : tList;
  }
  
  // 获取排班医生列表  
  await setterDoctorList(tList);
  
  timeList.value = tList;
  showCon.value = true;
};

// 医生筛选点击
const titleClick = (item: any) => {
  titleClickVal.value = common.isEmpty(item) ? "" : item;
};

// 医生详情点击
const doctorInfoClick = async (item: any) => {
  let queryData = {
    HosId: app.globalData.districtId || app.globalData.hosId,
    DeptCode: item.DeptCode || '',
    DoctorCode: item.DoctorCode || '',
    DoctorName: ''
  };
  
  let resp = await queryClinicBaseDoctor(queryData);
  if (!common.isEmpty(resp)) {
    doctorInfoIsShow.value = true;
    doctorInfo.value = resp[0];
  }
};

// 点击医生职称重置 确定按钮
const titleBtnClick = async (type: string) => {
  if (type == 'reset') {
    titleClickVal.value = {};
  } else {
    titleSelect.value = titleClickVal.value;
    await setterDoctorList();
    dialogShowChange();
  }
};

// 点击查看全部排班
const showAll = (doctorIndex: number, schedulIndex: number) => {
  const list = [...doctorList.value];
  list[doctorIndex].Scheduling[schedulIndex].showAllSchedu = !list[doctorIndex].Scheduling[schedulIndex].showAllSchedu;
  doctorList.value = list;
};

// 是否仅显示可约医生
const switchChange = async (e: any) => {
  reducibleOnly.value = e.detail.value;
  await setterDoctorList();
};

// 点击排班时间
const timeClick = async (e: any, item?: any, index?: number) => {
  // item and index are passed directly in Vue template
  // If called without item (click "All"), item is undefined
  
  if (!common.isEmpty(item)) {
    timeActive.value = index!;
  } else {
    timeActive.value = "";
  }
  await setterDoctorList();
};

// 医生dialog显隐
const dialogShowChange = () => {
  dialogIsShow.value = !dialogIsShow.value;
  titleClickVal.value = titleSelect.value;
};

const doNothing = () => {};

// 处理医生列表返回值 
const setterDoctorList = async (tList?: any[]) => {
  let list = tList || timeList.value;
  let time = typeof timeActive.value == 'number' ? list[timeActive.value].RegDate : "";
  
  let queryData = {
    HosId: app.globalData.districtId || app.globalData.hosId,
    ServiceId: serviceId.value,
    DeptCode: queryBean.value.DeptCode,
    DoctorCode: "",
    WorkDateStart: time || "",
    WorkDateEnd: time || "",
    TitleCode: titleSelect.value.DoctorTitleCode || "",
    OrderByDoc: '1',
    WaitRule: '1'
  };
  
  let resp = await queryClinicDoctorSchedule(queryData);
  let isReducibleOnly = reducibleOnly.value;
  
  if (!common.isEmpty(resp)) {
    for (let i of resp) {
      if (i.Data_1 && !common.isEmpty(i.Data_1)) {
        i.Data_1.map((item: any) => {
          item.RegDateDiy = item.RegDate.substring(5);
          item.WeekName = item.RegDate == common.newDay() ? '今天' : item.WeekName;
        });
      }
      
      /**如果医生头像没有域名 添加域名 */
      if (i.PhotoUrl && i.PhotoUrl.indexOf('http') == '-1') {
        i.PhotoUrl = REQUEST_CONFIG.BASE_URL + i.PhotoUrl;
      }
      if (i.PhotoUrl) {
          i.PhotoUrl = i.PhotoUrl.replace(/\\/g, '/');
      }
      
      if (i.Data_1 && i.Data_1.length > 6) {
        i.Data_1_Diy = i.Data_1.slice(0, 5);
        i.showAllSchedu = false;
      } else {
        i.Data_1_Diy = i.Data_1;
        i.showAllSchedu = true;
      }
    }
  }
  
  if (isReducibleOnly && !common.isEmpty(resp)) {
    resp = resp.filter((item: any) => item.Data_1.filter((cell: any) => cell.IsHalt != '7' && cell.IsHalt != '2').length > 0);
  }
  
  if (resp) {
    resp.map((item: any) => {
      let obj = [{
        Check: true,
        DeptName: item.DeptName,
        DeptCode: item.DeptCode,
        DoctorName: item.DoctorName,
        DoctorCode: item.DoctorCode,
        Data_1: item.Data_1,
        Data_1_Diy: item.Data_1_Diy,
        showAllSchedu: item.showAllSchedu,
      }];
      item.Scheduling = obj;
    });
  }
  
  doctorList.value = resp || [];
  showNoData.value = common.isEmpty(resp) ? true : false;
};

// 点击医生具体排班时间
const toClinic = (item: any, index: number, schedulItem: any) => {
  // 判断（约满且无候补）或者停诊
  if ((item.IsHalt == 7 && item.WaitLeaveCount <= 0) || item.IsHalt == '2') {
    return;
  }
  
  // Construct event object to mimic typical event structure if needed by pagesPatientFn, 
  // but handleRouter usually takes dataset from event.
  // Here we pass data manually or construct a mock event.
  // pagesPatientFn.handleRouter(e, 'yyghClinicMsg', this.data.serviceId, index)
  
  // Since pagesPatientFn.handleRouter expects an event object with currentTarget.dataset
  // We should reconstruct what it expects.
  // The original call was: pagesPatientFn.handleRouter(e, 'yyghClinicMsg',this.data.serviceId, index)
  // e.currentTarget.dataset.dataitem was 'item'
  
  const mockEvent = {
    currentTarget: {
      dataset: {
        dataitem: item,
        index: index
      }
    }
  };
  
  pagesPatientFn.handleRouter(mockEvent, 'yyghClinicMsg', serviceId.value, index);
};

// 查询其它科室排班
const queryScheduleList = async (e: any, doctorIndex: number, doctorItem: any) => {
  // Switch change event
  // Note: switch binding in Vue passes value differently than bindchange in WXML
  // In Vue @change, value is boolean (e.detail.value)
  
  // If we want to use the same logic, we just need to proceed.
  
  let list = common.deepCopy(doctorList.value, []);
  let time = typeof timeActive.value == 'number' ? timeList.value[timeActive.value].RegDate : "";
  
  let queryData = {
    workDateEnd: time || "",
    workDateStart: time || "",
    doctorCode: doctorItem.DoctorCode,
    deptCode: doctorItem.DeptCode,
    hosId: app.globalData.districtId || app.globalData.hosId,
    WaitRule: '1'
  };
  
  let res = await queryScheduleListApi(queryData);
  
  if (common.isNotEmpty(res)) {
    let scheduleList: any[] = [];
    res.map((item: any) => {
      // 转换返回数据 小写转大写
      item.hisQueryClinicSchedules = common.changeObj(item.hisQueryClinicSchedules);
      item.hisQueryBaseDoctor = common.changeObj(item.hisQueryBaseDoctor);
      
      if (item.hisQueryClinicSchedules && item.hisQueryClinicSchedules.length > 0) {
        // 判断是否多数据处理 星期 时间 上下午
        item.hisQueryClinicSchedules.map((ele: any) => {
          ele.WeekName = ele.RegDate == common.newDay() ? '今天' : common.weekDay(ele.RegDate, 1);
          ele.RegDateDiy = ele.RegDate.substring(5);
          ele.TimeSliceStr = ele.TimeSlice == 1 ? '上午' : ele.TimeSlice == 2 ? '下午' : '全天';
        });
        
        // 判断如果超出6个隐藏
        if (item.hisQueryClinicSchedules.length > 6) {
          item.Data_1_Diy = item.hisQueryClinicSchedules.slice(0, 5);
          item.showAllSchedu = false;
        } else {
          item.Data_1_Diy = item.hisQueryClinicSchedules;
          item.showAllSchedu = true;
        }
        
        scheduleList.push({
          Check: item.hisQueryBaseDoctor.DeptCode == doctorItem.DeptCode ? true : false,
          DeptName: item.hisQueryBaseDoctor.DeptName,
          DeptCode: item.hisQueryBaseDoctor.DeptCode,
          DoctorName: doctorItem.DoctorName,
          DoctorCode: doctorItem.DoctorCode,
          Data_1: item.hisQueryClinicSchedules,
          Data_1_Diy: item.Data_1_Diy,
          showAllSchedu: item.showAllSchedu,
        });
      }
    });
    
    // 给当前查询的医生新加列表
    list[doctorIndex].Scheduling = scheduleList;
  }
  
  // 查询过的医生 不展示switch
  list[doctorIndex].ShowDeptSwitch = true;
  doctorList.value = list;
};

// 折叠列表
const foldList = (doctorIndex: number, schedulIndex: number) => {
  let list = [...doctorList.value];
  list[doctorIndex].Scheduling[schedulIndex].Check = !list[doctorIndex].Scheduling[schedulIndex].Check;
  doctorList.value = list;
};

</script>

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