<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="160rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
          <u-form-item label="治疗类型" prop="marTypeName"  @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="medicineName" required @click="handleMedical">
            <view class="input-with-arrow">
              <u--input v-model="form.medicineName" readonly disabledColor="#ffffff" placeholder="请选择药品名称"
                inputAlign="left" :customStyle="getInputStyle('medicineName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="入库编号" prop="code" required >
              <u--input v-model="form.code"  placeholder="请填写入库编号"
                inputAlign="left" :customStyle="getInputStyle('code')"></u--input>
            </u-form-item>
            <u-form-item label="入库数量" prop="quantity" required >
              <u--input v-model="form.quantity"   @change="handleQuantityChange" placeholder="请填写入库数量"
                inputAlign="left" :customStyle="getInputStyle('quantity')"></u--input>
            </u-form-item>
            <u-form-item label="规格总数" prop="totalCount" required >
              <u--input v-model="form.totalCount"  readonly placeholder="请填写规格总数"
                inputAlign="left" :customStyle="getInputStyle('totalCount')"></u--input>
            </u-form-item>
            <u-form-item label="使用状态" prop="stateName" required  @click="handleState">
              <view class="input-with-arrow">
                <u--input v-model="form.stateName" readonly disabledColor="#ffffff" placeholder="请选择使用状态"
                  inputAlign="left" :customStyle="getInputStyle('stateName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="购买时间" prop="purchaseDate"  @click="selectDate()">
            <view class="input-with-arrow">
              <u--input v-model="form.purchaseDate" readonly disabledColor="#ffffff" placeholder="请选择购买时间" inputAlign="left" :customStyle="getInputStyle('purchaseDate')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
   
            <u-form-item label="生产日期" prop="productionDate"  @click="selectProductionDate()">
            <view class="input-with-arrow">
              <u--input v-model="form.productionDate" readonly disabledColor="#ffffff" placeholder="请选择生产日期" inputAlign="left" :customStyle="getInputStyle('productionDate')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="过期日期" prop="expiringDate"   @click="selectExpiringDate()">
            <view class="input-with-arrow">
              <u--input v-model="form.expiringDate" readonly disabledColor="#ffffff" placeholder="请选择过期日期" inputAlign="left" :customStyle="getInputStyle('expiringDate')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
            <u-form-item label="包装单位" prop="packageUnitName"  @click="handlePackageUnit">
              <view class="input-with-arrow">
                <u--input v-model="form.packageUnitName" readonly disabledColor="#ffffff" placeholder="请选择包装单位"
                  inputAlign="left" :customStyle="getInputStyle('packageUnitName')"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
  
            <u-form-item label="规格单位" prop="unitName"  @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="usedCount"  >
              <u--input v-model="form.usedCount"  placeholder="请填写已使用数量"
                inputAlign="left" :customStyle="getInputStyle('usedCount')"></u--input>
            </u-form-item>
            <u-form-item label="剩余数量" prop="leftCount"  >
              <u--input v-model="form.leftCount"  placeholder="请填写剩余数量"
                inputAlign="left" :customStyle="getInputStyle('leftCount')"></u--input>
            </u-form-item>
            <u-form-item label="年龄体重" prop="ageWeight"  >
              <u--input v-model="form.ageWeight"  placeholder="请填写年龄体重"
                inputAlign="left" :customStyle="getInputStyle('ageWeight')"></u--input>
            </u-form-item>
            <u-form-item label="药品单价" prop="purchasePrice"  >
              <u--input v-model="form.purchasePrice" type="digit" placeholder="请填写药品单价"
                inputAlign="left" :customStyle="getInputStyle('purchasePrice')"></u--input>
            </u-form-item>
            <u-form-item label="药品总价" prop="totalPrice"  >
              <u--input v-model="form.totalPrice" type="digit" placeholder="请填写药品总价"
                inputAlign="left" :customStyle="getInputStyle('totalPrice')"></u--input>
            </u-form-item>
            <u-form-item label="购买地址" prop="purchaseAddress"  labelPosition="top">
              <u--input v-model="form.purchaseAddress"  placeholder="请填写购买地址"
              inputAlign="left" :customStyle="getInputStyle('purchaseAddress')"></u--input>
          </u-form-item>
            <u-form-item label="医嘱" prop="usage"  labelPosition="top">
            <u--textarea v-model="form.usage" placeholder="请填写医嘱" inputAlign="left" style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </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="showState" :columns="stateList" keyName="dictLabel" @cancel="handleStateCancel"
        @confirm="handleStateConfirm"></u-picker>

        <u-picker itemHeight="88" :show="showMarType" :columns="marTypeList" keyName="dictLabel" @cancel="handleMarTypeCancel"
        @confirm="handleMarTypeConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showMedical" :columns="medicalList" keyName="shortNameBrandPackaging" @cancel="handleMedicalCancel"
      @confirm="handleMedicalConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showPackageUnit" :columns="packageUnitList" keyName="dictLabel" @cancel="handlePackageUnitCancel"
      @confirm="handlePackageUnitConfirm"></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="purchaseDateRef" 
			@cancel="datePickShow=false"
			@confirm="datePickConfirm"
			itemHeight="88"
		></u-datetime-picker>
    <u-datetime-picker
			:show="productionDateShow"
			mode="date"
      :minDate="-2209017600000"
      ref="productionDateRef" 
			@cancel="productionDateShow=false"
			@confirm="productionDateConfirm"
			itemHeight="88"
		></u-datetime-picker>

    <u-datetime-picker
			:show="expiringDateShow"
			mode="date"
      :minDate="-2209017600000"
      ref="expiringDateRef" 
			@cancel="expiringDateShow=false"
			@confirm="expiringDateConfirm"
			itemHeight="88"
		></u-datetime-picker>
  </view>
