<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="typeName" required @click="handleType">
            <view class="input-with-arrow">
              <u--input v-model="form.typeName" readonly disabledColor="#ffffff" placeholder="请选择费用类型"
                inputAlign="left" :customStyle="getInputStyle('typeName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="产生时间" prop="costTime" required @click="selectCostTime">
            <view class="input-with-arrow">
              <u--input v-model="form.costTime" readonly disabledColor="#ffffff" placeholder="请选择产生时间"
                inputAlign="left" :customStyle="getInputStyle('costTime')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item v-if="showMedicine" label="治疗类型" prop="treatTypeName" @click="handleTreatType">
            <view class="input-with-arrow">
              <u--input v-model="form.treatTypeName" readonly disabledColor="#ffffff" placeholder="请选择治疗类型"
                inputAlign="left" :customStyle="getInputStyle('treatTypeName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item v-if="showMedicine" label="药品名称" prop="medicineName" @click="handleMedicine">
            <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 v-if="showCheckType" label="检查类型" prop="checkTypeName" @click="handleCheckType">
            <view class="input-with-arrow">
              <u--input v-model="form.checkTypeName" readonly disabledColor="#ffffff" placeholder="请选择检查类型"
                inputAlign="left" :customStyle="getInputStyle('checkTypeName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item v-if="showNursingType" label="护理治疗" prop="checkTypeName" @click="handleNursingType">
            <view class="input-with-arrow">
              <u--input v-model="form.checkTypeName" readonly disabledColor="#ffffff" placeholder="请选择护理治疗"
                inputAlign="left" :customStyle="getInputStyle('checkTypeName')"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="费用名称" prop="costName" required>
            <u--input v-model="form.costName" placeholder="请填写费用名称" inputAlign="left" :customStyle="getInputStyle('costName')"></u--input>
          </u-form-item>
          <u-form-item label="单价" prop="price" required>
            <u--input v-model="form.price" type="digit" placeholder="请填写单价" inputAlign="left"
              :customStyle="getInputStyle('price')" @change="handlePriceChange">
              <template #suffix>
                <up-text text="元"></up-text>
              </template>
            </u--input>
          </u-form-item>
          <u-form-item label="数量" prop="count" required>
            <u--input v-model="form.count" type="digit" placeholder="请填写数量" inputAlign="left"
              :customStyle="getInputStyle('count')" @change="handleCountChange"></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="totalCost" required>
            <u--input v-model="form.totalCost" type="digit" placeholder="请填写总价" inputAlign="left"
              :customStyle="getInputStyle('totalCost')">
              <template #suffix>
                <up-text text="元"></up-text>
              </template>
            </u--input>
          </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;" :customStyle="getTextareaStyle('remark')"></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="showTypePicker" :columns="costTypeColumns" keyName="dictLabel" @cancel="showTypePicker = false"
      @confirm="handleTypeConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showTreatTypePicker" :columns="treatTypeColumns" keyName="dictLabel" @cancel="showTreatTypePicker = false"
      @confirm="handleTreatTypeConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showMedicinePicker" :columns="medicineColumns" keyName="shortNameBrandPackaging" @cancel="showMedicinePicker = false"
      @confirm="handleMedicineConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showCheckTypePicker" :columns="checkTypeColumns" keyName="dictLabel" @cancel="showCheckTypePicker = false"
      @confirm="handleCheckTypeConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showNursingTypePicker" :columns="nursingTypeColumns" keyName="dictLabel" @cancel="showNursingTypePicker = false"
      @confirm="handleNursingTypeConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showUnitPicker" :columns="packageUnitColumns" keyName="dictLabel" @cancel="showUnitPicker = false"
      @confirm="handleUnitConfirm"></u-picker>
    <u-datetime-picker
      :show="datePickShow"
      mode="datetime"
      ref="costTimeRef"
      @cancel="datePickShow = false"
      @confirm="datePickConfirm"
      itemHeight="88"
    ></u-datetime-picker>
  </view>
</template>

<script setup>
import { addDoctorRecordCost, getDoctorRecordCost, updateDoctorRecordCost } from '@/api/health/doctorRecordCost'
import { getDoctorRecord } from '@/api/health/doctorRecord'
import { getMedicineBasic, listMedicineBasic } from '@/api/health/medicineBasic'
import { getDicts } from '@/api/system/dict/data.js'
import { onLoad, onReady } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
import { getCurrentInstance, reactive, ref, toRefs } from 'vue'

