<template>
  <view class="container" style="paddingBottom:1rpx;">
    <view class="section">
      <view class="section-title">{{ title}}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="140rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
          <u-form-item label="人员姓名" prop="personName" required @click="handlePerson">
            <view class="input-with-arrow">
              <u--input v-model="form.personName" readonly disabledColor="#ffffff" placeholder="请选择人员"
                inputAlign="left" :customStyle="getInputStyle('personName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="健康档案" prop="healthRecordName" required @click="handHealthRecord">
            <view class="input-with-arrow">
              <u--input v-model="form.healthRecordName" readonly disabledColor="#ffffff" placeholder="请选择健康档案"
                inputAlign="left" :customStyle="getInputStyle('healthRecordName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="用药类型" prop="marTypeName" required @click="handleMarType">
            <view class="input-with-arrow">
              <u--input v-model="form.marTypeName" readonly disabledColor="#ffffff" placeholder="请选择用药类型"
                inputAlign="left" :customStyle="getInputStyle('marTypeName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="药品名称" prop="medicalName" required @click="handleMedical">
            <view class="input-with-arrow">
              <u--input v-model="form.medicalName" readonly disabledColor="#ffffff" placeholder="请选择药品名称"
                inputAlign="left" :customStyle="getInputStyle('medicalName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="药品来源" prop="resourceName" required @click="handleResource">
            <view class="input-with-arrow">
              <u--input v-model="form.resourceName" readonly disabledColor="#ffffff" placeholder="请选择药品来源"
                inputAlign="left" :customStyle="getInputStyle('resourceName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="用药地点" prop="placeName" required @click="handlePlace">
            <view class="input-with-arrow">
              <u--input v-model="form.placeName" readonly disabledColor="#ffffff" placeholder="请选择用药地点"
                inputAlign="left" :customStyle="getInputStyle('placeName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="用药时间" prop="dosingTime" required @click="selectDate()">
            <view class="input-with-arrow">
              <u--input v-model="form.dosingTime" readonly disabledColor="#ffffff" placeholder="请选择用药时间"
                inputAlign="left" :customStyle="getInputStyle('dosingTime')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="用药剂量" prop="dosage" required>
            <u--input v-model="form.dosage" placeholder="请填写用药剂量"  type="digit"
              inputAlign="left" :customStyle="getInputStyle('dosage')"></u--input>
          </u-form-item>
          <u-form-item label="用药单位" prop="unitName" required @click="handleUnit">
            <view class="input-with-arrow">
              <u--input v-model="form.unitName" readonly disabledColor="#ffffff" placeholder="请选择用药单位"
                inputAlign="left" :customStyle="getInputStyle('unitName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="备注" prop="remark" labelPosition="top">
            <u--textarea v-model="form.remark" placeholder="请填写备注" inputAlign="left"
              style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
        </u--form>
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <u-picker itemHeight="88" :show="showPerson" :columns="personList" keyName="name" @cancel="handlePersonCancel"
      @confirm="handlePersonConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showResource" :columns="resourceList" keyName="dictLabel" @cancel="handleResourceCancel"
      @confirm="handleResourceConfirm"></u-picker>

    <u-picker itemHeight="88" :show="showPlace" :columns="placeList" keyName="dictLabel" @cancel="handlePlaceCancel"
      @confirm="handlePlaceConfirm"></u-picker>

    <u-picker itemHeight="88" :show="showMarType" :columns="marTypeList" keyName="dictLabel" @cancel="handleMarTypeCancel"
      @confirm="handleMarTypeConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showHealthRecord" :columns="healthRecordList" keyName="name" @cancel="handHealthRecordCancel"
      @confirm="handHealthRecordConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showMedical" :columns="medicalList" keyName="shortNameBrandPackaging" @cancel="handleMedicalCancel"
      @confirm="handleMedicalConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showUnit" :columns="unitList" keyName="dictLabel" @cancel="handleUnitCancel"
      @confirm="handleUnitConfirm"></u-picker>
    <u-datetime-picker
      :show="datePickShow"
      mode="datetime"
      ref="dosingTimeRef"
      @cancel="datePickShow=false"
      @confirm="datePickConfirm"
      itemHeight="88"
    ></u-datetime-picker>
  </view>
