<template>
  <view class="container">
    <u-sticky offsetTop="0rpx" customNavHeight="0rpx">
      <view class="search-view">
        <view class="search-input-wrapper" @click="handlePerson">
          <u--input 
            v-model="queryParams.personName" 
            border="surround"
            readonly
            placeholder="请选择人员" 
            placeholderStyle="color: #909399"
            color="#333333"
            customStyle="background: rgba(102, 126, 234, 0.08); border: 2rpx solid rgba(102, 126, 234, 0.3); border-radius: 24rpx; height: 66rpx"
            class="search-input">
          </u--input>
          <uni-icons 
            type="search" 
            size="18" 
            color="#667eea" 
            class="search-icon">
          </uni-icons>
        </view>
        <view class="filter-btn" @click="filterPanel = !filterPanel">
          <uni-icons type="list" size="18" color="#667eea"></uni-icons>
          <text>筛选</text>
        </view>
        <view class="add-btn" @click="handleAdd()">
          <uni-icons type="plusempty" size="18" color="#667eea"></uni-icons>
          <text>新增</text>
        </view>

        <u-transition :show="filterPanel" mode="fade">
          <view class="filter-panel" :style="{ height: `${windowHeight - 42}px` }">
            <view class="filter-panel-content">
              <view class="filter-title">档案类型</view>
              <view class="state-list">
                <view v-for="item in typeList" :key="item.id" class="state-item"
                  :class="item.selected ? 'active' : ''" @click="selectType(item)">{{ item.dictLabel }}</view>
              </view>
              <view class="filter-title">发生日期</view>
              <view class="date-inputs">
                <u-input
                  :disabled="true"
                  :disabledColor="'#fff'"
                  class="dateInput"
                  @click="openOrCloseDate(true)"
                  border="surround"
                  v-model="queryParams.startTime"
                  placeholder="请选择开始时间"
                >
                  <template v-slot:suffix>
                    <u-icon name="calendar" @click.stop="openOrCloseDate(true)"></u-icon>
                  </template>
                </u-input>
                <u-input
                  :disabled="true"
                  :disabledColor="'#fff'"
                  class="dateInput"
                  @click="openOrCloseDate(false)"
                  border="surround"
                  v-model="queryParams.endTime"
                  placeholder="请选择结束时间"
                >
                  <template v-slot:suffix>
                    <u-icon name="calendar" @click.stop="openOrCloseDate(false)"></u-icon>
                  </template>
                </u-input>
              </view>
            </view>
            <view class="btn-box">
              <view class="btn-reset" @click="resetQuery()">
                <uni-icons type="reload" size="16" color="#909399"></uni-icons>
                <text>重置</text>
              </view>
              <view class="btn-confirm" @click="searchSubmit()">
                <uni-icons type="checkmarkempty" size="16" color="#ffffff"></uni-icons>
                <text>确定</text>
              </view>
            </view>
            <u-datetime-picker
              :closeOnClickOverlay="true"
              :show="timeShow"
              v-model="time"
              mode="date"
              :minDate="-2209017600000"
              @close="openOrCloseDate"
              @cancel="openOrCloseDate"
              @confirm="confirm"
            ></u-datetime-picker>
          </view>
        </u-transition>
      </view>
    </u-sticky>


    <u-list @scrolltolower="loadmore" :spaceHeight="116" lowerThreshold="100">
      <u-list-item v-for="(item, index) in listData" :key="index">
        <view class="list-item" @click="enterDetails(item)">
          <view class="item-header">
            <view class="card-name-section">
              <view class="card-icon">
                <uni-icons type="folder-add-filled" size="20" color="#ffffff"></uni-icons>
              </view>
              <view class="card-info">
                <text class="card-name">{{ item.name }}</text>
                <text class="card-code">{{ dictStr(item.type, typeList) }} · {{ dictStr(item.state, stateList) }}</text>
              </view>
            </view>
          </view>
          
          <view class="card-body">
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">人员名称</text>
                <text class="info-value">{{ item.personName || '--' }}</text>
              </view>
              <view class="info-item" v-if="item.occurTime">
                <text class="info-label">发生时间</text>
                <text class="info-value">{{ item.occurTime }}</text>
              </view>
              <view class="info-item" v-if="item.rehabilitationTime">
                <text class="info-label">康复时间</text>
                <text class="info-value">{{ item.rehabilitationTime }}</text>
              </view>
              <view class="info-item" v-if="item.duration">
                <text class="info-label">康复周期</text>
                <text class="info-value">{{ item.duration }}</text>
              </view>
              <view class="info-item info-item-full" v-if="item.etiology">
                <text class="info-label">发生原因</text>
                <text class="info-value">{{ dictStr(item.etiology, etiologyList) }}</text>
              </view>
              <view class="info-item info-item-full" v-if="item.initialSymptoms">
                <text class="info-label">初期症状</text>
                <text class="info-value">{{ item.initialSymptoms }}</text>
              </view>
              <view class="info-item info-item-full" v-if="item.mediumTermSymptoms">
                <text class="info-label">中期症状</text>
                <text class="info-value">{{ item.mediumTermSymptoms }}</text>
              </view>
              <view class="info-item info-item-full" v-if="item.laterStageSymptoms">
                <text class="info-label">后期症状</text>
                <text class="info-value">{{ item.laterStageSymptoms }}</text>
              </view>
              <view class="info-item info-item-full" v-if="item.remark">
                <text class="info-label">备注</text>
                <text class="info-value">{{ item.remark }}</text>
              </view>
            </view>
          </view>
          
          <view class="operate" @click.stop>
            <view class="btn-detail" @click="handleFullExport(item)">
              <uni-icons type="download" size="16" color="#13c2c2"></uni-icons>
              <text>导出</text>
            </view>
            <view class="btn-edit" @click="handleEdit(item)">
              <uni-icons type="compose" size="16" color="#667eea"></uni-icons>
              <text>修改</text>
            </view>
            <view class="btn-delete" @click="handleDelete(item)">
              <uni-icons type="trash" size="16" color="#f5576c"></uni-icons>
              <text>删除</text>
            </view>
          </view>
        </view>
      </u-list-item>
      <view>
      </view>
      <u-loadmore :status="status" loadingIcon="semicircle" height="88" fontSize="32rpx" @loadmore="loadmore" />
    </u-list>
    <u-picker itemHeight="88" :show="settingPickShow" :columns="settingColumns" keyName="settingName"
      @confirm="settingConfirm" @cancel="settingCancel"></u-picker>
      <u-picker itemHeight="88" :show="showPerson" :columns="personList" keyName="name" @cancel="handlePersonCancel"
        @confirm="handlePersonConfirm"></u-picker>
  </view>
       <!--返回首页按钮 -->
       <suspend></suspend>