const { proxy } = getCurrentInstance()
const title = ref('费用明细')
const flag = ref('add')
const doctorRecord = ref({})
const datePickShow = ref(false)
const showTypePicker = ref(false)
const showTreatTypePicker = ref(false)
const showMedicinePicker = ref(false)
const showCheckTypePicker = ref(false)
const showNursingTypePicker = ref(false)
const showUnitPicker = ref(false)
const showMedicine = ref(false)
const showCheckType = ref(false)
const showNursingType = ref(false)
const costTypeList = ref([])
const packageUnitList = ref([])
const checkTypeList = ref([])
const nursingTypeList = ref([])
const treatTypeList = ref([])
const medicineList = ref([])
const costTypeColumns = ref([])
const packageUnitColumns = ref([])
const checkTypeColumns = ref([])
const nursingTypeColumns = ref([])
const treatTypeColumns = ref([])
const medicineColumns = ref([])
const errorFields = ref([])

const data = reactive({
  form: {
    id: null,
    doctorRecordId: null,
    type: null,
    costTime: null,
    costName: null,
    personId: null,
    healthRecordId: null,
    totalCost: null,
    price: null,
    count: null,
    unit: null,
    medicineId: null,
    checkType: null,
    remark: null
  },
  queryMedicineParams: {
    pageNum: 1,
    treatmentType: null,
    pageSize: 1000
  },
  rules: {
    typeName: [{ required: true, message: '费用类型不能为空', trigger: ['change', 'blur'] }],
    costTime: [{ required: true, message: '产生时间不能为空', trigger: ['change', 'blur'] }],
    costName: [{ required: true, message: '费用名称不能为空', trigger: ['change', 'blur'] }],
    price: [{ required: true, message: '单价不能为空', trigger: ['change', 'blur'] }],
    count: [{ required: true, message: '数量不能为空', trigger: ['change', 'blur'] }],
    unitName: [{ required: true, message: '单位不能为空', trigger: ['change', 'blur'] }],
    totalCost: [{ required: true, message: '总价不能为空', trigger: ['change', 'blur'] }]
  }
})

const { form, queryMedicineParams, rules } = toRefs(data)

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 textareaBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6'
}

const textareaErrorStyle = {
  background: '#fef0f0',
  border: '2rpx solid #f56c6c'
}

const getInputStyle = (field) => {
  return errorFields.value.includes(field) ? inputErrorStyle : inputBaseStyle
}

const getTextareaStyle = (field) => {
  return errorFields.value.includes(field) ? textareaErrorStyle : textareaBaseStyle
}

onLoad((option) => {
  form.value.id = option.id
  form.value.doctorRecordId = option.doctorRecordId
  flag.value = option.flag
  if (flag.value == null) {
    title.value = form.value.id != null ? '费用明细-修改' : '费用明细-新增'
  } else {
    title.value = '费用明细-复制'
  }
  getData()
})

