<template>
  <view class="container">
    <u-sticky offsetTop="0rpx" customNavHeight="0rpx">
      <view class="search-view">
        <u--input 
          v-model="queryParams.keys" 
          border="surround"
          @click="searchBlur"
          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" 
          suffixIcon="search" 
          suffixIconStyle="color: #667eea">
        </u--input>
        <view class="filter-btn" @click="filterPanel = !filterPanel">
          <uni-icons type="list" size="18" color="#667eea"></uni-icons>
          <text>筛选</text>
        </view>
        <view class="add-btn" v-show="auth.hasPermi('health:medicineBasic:add')" @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="selcet-content" style="padding: 0 24rpx">
                <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="locked" size="20" color="#ffffff"></uni-icons>
              </view>
              <view class="card-info">
                <text class="card-name">{{ item.shortName }}-{{ item.brand }}({{ item.packaging }})</text>
              </view>
            </view>
          </view>
          
          <view class="card-body">
            <view class="info-row">
              <view class="info-item" v-if="item.name || true">
                <text class="info-label">药品全称</text>
                <text class="info-value">{{ item.name || '--' }}</text>
              </view>
              <view class="info-item" v-if="dictStr(item.treatmentType, typeList) || true">
                <text class="info-label">治疗类型</text>
                <text class="info-value">{{ dictStr(item.treatmentType, typeList) || '--' }}</text>
              </view>
              <view class="info-item" v-if="item.code || true">
                <text class="info-label">药品编码</text>
                <text class="info-value">{{ item.code || '--' }}</text>
              </view>
              <view class="info-item" v-if="dictStr(item.classification, classificationList) || true">
                <text class="info-label">药品分类</text>
                <text class="info-value">{{ dictStr(item.classification, classificationList) || '--' }}</text>
              </view>
              <view class="info-item" v-if="dictStr(item.category, categoryList) || true">
                <text class="info-label">类别</text>
                <text class="info-value">{{ dictStr(item.category, categoryList) || '--' }}</text>
              </view>
              <view class="info-item" v-if="dictStr(item.dosageForm, dosageFormList) || true">
                <text class="info-label">药品剂型</text>
                <text class="info-value">{{ dictStr(item.dosageForm, dosageFormList) || '--' }}</text>
              </view>
              <view class="info-item info-item-full" v-if="item.manufacturers || true">
                <text class="info-label">生产厂家</text>
                <text class="info-value">{{ item.manufacturers || '--' }}</text>
              </view>
              <view class="info-item info-item-full" v-if="item.createTime || true">
                <text class="info-label">录入时间</text>
                <text class="info-value">{{ item.createTime || '--' }}</text>
              </view>
              <view class="info-item info-item-full" v-if="parseAttachment(item.attachment).length">
                <text class="info-label">附件</text>
                <view class="attachment-list">
                  <image
                    v-for="(img, imgIdx) in parseAttachment(item.attachment)"
                    :key="imgIdx"
                    :src="img"
                    class="attachment-thumb"
                    mode="aspectFill"
                    @click.stop="previewAttachment(parseAttachment(item.attachment), imgIdx)"
                  ></image>
                </view>
              </view>
            </view>
          </view>
          
          <view class="operate" @click.stop>
            <view class="btn-edit" v-show="auth.hasPermi('health:medicineBasic:edit')" @click="handleEdit(item)">
              <uni-icons type="compose" size="16" color="#667eea"></uni-icons>
              <text>修改</text>
            </view>
            <view class="btn-copy" v-show="auth.hasPermi('health:medicineBasic:edit')" @click="handleCopy(item)">
              <uni-icons type="copy" size="16" color="#fa8c16"></uni-icons>
              <text>复制</text>
            </view>
            <view class="btn-delete" v-show="auth.hasPermi('health:medicineBasic:remove')" @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>
  </view>
        <!--返回首页按钮 -->
        <suspend></suspend> 
</template>