</template>

<script setup>
import { getMarRecord, addMarRecord, updateMarRecord  } from '@/api/health/marRecord'
import { listPerson, getPerson } from '@/api/health/person'
import { listHealthRecord } from '@/api/health/healthRecord'
import { listMedicineBasic, getMedicineBasic } from '@/api/health/medicineBasic'
const { proxy } = getCurrentInstance()
import { getDicts } from '@/api/system/dict/data.js'
import dayjs from 'dayjs'
import {onLoad,onReady} from "@dcloudio/uni-app";
import {reactive ,toRefs,ref,computed ,getCurrentInstance }from "vue";

// 错误字段
const errorFields = ref([])

// 输入框基础样式
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 输入框错误样式
const inputErrorStyle = {
  background: '#fef0f0',
  border: '2rpx solid #f56c6c',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 根据字段名获取输入框样式
const getInputStyle = (field) => {
  return errorFields.value.includes(field) ? inputErrorStyle : inputBaseStyle
}

const datePickShow = ref(false)
const showPerson = ref(false)
const flag = ref('add')
const showHealthRecord = ref(false)
const title = ref("用药记录")
const healthRecordList = ref([])
const personList = ref([])

const medicalList = ref([])
const showMedical = ref(false)

const marTypeList = ref([])
const showMarType = ref(false)

const resourceList = ref([])
const showResource = ref(false)

const placeList = ref([])
const showPlace = ref(false)

const unitList = ref([])
const showUnit = ref(false)

const data = reactive({
form: {
  id: null,
    name: null,
    type: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    healthRecordId: null,
    dosingTime: null,
    dosage: null,
    personId: null,
    resource: '1',
    place: '1',
     resourceName: '医院开药',
    placeName: '家中'
},
queryPersonParams: {
  pageNum: 1,
  status: '1',
  pageSize: 1000
},
queryHealthRecordParams: {
  pageNum: 1,
  personId:null,
  pageSize: 1000
},
queryMedicineParams: {
    pageNum: 1,
    treatmentType: null,
    pageSize: 1000
  },
rules: {
  healthRecordName: [{ required: true, message: '健康档案不能为空', trigger:['change', 'blur'] }],
  personName: [{ required: true, message: '人员不能为空', trigger: ['change', 'blur'] }],
  medicalName: [{ required: true, message: '药品名称不能为空', trigger: ['change', 'blur'] }],
  marTypeName: [{ required: true, message: '用药类型不能为空', trigger: ['change', 'blur'] }],
  resource: [{ required: true, message: '药品来源不能为空', trigger: ['change', 'blur'] }],
  place: [{ required: true, message: '用药地点不能为空', trigger: ['change', 'blur'] }],
  dosage: [{ required: true, message: '用药剂量不能为空', trigger: ['change', 'blur'] }],
  unitName: [{required: true, message: '用药单位不能为空', trigger: ['change', 'blur'] }],
  dosingTime: [{ required: true, message: '用药时间不能为空', trigger: ['change', 'blur'] }]
}
})
const { form, queryPersonParams, queryHealthRecordParams,queryMedicineParams, rules} = toRefs(data)


onLoad((option) => {
     form.value.id = option.id
     flag.value = option.flag
     if(flag.value==null){
      if(form.value.id!=null){
      title.value="用药记录-修改"
     }else{
      title.value="用药记录-新增"
     }
     }else{
      title.value="用药记录-复制"
     }
     
    getData()
})
onReady(() => {
     form.value.dosingTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
})
function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
 }