onReady(() => {
  if (!form.value.costTime) {
    form.value.costTime = 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() {
  const dictTasks = [
    getDicts('cost_type').then(res => {
      costTypeList.value = res.data
      costTypeColumns.value = [res.data]
    }),
    getDicts('package_unit').then(res => {
      packageUnitList.value = res.data
      packageUnitColumns.value = [res.data]
    }),
    getDicts('check_type').then(res => {
      checkTypeList.value = res.data
      checkTypeColumns.value = [res.data]
    }),
    getDicts('nursing_type').then(res => {
      nursingTypeList.value = res.data
      nursingTypeColumns.value = [res.data]
    }),
    getDicts('mar_type').then(res => {
      treatTypeList.value = res.data
      treatTypeColumns.value = [res.data]
    })
  ]
  if (form.value.doctorRecordId) {
    getDoctorRecord(form.value.doctorRecordId).then(res => {
      doctorRecord.value = res.data
      form.value.personId = res.data.personId
      form.value.healthRecordId = res.data.healthRecordId
    })
  }
  if (form.value.id != null) {
    Promise.all(dictTasks).then(() => getDoctorRecordCost(form.value.id)).then(res => {
      form.value = res.data
      form.value.doctorRecordId = form.value.doctorRecordId || doctorRecord.value.id
      form.value.typeName = dictStr(form.value.type, costTypeList.value)
      form.value.unitName = dictStr(form.value.unit, packageUnitList.value)
      form.value.checkTypeName = dictStr(form.value.checkType, checkTypeList.value) || dictStr(form.value.checkType, nursingTypeList.value)
      // 后端返回的单价/数量/总价为数字类型，校验器按 string 校验会误判为空，这里统一转为字符串
      form.value.price = form.value.price != null ? String(form.value.price) : form.value.price
      form.value.count = form.value.count != null ? String(form.value.count) : form.value.count
      form.value.totalCost = form.value.totalCost != null ? String(form.value.totalCost) : form.value.totalCost
      applyTypeState(form.value.type)
      if (flag.value != null) {
        form.value.id = null
      }
    })
  }
}

function selectCostTime() {
  datePickShow.value = true
  proxy.$refs['costTimeRef'].innerValue = new Date().getTime()
}

function datePickConfirm(e) {
  form.value.costTime = dayjs(e.value).format('YYYY-MM-DD HH:mm:ss')
  datePickShow.value = false
}

function handleType() {
  showTypePicker.value = true
}

function handleTypeConfirm(e) {
  form.value.typeName = e.value[0].dictLabel
  form.value.type = e.value[0].dictValue
  showTypePicker.value = false
  applyTypeState(form.value.type)
}

function applyTypeState(type) {
  if (type === '1') {
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = false
    form.value.costName = form.value.costName || '挂号费'
    form.value.count = form.value.count || 1
    form.value.unit = form.value.unit || '6'
  } else if (type === '2') {
    showCheckType.value = true
    showNursingType.value = false
    showMedicine.value = false
    form.value.count = form.value.count || 1
    form.value.unit = form.value.unit || '5'
  } else if (type === '3') {
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = true
    form.value.count = form.value.count || 1
    getMedicineList()
  } else if (type === '4') {
    showCheckType.value = false
    showNursingType.value = true
    showMedicine.value = false
    form.value.unit = form.value.unit || '6'
    form.value.count = form.value.count || 1
  } else if (type === '5') {
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = false
    form.value.costName = form.value.costName || '交通费'
    form.value.unit = form.value.unit || '6'
    form.value.count = form.value.count || 1
  } else if (type === '6') {
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = false
    form.value.costName = form.value.costName || '餐饮'
    form.value.unit = form.value.unit || '6'
    form.value.count = form.value.count || 1
  } else {
    showCheckType.value = false
    showNursingType.value = false
    showMedicine.value = false
    form.value.costName = form.value.costName || '其他'
    form.value.count = form.value.count || 1
  }
  form.value.unitName = dictStr(form.value.unit, packageUnitList.value)
  calcTotalCost()
}

function handleTreatType() {
  showTreatTypePicker.value = true
}

function handleTreatTypeConfirm(e) {
  form.value.treatTypeName = e.value[0].dictLabel
  queryMedicineParams.value.treatmentType = e.value[0].dictValue
  showTreatTypePicker.value = false
  getMedicineList()
}

function getMedicineList() {
  listMedicineBasic(queryMedicineParams.value).then(res => {
    medicineList.value = res.rows
    medicineColumns.value = [res.rows]
  })
}

function handleMedicine() {
  if (medicineColumns.value.length === 0) {
    getMedicineList()
  }
  showMedicinePicker.value = true
}

function handleMedicineConfirm(e) {
  const medicine = e.value[0]
  form.value.medicineId = medicine.id
  form.value.medicineName = medicine.shortNameBrandPackaging
  form.value.costName = medicine.shortNameBrandPackaging
  showMedicinePicker.value = false
  getMedicineBasic(medicine.id).then(res => {
    form.value.unit = res.data.packageUnit
    form.value.unitName = dictStr(form.value.unit, packageUnitList.value)
  })
}

function handleCheckType() {
  showCheckTypePicker.value = true
}

function handleCheckTypeConfirm(e) {
  form.value.checkTypeName = e.value[0].dictLabel
  form.value.checkType = e.value[0].dictValue
  form.value.costName = e.value[0].dictLabel
  showCheckTypePicker.value = false
}

function handleNursingType() {
  showNursingTypePicker.value = true
}

function handleNursingTypeConfirm(e) {
  form.value.checkTypeName = e.value[0].dictLabel
  form.value.checkType = e.value[0].dictValue
  form.value.costName = e.value[0].dictLabel
  showNursingTypePicker.value = false
}

function handleUnit() {
  showUnitPicker.value = true
}

function handleUnitConfirm(e) {
  form.value.unitName = e.value[0].dictLabel
  form.value.unit = e.value[0].dictValue
  showUnitPicker.value = false
}

function handlePriceChange() {
  calcTotalCost()
}

function handleCountChange() {
  calcTotalCost()
}

function calcTotalCost() {
  if (form.value.price != null && form.value.count != null && form.value.price !== '' && form.value.count !== '') {
    form.value.totalCost = parseFloat(Number(form.value.price) * Number(form.value.count)).toFixed(2)
  }
}

function submit() {
  errorFields.value = []
  form.value.personId = form.value.personId || doctorRecord.value.personId
  form.value.healthRecordId = form.value.healthRecordId || doctorRecord.value.healthRecordId
  form.value.doctorRecordId = form.value.doctorRecordId || doctorRecord.value.id
  proxy.$refs['uForm'].validate().then(() => {
    if (form.value.id != null) {
      updateDoctorRecordCost(form.value).then(() => {
        proxy.$refs['uToast'].show({
          message: '修改成功',
          complete() {
            uni.navigateBack()
          }
        })
      })
    } else {
      addDoctorRecordCost(form.value).then(() => {
        proxy.$refs['uToast'].show({
          message: '新增成功',
          complete() {
            uni.navigateBack()
          }
        })
      })
    }
  }).catch(errors => {
    if (errors && errors.length > 0) {
      errorFields.value = errors.map(err => err.field)
    }
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
  })
}
</script>

<style lang="scss" scoped>
page {
  height: 100%;
  overflow: auto;
}

.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>