</template>

<script setup>
import { listHealthRecord, delHealthRecord } from '@/api/health/healthRecord'
import { exportRecordFull } from '@/api/health/statisticAnalysis'
import { listPerson } from '@/api/health/person'
import { getDicts } from '@/api/system/dict/data.js'
import { timeHandler } from '@/utils/common.ts'
import {onLoad,onShow} from "@dcloudio/uni-app";
import dayjs from 'dayjs'
    // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref,computed }from "vue";
const pageNum = ref(1)
const listData = ref([])
const isShow = ref(false)
const status = ref('loadmore')
const settingPickShow = ref(false)
const settingColumns = ref([])
const timeShow= ref(false)
const showPerson = ref(false)
const personList = ref([])
const typeList = ref([])
const etiologyList = ref([])
const stateList = ref([])

const  flag= ref(true)
const time =ref( Number(new Date()))
const data = reactive({
  filterPanel: false,
  queryPersonParams: {
    pageNum: 1,
    pageSize: 100
  },
  queryParams: {
    name: null,
    type: null,
    healthRecordId: null,
    dosingTime: null,
    dosage: null,
    personId: null,
    resource: null,
    place: null
   } 
})
const { filterPanel, queryPersonParams, queryParams} = toRefs(data)
const windowHeight = computed(() => {
			uni.getSystemInfoSync().windowHeight - 50
		})	
onLoad(() => {
    getList()
  });

 onShow(() => {
    if (isShow.value) {
      listData.value=[]
      getList()
      isShow.value = false
    }
  });

  function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }

  function selectType(item) {
      queryParams.value.type = item.dictValue
      typeList.value.map(ele => {
        if (ele.dictValue == item.dictValue) {
          ele.selected = true
          Reflect.set(ele, 'selected', true)
        } else {
          Reflect.set(ele, 'selected', false)
        }
      })
    }

  function  openOrCloseDate(data) {
    if (typeof data === 'boolean') {
      flag.value = data
      timeShow.value = true
    } else {
      timeShow.value = false
    }
  }
function loadmore() {
      pageNum.value += 1
      if (status.value == 'loadmore') {
        getList()
      }
    }
