<template>
  <view class="p_mask screen_dialog_mask" :class="{ fixed: !pMask }" v-if="screenDialogShow" @click="showScreenMask">
    <view class="screen_inner p_flexCenterCol" @click.stop="doNothing">
      <view class="screen_box p_format p_scroll">
        <!-- 时间 -->
        <view class="screen_item" v-if="showDatePicker">
          <view class="item_tit p_flexBetween">
            <view class="item_tit_val">咨询时间</view>
          </view>
          <view class="item_time_box p_flexBetween">
            <picker mode="date"
              :value="queryDataCopy.ConsultStartDate || queryDataCopy.BeginDate || queryDataCopy.StartTime"
              :start="start"
              :end="queryDataCopy.ConsultEndDate || queryDataCopy.EndDate || queryDataCopy.EndTime"
              @change="dateChange"
              :data-key="queryDataCopy.ConsultStartDate ? 'queryDataCopy.ConsultStartDate' : queryDataCopy.BeginDate ? 'queryDataCopy.BeginDate' : 'queryDataCopy.StartTime'">
              <view class="time_con p_flexCenter">
                {{ queryDataCopy.ConsultStartDate || queryDataCopy.BeginDate || queryDataCopy.StartTime }}
              </view>
            </picker>
            <view class="time_tip">至</view>
            <picker mode="date" :value="queryDataCopy.ConsultEndDate || queryDataCopy.EndDate || queryDataCopy.EndTime"
              :start="queryDataCopy.ConsultStartDate || queryDataCopy.BeginDate || queryDataCopy.StartTime"
              @change="dateChange"
              :data-key="queryDataCopy.ConsultEndDate ? 'queryDataCopy.ConsultEndDate' : queryDataCopy.EndDate ? 'queryDataCopy.EndDate' : 'queryDataCopy.EndTime'">
              <view class="time_con p_flexCenter">
                {{ queryDataCopy.ConsultEndDate || queryDataCopy.EndDate || queryDataCopy.EndTime }}
              </view>
            </picker>
          </view>
        </view>
        <!-- 单选多选 -->
        <view class="screen_item" v-for="(itemParent, indexParent) in screenListCopy" :key="indexParent">
          <view class="item_tit p_flexBetween">
            <view class="item_tit_val">{{ itemParent.title }}<text class="item_tit_subval p_color_9">（{{ itemParent.type === '0' ? '单选' : itemParent.type === '1' ? '多选' : '' }}）</text></view>
          </view>
          <view class="item_list">
            <view
              class="item_val p_flexCenter"
              :class="{ 'p_color p_border item_val_ac': isHas(index, itemParent.selectedInd) }"
              v-for="(item, index) in itemParent.list" :key="index" @click="itemClick"
              :data-index-parent="indexParent"
              :data-index="index" :data-item="item">{{ item.name }}</view>
          </view>
        </view>
        <!-- 医生职称 -->
        <view class="screen_item" v-if="showDoctorTitle">
          <view class="item_tit p_flexBetween">
            <view class="item_tit_val">医生职称</view>
          </view>
          <view class="item_list">
            <view
              class="item_val p_flexCenter"
              :class="{ 'p_color p_border item_val_ac': isHas(item.DoctorTitleCode, titleSelectedList) }"
              v-for="(item, index) in titleList" :key="index" @click="titleListClick" :data-item="item">{{ item.DoctorTitle }}
            </view>
          </view>
        </view>
        <!-- 就诊人 -->
        <view class="screen_item" v-if="showMember && memberList.length > 0">
          <view class="item_tit p_flexBetween">
            <view class="item_tit_val">选择就诊人</view>
          </view>
          <view class="item_list">
            <view
              class="item_val p_flexCenter"
              :class="{ 'p_color p_border item_val_ac': item.memberId == (queryDataCopy.memberId || queryDataCopy.MemberId) }"
              v-for="(item, index) in memberList" :key="index" @click="memberClick" :data-item="item">{{ item.memberName }}</view>
          </view>
        </view>

      </view>
      <!-- 按钮 -->
      <view class="btn_list p_flexCenter">
        <view class="btn_item btn_item_reset p_border p_color p_flexCenter" @click="btnClick" data-type="reset">重置</view>
        <view class="btn_item btn_item_confirm p_bgcolor p_flexCenter" @click="btnClick" data-type="confirm">确定</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, getCurrentInstance, defineExpose } from 'vue';
import { common } from '@/uni-app-base/utils';
import icon from '@/utils/icon';
import { deepCopy, copy as netHosCopy } from '/pagesNetHos/st1/static/js/netHosCommon';
import { isHas } from '/pagesNetHos/st1/static/js/common';
import { queryTitleInfoNew, queryBaseMemberList_V3 } from '/pagesNetHos/st1/service/doctor/index';