</template>

<script setup>
import {  getMedicineStockIn, addMedicineStockIn, updateMedicineStockIn } from '@/api/health/medicineStockIn'
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";
  // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
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 flag = ref('add')
const title = ref("药品入库清单")

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

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

const stateList = ref([])
const showState = ref(false)

const packageUnitList = ref([])
const showPackageUnit = ref(false)

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

const data = reactive({
form: {
  id: null,
    medicineId: null,
    quantity: 1,
    productionDate: null,
    expiringDate: null,
    purchaseDate: null,
    purchasePrice: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    code: null,
    state: '0',
    stateName: '未使用',
    leftCount: null,
    usedCount: null,
    purchaseAddress: null,
    totalPrice: null,
    usage: null,
    ageWeight: null,
    totalCount: null,
    unit: null,
    packageUnit: null
},
queryPersonParams: {
  pageNum: 1,
  status: '1',
  pageSize: 1000
},
queryHealthRecordParams: {
  pageNum: 1,
  personId:null,
  pageSize: 1000
},
queryMedicineParams: {
    pageNum: 1,
    treatmentType: null,
    pageSize: 1000
  },
rules: {
  medicineName: [{ required: true, message: '药品名称不能为空', trigger: ['change', 'blur'] }],
  quantity: [{type: 'number',  required: true, message: '数量不能为空', trigger: ['change', 'blur'] }],
  // productionDate: [{ required: true, message: '生产日期不能为空', trigger: ['change', 'blur'] }],
  // expiringDate: [{ required: true, message: '过期日期不能为空', trigger: ['change', 'blur'] }],
  totalCount: [{ type: 'number', required: true, message: '规格总数不能为空', trigger: ['change', 'blur'] }],
  
  code: [{ type: 'number', required: true, message: '入库编号不能为空', trigger: ['change', 'blur'] }],

  stateName: [{ required: true, message: '使用状态不能为空', trigger: ['change', 'blur'] }]
}
})
const { form,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.purchaseDate = 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
 }

 const handleQuantityChange = (val) => {
  if(form.value.medicineId!=null){
  getMedicineBasic(form.value.medicineId).then((response) => {
    form.value.totalCount = response.data.specifications * val
  })
}
}

 function  selectProductionDate() {
      productionDateShow.value = true
      proxy.$refs['productionDateRef'].innerValue = new Date().getTime()
  }