function  getData() {
  listMedicineBasic(queryMedicineParams.value).then((response) => {
    medicalList.value = [response.rows] 
  })
      // 药品来源
    if(form.value.id!=null){
      getMarRecord(form.value.id).then(res => {
        listPerson(queryPersonParams.value).then((response) => {
     personList.value = [response.rows] 

      queryHealthRecordParams.value.personId=res.data.personId
      listHealthRecord(queryHealthRecordParams.value).then((response) => {  
        healthRecordList.value = [response.rows] 
      })
     })
        form.value = res.data   
        if(flag.value!=null){
        form.value.dosingTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
       }
        form.value.medicalName=form.value.name
        getDicts('mar_place').then(result => {
          placeList.value =[result.data] 
          form.value.placeName=dictStr(form.value.place, result.data)
         })
          // 药品来源
        getDicts('mar_resource').then(result => {
          resourceList.value =[result.data] 
          form.value.resourceName=dictStr(form.value.resource, result.data)
         })
                   // 药品来源
        getDicts('medical_unit').then(result => {
          unitList.value =[result.data] 
          form.value.unitName=dictStr(form.value.unit, result.data)
         })
                // 用药类型
           getDicts('mar_type').then(result => {
            marTypeList.value =[result.data] 
          form.value.marTypeName=dictStr(form.value.type, result.data)
         })
      })
    }else{
      listPerson(queryPersonParams.value).then((response) => {
     personList.value = [response.rows] 
     if(response.rows.length>0){
      form.value.personName= response.rows[0].name
      form.value.personId = response.rows[0].id
      queryHealthRecordParams.value.personId=response.rows[0].id
      listHealthRecord(queryHealthRecordParams.value).then((response) => {  
        healthRecordList.value = [response.rows] 
        if(response.rows.length>0){
      form.value.healthRecordName= response.rows[0].name
      form.value.healthRecordId = response.rows[0].id
    }
      })
     }
     })
     // 类型
     getDicts('mar_type').then(res => {
        marTypeList.value =[res.data] 
      })
           // 类型
     getDicts('medical_unit').then(res => {
        unitList.value =[res.data] 
      })
       // 类型
       getDicts('mar_resource').then(res => {
        resourceList.value =[res.data] 
      })
       // 子类型
       getDicts('mar_place').then(res => {
        placeList.value =[res.data] 
      })

    }
}

function handlePerson() {
      if (personList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '人员为空  ', type: 'warning'
        })
      } else {
        showPerson.value = true
      }
   }
function   handlePersonConfirm(e) {
     form.value.personName = e.value[0].name
      form.value.personId = e.value[0].id
      form.value.healthRecordName = ''
      form.value.healthRecordId = ''
      queryHealthRecordParams.value.personId=e.value[0].id
      listHealthRecord(queryHealthRecordParams.value).then((response) => {  
        healthRecordList.value = [response.rows] 
        if(response.rows.length>0){
      form.value.healthRecordName= response.rows[0].name
      form.value.healthRecordId = response.rows[0].id
    }
  showPerson.value = false
})
      
}
function handlePersonCancel() {
     showPerson.value = false
  }

  function handleMedical() {
      if (medicalList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '药品为空  ', type: 'warning'
        })
      } else {
        showMedical.value = true
      }
   }
function   handleMedicalConfirm(e) {
     form.value.medicalName = e.value[0].shortNameBrandPackaging
     form.value.name = e.value[0].shortNameBrandPackaging
      form.value.medicineId = e.value[0].id
      getMedicineBasic(e.value[0].id).then((response) => {
    form.value.unit = response.data.unit
       // 药品来源
         getDicts('medical_unit').then(result => {
          form.value.unitName=dictStr( response.data.unit, result.data)
         })
    form.value.contentUnit = response.data.contentUnit
  })
      showMedical.value = false
      
}
function handleMedicalCancel() {
     showMedical.value = false
  }
function handHealthRecord() {
      if (healthRecordList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '健康档案为空  ', type: 'warning'
        })
      } else {
        showHealthRecord.value = true
      }
   }
function   handHealthRecordConfirm(e) {
      form.value.healthRecordName = e.value[0].name
      form.value.healthRecordId = e.value[0].id
      showHealthRecord.value = false
}
function handHealthRecordCancel() {
     showHealthRecord.value = false
}

