<template>
  <view class="consumableList">
    <view class="head" >
      <uni-search-bar v-model="dataInfo.keyWord" placeholder="请搜索耗材" bgColor="#F8F8F8" @input="search" cancelButton="none" focus :radius="18" />
    </view>
    <view class="body" v-if="dataInfo.list.length">
      <view class="body_item ellipsis" v-for="data in dataInfo.list" :key="data.id" @click="numberClick(data, 'addConsumable')">
        {{data.name}}
        <template v-if="data.model">({{data.model}})</template>
        <template v-if="data.unit">({{data.unit}})</template>
      </view>
    </view>
    <view class="zanwu" v-else>
      <text class="newicon newicon-zanwu"></text>
    </view>
    <view class="foot_common_btns">
      <button @click="goBack" type="default" class="primaryButton btn">返回</button>
    </view>
    <NumberModal v-if="dataInfo.isNumber" @cancelEmit="cancelNumber" @confirmEmit="conformNumber" :selectData="dataInfo.selectData" :selectType="dataInfo.selectType"></NumberModal>
  </view>
</template>

<script setup>
  import { debounce, uniqBy } from 'lodash-es'
  import { ref, reactive} from 'vue'
  import NumberModal from '@/components/NumberModal.vue';
  import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
  import { api_consumable, getFetchDataList, api_incidentDetail, api_addSummaryDoc, api_incidentCategoryConsumable } from "@/http/api.js"
  import { defaultColor } from '@/static/js/theme.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  import { useLoginUserStore } from '@/stores/loginUser'
  import { useGoBack } from '@/share/useGoBack.js'
  
  useSetTitle();
  const loginUserStore = useLoginUserStore();
  const { goBack }  = useGoBack();
  
  // 主题颜色
  const primaryColor = ref(defaultColor)
  
  // 数据
  const dataInfo = reactive({
    list: [],//工单列表
    idx: 0,//页码
    hasMore: true,//是否有更多数据
    incidentId: undefined,//事件ID
    summaryId: undefined,//汇总单ID
    incidentData: {},//事件对象
    keyWord: '',//搜索的关键词
    isNumber: false,//修改数量弹窗
    evtNumber: 1,//弹窗返回的数量
    selectData: {},//选择的对象
    selectType: {},//选择的对象类型
		itsmZeroStock:null, //是否支持零库存
		itsmParentConsumable:null //是否支持父级科室耗材
  })
  
  // 点击修改数量
  function numberClick(data, type){
    console.log(data)
    dataInfo.isNumber = true;
    dataInfo.selectData = {
      consumableBrandModel: data.brandModel,
      consumableUnit: data.unit,
      consumableEndPrice: data.endPrice,
      consumableId: data.id,
      consumableName: data.name,
    };
    dataInfo.selectType = type;
  }
  
  // 确认修改数量
  function conformNumber(evtNumber){
    dataInfo.evtNumber = evtNumber;
    dataInfo.isNumber = false;
    addSummaryDoc();
  }
  
  // 关闭修改数量
  function cancelNumber(){
    dataInfo.isNumber = false;
  }
  
  // 添加耗材
  function addSummaryDoc(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    let postData = {
      "consumableList": [
        {
          "consumablesId": dataInfo.selectData.consumableId,
          "consumablesNum": dataInfo.evtNumber
        }
      ],
      "summaryId": dataInfo.summaryId
    };
    api_addSummaryDoc(postData).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        uni.showToast({
        	icon: 'none',
          title: '添加耗材成功',
          mask: true,
        });
        setTimeout(() => {
          uni.navigateTo({
            url: `/pages/handler/handler?incidentId=${dataInfo.incidentId}`,
          })
        }, 1500)
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }
  
  // 获取事件详情
  function getIncidentDetail(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    api_incidentDetail(dataInfo.incidentId).then(res => {
      uni.hideLoading();
      if(res.status == 200){
        dataInfo.incidentData = res.data || {};
				getHosConfig()
      }else{
        uni.showToast({
          icon: 'none',
          title: res.msg || '请求数据失败！'
        });
      }
    })
  }
  
  // 搜索
  const search = debounce(getList.bind(null, 0), 500);
  
  // 是否没有故障耗材配置
  const isFlag = ref(false);
  
  // 获取故障耗材配置
  async function getIncidentCategoryConsumable(){
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    
    let postData = {
      idx: 0,
      sum: 20,
      incidentCategoryConsumable: {
        duty: dataInfo.incidentData.duty.id,
        category: dataInfo.incidentData.category,
      }
    }
    
    let res = await api_incidentCategoryConsumable(postData);
    uni.hideLoading();
    uni.stopPullDownRefresh();
    if(res.status == 200){
      let list = res.list || [];
      if(list.length){
        isFlag.value = false;
        let arr = list.map(v => v.consumableDTOS).flat();
        dataInfo.list = uniqBy(arr, 'id');
      }else{
        isFlag.value = true;
      }
    }else{
      isFlag.value = false;
      uni.showToast({
        icon: 'none',
        title: res.msg || '请求数据失败！'
      });
    }
  }
  
  // 获取列表信息
   function getList(idx){
    // 判断是否满足故障耗材配置
    // await getIncidentCategoryConsumable();
    // if(!isFlag.value){
    //   return;
    // }
    
    if(dataInfo.keyWord.trim() === ''){
      dataInfo.list = [];
      uni.stopPullDownRefresh();
      return;
    }
    
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    
    dataInfo.idx = idx === undefined ? dataInfo.idx : idx;
    if(dataInfo.idx === 0){
      dataInfo.list = [];
    }

    let postData = {
      idx: dataInfo.idx,
      sum: 20,
      consumable: {
        name: dataInfo.keyWord,
				upHosId:loginUserStore.loginUser.user.currentHospital.id,
        hosId: loginUserStore.loginUser.user.currentHospital.id
      }
    }
		if(dataInfo.itsmParentConsumable.value==1){
			delete postData.consumable.hosId
		}else{
			delete postData.consumable.upHosId
		}
		getFetchDataList("simple/data", "consumable", postData)
		  .then((res) => {
				uni.hideLoading();
				uni.stopPullDownRefresh();
				if(res.status == 200){
				  let list = res.list || [];
				  if(list.length){
				    dataInfo.hasMore = true;
						if(dataInfo.itsmZeroStock.value==0){
							let arr = dataInfo.idx === 0 ? list : dataInfo.list.concat(list)
							dataInfo.list = arr.filter(i=>i.stock!=0)
						}else{
							dataInfo.list = dataInfo.idx === 0 ? list : dataInfo.list.concat(list);
						}
					}else{
				    dataInfo.hasMore = false;
				  }
				}else{
				  uni.showToast({
				    icon: 'none',
				    title: res.msg || '请求数据失败！'
				  });
				}
		  });
  }
  
	// 获取院区配置是否支持零库存/是否支持父级科室耗材
	function getHosConfig(){
		let postData = {
		  idx: 0,
		  sum: 9999,
			hospitalConfig:{
				hosId: loginUserStore.loginUser.user.currentHospital.id,
				model: "itsm"
			}
		};
		getFetchDataList("simple/data", "hospitalConfig", postData)
		  .then((res) => {
				dataInfo.itsmZeroStock = res.list.find(i=>i.key=='itsmZeroStock')
				dataInfo.itsmParentConsumable = res.list.find(i=>i.key=='itsmParentConsumable')
				getList(0);
		  });
	}
	
  onLoad((option) => {
    dataInfo.incidentId = option.incidentId;
    dataInfo.summaryId = option.summaryId;
    getIncidentDetail();
  })
  
  onPullDownRefresh(() => {
    getList(0)
  })
  
  onReachBottom(() => {
    dataInfo.idx += 1;
    if (dataInfo.hasMore) {
      getList(); // 当触底时加载更多数据
    }
  })
</script>

<style lang="scss" scoped>
.consumableList{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .head{
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 24rpx;
    position: fixed;
    z-index: 99;
    width: 100%;
    box-sizing: border-box;
    background: linear-gradient( 90deg, #58CF66 0%, #DDE9FC 100%);
  }
  .body{
    margin-bottom: 140rpx;
    margin-top: 88rpx;
    font-size: 26rpx;
    .body_item{
      border-bottom: 1rpx solid #DEDEDE;
      padding: 24rpx;
    }
  }
  .zanwu{
    margin-bottom: 140rpx;
    margin-top: 88rpx;
    display: flex;
    justify-content: center;
    .newicon-zanwu{
      font-size: 256rpx;
      color: #D6D6D6;
      margin-top: 140rpx;
    }
  }
  .foot_common_btns{
    position: fixed;
    left: 0;
    bottom: 0;
    background-color: #fff;
  }
}
</style>