function productionDateConfirm(e) {
      form.value.productionDate = dayjs(e.value).format("YYYY-MM-DD")
      productionDateShow.value = false
  }

  function  selectExpiringDate() {
    expiringDateShow.value = true
      proxy.$refs['expiringDateRef'].innerValue = new Date().getTime()
  }
function expiringDateConfirm(e) {
      form.value.expiringDate = dayjs(e.value).format("YYYY-MM-DD")
      expiringDateShow.value = false
  }
function  getData() {
  listMedicineBasic(queryMedicineParams.value).then((response) => {
    medicalList.value = [response.rows] 
  })
     // 类型
     getDicts('used_state').then(res => {
        stateList.value =[res.data] 
      })

           // 类型
     getDicts('mar_type').then(res => {
        marTypeList.value =[res.data] 
      })
           // 类型
     getDicts('medical_unit').then(res => {
        unitList.value =[res.data] 
      })
         // 类型
     getDicts('package_unit').then(res => {
      packageUnitList.value =[res.data] 
      })

    if(form.value.id!=null){
      getMedicineStockIn(form.value.id).then(res => {
        form.value = res.data   
     
         getDicts('package_unit').then(result => {
          form.value.packageUnitName=dictStr(form.value.packageUnit, result.data)
         })
                  // 药品来源
        getDicts('medical_unit').then(result => {
          form.value.unitName=dictStr(form.value.unit, result.data)
         })
                    // 药品来源
        getDicts('used_state').then(result => {
          form.value.stateName=dictStr(form.value.state, result.data)
         })
                // 用药类型
           getDicts('mar_type').then(result => {
          form.value.marTypeName=dictStr(form.value.type, result.data)
         })
      })
    }else {

      const date = new Date()
  const year = date.getFullYear() // 年份
  let month = date.getMonth() + 1 // 月份，返回值为0-11，所以需要加1
  let day = date.getDate() // 日期
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  // 对月份和日期进行补零
  month = month < 10 ? '0' + month : month.toString()
  day = day < 10 ? '0' + day : day.toString()
  hour = hour < 10 ? '0' + hour : hour.toString()
  minute = minute < 10 ? '0' + minute : minute.toString()
  second = second < 10 ? '0' + second : second.toString()
  const currentDate = year + month + day + hour + minute + second
  form.value.code = currentDate
    }
}

function handlePackageUnit() {
        if (packageUnitList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '药品来源为空  ', type: 'warning'
          })
        } else {
          showPackageUnit.value = true
        }
     }
  function   handlePackageUnitConfirm(e) {
        form.value.packageUnitName = e.value[0].dictLabel
        form.value.packageUnit = e.value[0].dictValue
        showPackageUnit.value = false
  }
 function handlePackageUnitCancel() {
  showPackageUnit.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.medicineName = 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.packageUnit = response.data.packageUnit
         form.value.totalCount = response.data.specifications
         if (form.value.quantity != null) {
             form.value.totalCount = response.data.specifications * form.value.quantity
        }
       // 药品来源
         getDicts('package_unit').then(result => {
          form.value.packageUnitName=dictStr( response.data.packageUnit, result.data)
         })


  })
      showMedical.value = false
      
}
function handleMedicalCancel() {
     showMedical.value = false
  }


function handleState() {
        if (stateList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '使用状态为空  ', type: 'warning'
          })
        } else {
          showState.value = true
        }
     }
  function   handleStateConfirm(e) {
        form.value.stateName = e.value[0].dictLabel
        form.value.state = e.value[0].dictValue
        showState.value = false
  }
 function handleStateCancel() {
      showState.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 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.medicineName = ""
     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['purchaseDateRef'].innerValue = new Date().getTime()
  }
function datePickConfirm(e) {
      form.value.purchaseDate = 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){
          updateMedicineStockIn(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/health/medicineStockIn/list` })
            }
          })
        })
          }else {
            form.value.id == null
            addMedicineStockIn(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/medicineStockIn/list` })
            }
          })
        })
          }
        }else {
          addMedicineStockIn(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/health/medicineStockIn/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>