function getList() {
  listPerson(queryPersonParams.value).then((response) => {
        personList.value = [response.rows]
      })
       // 类型
       getDicts('record_type').then(res => {
        typeList.value = res.data
      })
       // 用药地点
       getDicts('etiology').then(res => {
        etiologyList.value = res.data
      })
            // 单位
            getDicts('health_record_state').then(res => {
              stateList.value = res.data
      })

      status.value = 'loading'
      listHealthRecord({ pageSize: 10, pageNum: pageNum.value, ...queryParams.value }).then(res => {
        listData.value = listData.value.concat(res.rows)
        if (listData.value.length < res.total) {
          status.value = 'loadmore'
        } else {
          status.value = 'nomore'
        }
      }).catch(() => {
        status.value = 'nomore'
      })
    }
    function confirm(e) {
      const date = timeHandler(new Date(e.value), '-', ':')
            let formatValue = 'YYYY-MM-DD'
            dayjs(date).format(formatValue)
      if (flag.value) {
        queryParams.value.startTime =  dayjs(date).format(formatValue)
      } else {
        queryParams.value.endTime =  dayjs(date).format(formatValue)
      }
      timeShow.value = false
    }
function settingConfirm(e) {
      queryParams.value.settingId = e.value[0].settingId
      queryParams.value.settingName = e.value[0].settingName
      settingPickShow.value = false
    }
function settingCancel() {
      settingPickShow.value = false
    }
    function searchSubmit() {
      if(queryParams.value.startTime!=''&&queryParams.value.startTime!=undefined&&queryParams.value.endTime!=''&&queryParams.value.endTime!=undefined){
        queryParams.value.time = queryParams.value.startTime+'-'+queryParams.value.endTime 
      } 
      pageNum.value = 1
      listData.value = []
      getList()
      filterPanel.value = false
    }
    function handlePerson() {
        console.log('personList.value:', personList.value)
        console.log('personList.value[0]:', personList.value[0])
        if (!personList.value[0] || personList.value[0].length === 0) {
          uni.showToast({
            title: '人员为空',
            icon: 'none'
          })
        } else {
          console.log('准备打开人员选择器')
          showPerson.value = true
        }
     }
  function   handlePersonConfirm(e) {
    queryParams.value.personName = e.value[0].name
    queryParams.value.personId= e.value[0].id
        showPerson.value = false
        pageNum.value = 1
      listData.value = []
      getList()
  }
 function handlePersonCancel() {
  queryParams.value.personName = ''
    queryParams.value.personId= null
        showPerson.value = false
        pageNum.value = 1
      listData.value = []
      getList()
  }
    function searchBlur() {
      pageNum.value = 1
      listData.value = []
      getList()
    }
    function resetQuery() {
          queryParams.value.personName = ''
       queryParams.value.type = ''
        queryParams.value.startTime = ''
         queryParams.value.time = ''
        
        queryParams.value.endTime = ''
        queryParams.value.personId = ''
        
    }
    function enterDetails(item) {
      uni.navigateTo({ url: `/pages/health/healthRecord/details?id=${item.id}` })
    }
    function handleEdit(item) {
      uni.navigateTo({ url: `/pages/health/healthRecord/addEdit?id=${item.id}` })
      isShow.value = true
    }
    function handleAdd() {
      uni.navigateTo({ url: `/pages/health/healthRecord/addEdit` })
      isShow.value = true
    }
    function handleDelete(item) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条记录吗？',
        confirmText: '删除',
        cancelText: '取消',
        confirmColor: '#f5576c',
        cancelColor: '#909399',
        success: function (res) {
          if (res.confirm) {
            delHealthRecord(item.id).then(() => {
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              pageNum.value = 1
              listData.value = []
              getList()
            })
          }
        }
      });
    }
    function handleFullExport(item) {
      uni.showLoading({ title: '正在导出' })
      exportRecordFull(
        { recordId: item.id },
        `${item.name || '健康档案'}_完整信息_${Date.now()}.xlsx`
      ).then(() => {
        uni.showToast({ title: '导出成功', icon: 'success' })
      }).finally(() => {
        uni.hideLoading()
      })
    }
	
</script>

<style lang="scss" scoped>
@import '@/styles/health-common.scss';

// 筛选面板位置补充（单行模式）
.search-view .filter-panel {
  top: 96rpx;
}

// 筛选面板额外输入框
.filter-panel-content {
  .state-list {
    margin-bottom: 24rpx;

    .state-item {
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

      &:active {
        transform: scale(0.95);
      }
    }

    .active {
      box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
    }
  }

  .date-inputs {
    display: flex;
    flex-direction: column;
    gap: 16rpx;

    .dateInput {
      border-radius: 12rpx;
      border: 2rpx solid #e8edf3;
    }
  }
}
</style>