<script setup>
import { listMedicineBasic, delMedicineBasic } from '@/api/health/medicineBasic'
import { getDicts } from '@/api/system/dict/data.js'
import { timeHandler } from '@/utils/common.ts'
import {onLoad,onShow} from "@dcloudio/uni-app";
import auth from "@/plugins/auth"; // 建议使用auth进行鉴权操作
import config from '@/config'
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 typeList = ref([])
const classificationList = ref([])
const categoryList = ref([])
const dosageFormList = ref([])

const  flag= ref(true)
const time =ref( Number(new Date()))
const data = reactive({
  filterPanel: false,
  queryParams: {
    name: null,
    classification: null,
    keys: null,
    brand: null,
    packaging: null,
    manufacturers: null,
    treatmentType: null,
    isImport: null,
    ingredients: null,
    usage: null,
    dosageForm: null,
    code: null,
    shortName: null
   } 
})
const { filterPanel, queryParams} = toRefs(data)
const windowHeight = computed(() => {
      return 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.treatmentType = 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() {
       // 治疗类型
       getDicts('mar_type').then(res => {
        typeList.value = res.data
      })
       // 用药地点
       getDicts('medicine_classification').then(res => {
        classificationList.value = res.data
      })
            // 单位
            getDicts('medicine_category').then(res => {
              categoryList.value = res.data
      })

       // 药品类型
       getDicts('dosage_form').then(res => {
        dosageFormList.value = res.data
      })
      status.value = 'loading'
      listMedicineBasic({ 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() {
      // 只有开始和结束时间都设置时才拼接 time 字段，否则清空避免上一次筛选残留
      if (queryParams.value.startTime && queryParams.value.endTime) {
        queryParams.value.time = queryParams.value.startTime + '-' + queryParams.value.endTime
      } else {
        queryParams.value.time = ''
      }
      pageNum.value = 1
      listData.value = []
      getList()
      filterPanel.value = false
    }
    function searchBlur() {
      pageNum.value = 1
      listData.value = []
      getList()
    }
    function resetQuery() {
      queryParams.value.treatmentType = ''
      queryParams.value.keys = ''
      queryParams.value.startTime = ''
      queryParams.value.time = ''
      queryParams.value.endTime = ''
      // 同步重置选中状态
      typeList.value.forEach(ele => {
        Reflect.set(ele, 'selected', false)
      })
    }
    function enterDetails(item) {
      uni.navigateTo({ url: `/pages/health/medicineBasic/details?id=${item.id}` })
    }
    function handleEdit(item) {
      uni.navigateTo({ url: `/pages/health/medicineBasic/addEdit?id=${item.id}` })
      isShow.value = true
    }
    function handleCopy(item) {
      uni.navigateTo({ url: `/pages/health/medicineBasic/addEdit?flag=copy&id=${item.id}` })
      isShow.value = true
    }
    function handleAdd() {
      uni.navigateTo({ url: `/pages/health/medicineBasic/addEdit` })
      isShow.value = true
    }
    function handleDelete(item) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条记录吗？',
        confirmText: '删除',
        cancelText: '取消',
        confirmColor: '#f5576c',
        cancelColor: '#909399',
        success: function (res) {
          if (res.confirm) {
            delMedicineBasic(item.id).then(() => {
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              pageNum.value = 1
              listData.value = []
              getList()
            })
          }
        }
      });
    }

// 解析附件字段为URL数组
function parseAttachment(attachment) {
  if (!attachment) return []
  // 附件是后端静态资源直链，需要用域名拼接，不能带网关前缀 prod-api
  const origin = config.baseUrl.replace(/^(https?:\/\/[^/]+).*$/, '$1')
  return attachment.split(',').filter(url => url).map(url => {
    if (url.startsWith('http')) return url
    return origin + url
  })
}

// 预览附件图片
function previewAttachment(urls, index) {
  uni.previewImage({
    urls: urls,
    current: urls[index]
  })
}
</script>

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

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

// 附件图片展示区
.attachment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-top: 4rpx;
  width: 100%;

  .attachment-thumb {
    width: 120rpx;
    height: 120rpx;
    border-radius: 8rpx;
    background: #f5f7fa;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.08);
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.95);
    }
  }
}
</style>