const { proxy } = getCurrentInstance() as any;
const app = getApp();

const props = withDefaults(defineProps<{
  // 遮罩层定位方式
  pMask?: boolean;
  // 是否展示筛选组件
  screenDialogShow?: boolean;
  // 是否展示就诊人
  showMember?: boolean;
  // 是否展示全部就诊人按钮
  showAllMember?: boolean;
  // 是否展示医生筛选
  showDoctorTitle?: boolean;
  // 筛选值
  screenList?: any[];
  // 入参
  queryData?: any;
  // 是否展示日期
  showDatePicker?: boolean;
  // 开始日期
  start?: string;
}>(), {
  pMask: true,
  screenDialogShow: false,
  showMember: false,
  showAllMember: true,
  showDoctorTitle: false,
  screenList: () => [],
  queryData: () => ({}),
  showDatePicker: false,
  start: ''
});

const emit = defineEmits(['screenConfirmClk', 'showScreenMask']);

// 当前选中的list
const selectedList = ref<any[]>([]);
// list副本
const screenListCopy = ref<any[]>([]);
// 入参副本
const queryDataCopy = reactive<any>({});
// 就诊人列表
const memberList = ref<any[]>([]);
// 当前选中的就诊人
const memberSelected = ref<any>({});
// 医生职称列表
const titleList = ref<any[]>([]);
// 当前选择医生职称
const titleSelectedList = ref<string[]>(['']);

// 监听 queryData 变化
watch(() => props.queryData, (val) => {
  console.log(val, "val");
  Object.assign(queryDataCopy, deepCopy(val));
}, { immediate: true, deep: true });

// 监听 screenList 变化
watch(() => props.screenList, (val) => {
  if (val && val.length > 0) {
    screenListCopy.value = deepCopy(val);
  }
}, { immediate: true, deep: true });

// 监听 screenDialogShow 变化，显示时调用 main
watch(() => props.screenDialogShow, (val) => {
  if (val) {
    main();
  }
});

onMounted(() => {
  if (props.screenDialogShow) {
    main();
  }
});

// 页面显示时调用
// 注意：UniApp 组件没有 pageLifetimes，需要在父组件中处理
const main = () => {
  screenListCopy.value = deepCopy(props.screenList);
  if (props.showMember) {
    getCardList();
  }
  if (props.showDoctorTitle) {
    getDoctorTitle();
  }
};

// 暴露方法供父组件调用
defineExpose({
  main
});

// 获取医生职称
const getDoctorTitle = async () => {
  let data = {
    HosId: (app.globalData as any).hosId,
    DeptCode: "",
    IsUsed: true
  };
  let titleListData: any[] = [];
  let { resp } = await queryTitleInfoNew(data);
  if (!common.isEmpty(resp)) {
    resp.unshift({
      DoctorTitle: '全部',
      DoctorTitleCode: ''
    });
    titleListData = resp;
  }
  titleList.value = titleListData;
};

// 点击状态选项  区分单选多选
const itemClick = (e: any) => {
  let indexParent = e.currentTarget?.dataset?.indexParent;
  let itemParent = screenListCopy.value[indexParent];
  let item = e.currentTarget?.dataset?.item;
  let index = e.currentTarget?.dataset?.index;
  
  if (itemParent.type === '0' || item.name.indexOf('全部') !== -1) {
    // 单选 或 点击了全部
    itemParent.selectedInd = [index];
  } else if (itemParent.type === '1') {
    // 多选
    if (itemParent.selectedInd.includes(index)) {
      // 多选时 不能取消最后一个选择
      if (itemParent.selectedInd.length === 1) {
        return;
      }
      let ind = itemParent.selectedInd.findIndex((ind: number) => ind === index);
      itemParent.selectedInd.splice(ind, 1);
    } else {
      itemParent.selectedInd.push(index);
    }
    // 过滤含有 全部 的字段
    let allIndex = itemParent.list.findIndex((item: any) => item.name.indexOf('全部') !== -1);
    itemParent.selectedInd = itemParent.selectedInd.filter((item: number) => item !== allIndex);
  }
};

// 就诊人点击
const memberClick = (e: any) => {
  let item = e.currentTarget?.dataset?.item;
  queryDataCopy.MemberId = item.memberId || item.MemberId || "";
  queryDataCopy.MemberIds = item.memberId || item.MemberId || "";
};

// 医生职称点击
const titleListClick = (e: any) => {
  let item = e.currentTarget?.dataset?.item;
  let titleSelected = [...titleSelectedList.value];
  
  if (item.DoctorTitle === '全部') {
    titleSelected = [''];
  } else {
    if (titleSelected.includes(item.DoctorTitleCode)) {
      // 多选时不能清空所有字段
      if (titleSelected.length === 1) {
        return;
      }
      titleSelected = titleSelected.filter((cell: string) => cell !== item.DoctorTitleCode);
    } else {
      titleSelected.push(item.DoctorTitleCode);
    }
    // 过滤全部选项
    titleSelected = titleSelected.filter((item: string) => item !== '');
  }
  console.log(titleSelected);
  queryDataCopy.DoctorTitleCode = titleSelected.join(',');
  titleSelectedList.value = titleSelected;
};