function handleResource() {
        if (resourceList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品来源为空  ', type: 'warning'
          })
        } else {
          showResource.value = true
        }
     }
  function   handleResourceConfirm(e) {
        form.value.resourceName = e.value[0].dictLabel
        form.value.resource = e.value[0].dictValue
        showResource.value = false
  }
 function handleResourceCancel() {
      showResource.value = false
      }

      function handleUnit() {
        if (unitList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '用药单位为空  ', type: 'warning'
          })
        } else {
          showUnit.value = true
        }
     }
  function   handleUnitConfirm(e) {
        form.value.unitName = e.value[0].dictLabel
        form.value.unit = e.value[0].dictValue
        showUnit.value = false
  }
 function handleUnitCancel() {
      showUnit.value = false
      }

      function handlePlace() {
        if (placeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '用药地点为空  ', type: 'warning'
          })
        } else {
          showPlace.value = true
        }
     }
  function   handlePlaceConfirm(e) {
        form.value.placeName = e.value[0].dictLabel
        form.value.place = e.value[0].dictValue
        showPlace.value = false
  }
 function handlePlaceCancel() {
  showPlace.value = false
      }

  function handleMarType() {
        if (marTypeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '用药类型为空  ', type: 'warning'
          })
        } else {
          showMarType.value = true
        }
     }
  function   handleMarTypeConfirm(e) {
        form.value.marTypeName = e.value[0].dictLabel
        form.value.type = e.value[0].dictValue

        queryMedicineParams.value.treatmentType = e.value[0].dictValue
        form.value.medicalName = ""
     form.value.name = ""
      form.value.medicineId = null
  listMedicineBasic(queryMedicineParams.value).then((response) => {
    medicalList.value = [response.rows] 
  })

        showMarType.value = false
  }
 function handleMarTypeCancel() {
       showMarType.value = false
      }

function  selectDate() {
      datePickShow.value = true
      proxy.$refs['dosingTimeRef'].innerValue = new Date().getTime()
  }
function datePickConfirm(e) {
      form.value.dosingTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
      datePickShow.value = false
  }
function submit() {
      // 清空错误字段
      errorFields.value = []
      
      proxy.$refs['uForm'].validate().then(() => {
        if (form.value.id != null) {
          if(flag.value==null){
            updateMarRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/health/marRecord/list` })
            }
          })
        })
          }else {
            form.value.id == null
            addMarRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/marRecord/list` })
            }
          })
        })
          }

        }else {
          addMarRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/marRecord/list` })
            }
          })
        })
        }
      }).catch(errors => {
        // 验证失败，记录错误字段
        if (errors && errors.length > 0) {
          errorFields.value = errors.map(err => err.field)
        }
        proxy.$modal.msgError('请填写完整信息')
      })
    }
</script>

<style lang="scss" scoped>
.section {
  margin: 24rpx;
  padding: 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .section-title {
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    line-height: 1.2;
    font-size: 28rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      width: 6rpx;
      height: 28rpx;
      background: #ffffff;
      border-radius: 3rpx;
      margin-right: 12rpx;
    }
  }

  .form-view {
    padding: 24rpx;

    .form-btn {
      padding-top: 16rpx;
    }

    // 带箭头的输入框容器
    .input-with-arrow {
      position: relative;
      width: 100%;

      .arrow-icon {
        position: absolute;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
        color: #c0c4cc;
        font-size: 20rpx;
        pointer-events: none;
        z-index: 10;
      }
    }
  }
}
</style>

<style lang="scss">
.form-btn .u-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  border-radius: 24rpx !important;
  height: 80rpx !important;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
}

.form-btn .u-button__text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
  letter-spacing: 2rpx !important;
}

/* 强制让错误状态的输入框边框变红 */
.u-form-item--error .u--input,
.u-form-item--error .u-input,
.u-form-item--error .u-input__content,
.u-form-item--error .u-input__content__field-wrapper {
  border: 2rpx solid #f56c6c !important;
  background: #fef0f0 !important;
}

.u-form-item--error .u--textarea,
.u-form-item--error .u-textarea {
  border: 2rpx solid #f56c6c !important;
  background: #fef0f0 !important;
}
</style>