// 获取就诊人列表
const getCardList = async () => {
  let queryData = {
    HosId: (app.globalData as any).hosId,
    isEncrypt: true,
  };
  let { resp } = await queryBaseMemberList_V3(queryData);
  let list: any[] = [];
  if (!common.isEmpty(resp)) {
    if (props.showAllMember) {
      resp.unshift({
        memberName: '全部',
        memberId: '',
      });
    }
    list = resp;
  }
  memberList.value = list;
};

// 日期更改
const dateChange = (e: any) => {
  let key = e.currentTarget?.dataset?.key;
  if (key) {
    const keys = key.split('.');
    if (keys.length === 2) {
      (queryDataCopy as any)[keys[1]] = e.detail.value;
    } else {
      queryDataCopy[key] = e.detail.value;
    }
  }
};

// 按钮点击
const btnClick = (e: any) => {
  let type = e.currentTarget?.dataset?.type;
  
  if (type === 'confirm') {
    // 确定
    let data: any = {};
    let queryDataCopyNew = deepCopy(queryDataCopy);
    
    for (let item of screenListCopy.value) {
      for (let i of item.selectedInd) {
        data = copy(item.list[i].options, data);
      }
    }
    netHosCopy(data, queryDataCopyNew);
    
    // memberId 和 MemberIds 只传一个
    if (queryDataCopyNew.MemberIds == '') {
      let arr: string[] = [];
      memberList.value.map((item: any) => {
        arr.push(item.memberId);
      });
      queryDataCopyNew.MemberIds = arr.join(',');
    }
    emit('screenConfirmClk', queryDataCopyNew);
    showScreenMask();
  } else if (type === 'reset') {
    // 重置
    screenListCopy.value = deepCopy(props.screenList);
    Object.assign(queryDataCopy, deepCopy(props.queryData));
    queryDataCopy.DoctorTitleCode = '';
    queryDataCopy.MemberId = "";
    queryDataCopy.MemberIds = "";
    titleSelectedList.value = [''];
  }
};

// 展示筛选弹窗
const showScreenMask = () => {
  emit('showScreenMask');
};

const doNothing = () => {
  // 阻止事件冒泡
};

// 如果对象key相同  将值push至复制对象中
const copy = (obj: any, c: any = {}) => {
  for (var i in obj) {
    if (Object.keys(c).includes(i)) {
      let arr = c[i].split(',');
      arr.push(obj[i]);
      c[i] = arr.join(',');
    } else {
      c[i] = obj[i];
    }
  }
  return c;
};
</script>

<style lang="scss" scoped>
@import "@/pagesNetHos/st1/static/css/common.scss";

.p_mask {
  height: 100vh;
  position: absolute;
}

.screen_inner {
  background-color: #fff;
  padding: 10upx 30upx 0;
  border-radius: 0px 0px 36upx 36upx;
  max-height: 800upx;
}

.screen_box {
  width: 100%;
}

.item_tit {
  margin: 30upx 0 10upx;
}

.item_tit_val {
  font-size: 32upx;
  font-weight: 500;
}

.item_tit_subval {
  font-size: 28upx;
}

.item_tit_img {
  width: 20upx;
  height: 20upx;
}

.item_list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.item_val {
  padding: 0 20upx;
  width: 216upx;
  height: 68upx;
  background: #F7F7F7;
  border-radius: 34upx;
  font-size: 26upx;
  margin: 20upx 20upx 0 0;
}

.item_val:nth-child(3n) {
  margin-right: 0;
}

.item_val_ac {
  background-color: #E7F7F3;
}

.item_val_ac::after,
.item_val_ac::before {
  border-color: #01BF8E;
  border-radius: 34px;
}

.time_con {
  width: 312upx;
  height: 68upx;
  background: #F7F7F7;
  border-radius: 8px;
  margin: 20upx 0;
  font-size: 26upx;
}

.time_tip {
  font-size: 26upx;
}

.btn_list {
  margin: 30upx 0;
}

.btn_item {
  width: 345upx;
  height: 92upx;
  background-color: #fff;
  border-radius: 46upx 0 0 46upx;
  font-size: 34upx;
}

.btn_item_reset::after,
.btn_item_reset::before {
  border-color: #01BF8E;
  border-radius: 46px 0 0 46px;
}

.btn_item_confirm {
  border-radius: 0px 46upx 46upx 0px;
}

.fixed {
  position: fixed;
}
</style>
