<template>
  <el-form
    ref="formRef"
    :model="dataForm"
    label-width="110px"
    :rules="dataRule"
    class="bed-change-form"
    :toggleType="isDetail"
  >
    <div class="info-wrap" v-if="!isDetail">
      <el-row :gutter="20">
        <el-col :span="12" :xs="24">
          <el-form-item label="长者姓名" prop="elderlyId">
            <SelectElder v-model="dataForm.elderlyId" @elder="handleSelectElder" type="1" :tId="dataForm.tenantId"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="证件号码" prop="idCard">
            <TgInput v-model="dataForm.idCard" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="原床位" prop="originalName">
            <TgInput v-model="dataForm.originalName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="原床位类型" prop="overheadChargeId">
            <TgSelect
                v-model="dataForm.overheadChargeId"
                placeholder="请选择"
                disabled
                :list="bedList"
                dict-label="chargeName"
                dict-value="id"
              >
                <el-option v-for="t in bedList" :key="t.id" :label="t.chargeName" :value="t.id" />
              </TgSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24" :xs="24">
          <el-col :span="12" :xs="24">
            <el-form-item label="变更生效日期" prop="changeDate">
              <!-- :disabledDate="(arg) => disabledDate(arg)" -->
              <TgDatePicker v-model="dataForm.changeDate" type="date" placeholder="变更生效日期" />
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="新床位" prop="expectId">
            <SelectRoom v-model="dataForm.expectId"  @bed="bedChange"  :disabled="!dataForm.elderlyId" status="0" :tId="dataForm.tenantId"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="是否包房" prop="isPrivateRoom">
            <TgRadio
              v-model="dataForm.isPrivateRoom"
              :list="getDictOptions(DICT_TYPE.PRIVATE_ROOM)"
              inline
            >
              <el-radio
                v-for="(item, index) in getIntDictOptions(DICT_TYPE.PRIVATE_ROOM)"
                :label="item.label"
                :value="item.value"
                :key="index"
                >{{ item.label }}</el-radio
              >
            </TgRadio>
            <el-tooltip class="item" effect="dark" placement="top-start">
              <template #content
                >包房：当前床位所在的房间的其他床位将被锁定，无法再为其他人办理入住。包房金额以页面显示金额为准，本房间其他床位的金额不计算在内。<br />
                非包房：仅锁定当前床位，并不影响房间内的其他床位办理入住。</template
              >
              <Icon icon="ep:info-filled" />
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6" :xs="24">
          <el-form-item label="新床位类型" prop="expectOverheadChargeId">
            <TgSelect
              v-model="dataForm.expectOverheadChargeId"
              placeholder="请选择"
              clearable
              @change="handleChange"
              :list="bedList"
              dict-label="chargeName"
              dict-value="id"
            >
              <el-option v-for="t in bedList" :key="t.id" :label="t.chargeName" :value="t.id" />
            </TgSelect>
          </el-form-item>
        </el-col>
        <el-col :span="6" :xs="24">
          <el-form-item label="床位费原价" prop="amount">
            <span class="price">¥{{ formatNum(dataForm.amount) }}元/月</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="是否打折" prop="isDiscount">
            <TgSwitch v-model="dataForm.isDiscount" @change="handleSwitch"/>
          </el-form-item>
        </el-col>
        <template v-if="dataForm.isDiscount==1">
          <el-col :span="9" :xs="24">
            <el-form-item label="折扣金额(元)" prop="discountAmount">
              <TgInput v-model="discountAmount" append-text="¥" @blur="handleBlur(dataForm, 1)" />
            </el-form-item>
          </el-col>
          <el-col :span="9" :xs="24">
            <el-form-item label="折扣率" prop="discount">
              <TgInputNumber v-model="discount" @blur="handleBlur(dataForm, 2)" />
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="24">
          <el-form-item label="变更原因" prop="reason">
            <TgTextarea v-model="dataForm.reason" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="changeFiles" label="附件">
            <SelectUpload
              fun-name="附件"
              v-model="dataForm.changeFiles"
              :elder="{ elderId: dataForm.elderlyId, elderName: dataForm.elderName }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <div v-else>
      <div class="info-title">长者信息</div>
      <div class="info-wrap">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="长者姓名" prop="elderlyId">
              <SelectElder v-model="dataForm.elderlyId" type="1" :toggleType="isDetail"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="证件号码" prop="idCard">
              <TgInput v-model="dataForm.idCard" disabled :toggleType="isDetail"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="变更生效日期" prop="changeDate">
              <TgDatePicker v-model="dataForm.changeDate" type="date" placeholder="变更生效日期" :toggleType="isDetail"/>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="info-title">变更前</div>
      <div class="info-wrap">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="床位类型" prop="overheadChargeId">
              <TgSelect
                v-model="dataForm.overheadChargeId"
                placeholder="请选择"
                clearable
                @change="handleChange"
                :list="bedList"
                dict-label="chargeName"
                dict-value="id"
                :toggleType="isDetail"
              >
                <el-option v-for="t in bedList" :key="t.id" :label="t.chargeName" :value="t.id" />
              </TgSelect>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="床位号" prop="originalName">
              <TgInput v-model="dataForm.originalName" :toggleType="isDetail"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="床位价格" prop="originalAmount">
              <TgInput v-model="dataForm.originalAmount" :toggleType="isDetail"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="是否打折" prop="originalIsDiscount">
              <TgSwitch v-model="dataForm.originalIsDiscount" :toggleType="isDetail"/>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="info-title">变更后</div>
      <div class="info-wrap">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="床位类型" prop="expectOverheadChargeId">
              <TgSelect
                v-model="dataForm.expectOverheadChargeId"
                placeholder="请选择"
                clearable
                @change="handleChange"
                :list="bedList"
                dict-label="chargeName"
                dict-value="id"
                :toggleType="isDetail"
              >
                <el-option v-for="t in bedList" :key="t.id" :label="t.chargeName" :value="t.id" />
              </TgSelect>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="床位号" prop="expectId">
              <TgInput v-model="dataForm.bedName" :toggleType="isDetail"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="床位价格" prop="amount">
              {{ formatNum(dataForm.amount) }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item :label="(diffValueStr(dataForm)==0?'差额':diffValueStr(dataForm)>0?'需补缴':'需退款')" prop="actualAmount">
              <el-text style="font-weight: bold;color: red">{{ Math.abs(diffValueStr(dataForm)).toFixed(2) }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="是否包房" prop="isPrivateRoom">
              <TgRadio
                v-model="dataForm.isPrivateRoom"
                :list="getDictOptions(DICT_TYPE.PRIVATE_ROOM)"
                inline
                :toggleType="isDetail"
              >
                <el-radio
                  v-for="(item, index) in getIntDictOptions(DICT_TYPE.PRIVATE_ROOM)"
                  :label="item.label"
                  :value="item.value"
                  :key="index"
                  >{{ item.label }}</el-radio
                >
              </TgRadio>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="是否打折" prop="originalIsDiscount">
              <TgSwitch v-model="dataForm.originalIsDiscount" :toggleType="isDetail"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24" v-show="dataForm.isDiscount==1">
            <el-form-item label="折后价格" prop="actualAmount">
              <span class="price">{{ formatNum(dataForm.actualAmount) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="24">
          <el-form-item label="变更原因" prop="reason">
            <TgTextarea v-model="dataForm.reason" :toggleType="isDetail"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="changeFiles" label="附件">
            <SelectUpload
              v-model="dataForm.changeFiles"
              fun-name="附件"
              :elder="{ elderId: dataForm.elderlyId, elderName: dataForm.elderName }"
              :is-detail="isDetail"
            />
          </el-form-item>
        </el-col>
      </div>
    </div>
  </el-form>
</template>
<script setup lang="ts">
import { getOverheadListByType } from '@/api/elderly/fee/overheadCharge'
import { getChargeCategoryTree } from '@/api/elderly/fee/chargeCategory'
import { filteredTreeData, findTreeNode } from '@/utils/tree'
import { formatTime, getParentNodesById } from '@/utils'
import { getIntDictOptions, DICT_TYPE, getDictOptions, getDictLabel } from '@/utils/dict'
import { formatNum } from '@/utils/formatter'
import { getBusinessId } from '@/api/elderly/common'
import {getBedChangeRecordById, getBedChangeRecordElderlyById} from '@/api/elderly/elder/bed-change'
import { bedChangeFormType } from '../types'
import { getTenantId } from '@/utils/auth'
defineOptions({ name: 'BedChangeProcessForm' })

const formRef = ref() // 表单 Ref
const state = reactive<bedChangeFormType>({
  dataForm: {
    id: '',
    elderlyId: '',
    elderName: '',
    idCard: '',
    originalId: '', // 原床位id
    originalName: '', // 原床位名称
    changeDate: formatTime(Date.now(), 'yyyy-MM-dd'),
    expectId: '', // 现床位id
    expectName: '', // 床位类型名称
    isPrivateRoom: '',
    overheadChargeId: '', // 原床位类型id
    expectOverheadChargeId: '', // 现床位类型id
    amount: 0,
    discountAmount: '',
    discount: undefined,
    actualAmount: 0,
    isDiscount: '',
    categoryName: '',
    originalAmount: '',
    originalIsDiscount: '',
    changeFiles: [],
    reason: '',
    startTenantId: '',
    tenantId: undefined
  },
  dataRule: {
    elderlyId: [{ required: true, message: '长者不能为空', trigger: 'blur' }],
    changeDate: [{ required: true, message: '变更生效日期不能为空', trigger: 'blur' }],
    expectId: [{ required: true, message: '新床位不能为空', trigger: 'blur' }],
    expectOverheadChargeId: [{ required: true, message: '床位类型不能为空', trigger: 'blur' }],
    isPrivateRoom: [{ required: true, message: '是否包房不能为空', trigger: 'blur' }],
    discountAmount: [{ required: true, message: '折扣金额不能为空', trigger: 'blur' }],
    discount: [{ required: true, message: '折扣率不能为空', trigger: 'blur' }]
  }
})
const { dataForm, dataRule } = toRefs(state)
const resetFormField =  reactive({ ...dataForm.value })
const loading = ref(false)
const discount = ref()
const discountAmount = ref()
const processStatus = ref('')

const isDetail = ref(false)
/** 打开弹窗 */
const init = async (id, detail, status,elderly=undefined) => {
  dataForm.value.startTenantId = getTenantId()
  getTreeData()
  isDetail.value = detail
  if(elderly){
    //等新接口，查询后赋值
    const item = await getBedChangeRecordElderlyById(elderly.elderId)
    dataForm.value.elderlyId = item.id
    dataForm.value.idCard = item.idCard
    dataForm.value.elderName = item.elderName
    dataForm.value.overheadChargeId = item.overheadChargeId
    dataForm.value.originalId = item.bedId
    dataForm.value.originalName = item.bedName
    dataForm.value.originalAmount = item.actualAmount
  }
  //http://192.168.100.21:48080/admin-api/build/getBedList?bedName=&status=0&tenantIds=0&orgType=1
  if (id) {
    const res = await getBedChangeRecordById(id, status,isDetail.value)
    dataForm.value = res
    dataForm.value.changeFiles = res.changeFiles ? JSON.parse(res.changeFiles) : []
    discount.value = formatNum(res.discount)
    discountAmount.value = formatNum(res.discountAmount)
    if(!res.startTenantId){
      dataForm.value.startTenantId = getTenantId()
    }
  }
  getOverheadList()
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  return {
    valid,
    dataForm: {
      ...dataForm.value,
      changeFiles: JSON.stringify(dataForm.value.changeFiles),
      type: 4 // 床位变更
    }
  }
}

const diffValueStr = (dataForm) =>{
  try {
    return parseFloat((dataForm.actualAmount - dataForm.originalAmount).toFixed(2))
  }catch (_) {}
  return 0
}

const bedList = ref<{ chargeName: string; id: string; price: number; superiorsId: string }[]>([])
const getOverheadList = async () => {
  const res = await getOverheadListByType(1, dataForm.value.startTenantId)
  bedList.value = res
}

const bedChange = () => {
  // bedList.value.map((item)=>{
  //   if(item.id==overheadChargeId){
  //     dataForm.value.originalAmount = item.price
  //   }
  // })

}

// 项目类别
const treeList = ref()
const getTreeData = async () => {
  try {
    loading.value = true
    const data = await getChargeCategoryTree()
    treeList.value = filteredTreeData(data, 'childrenList')
  } catch (err) {
    console.log('err', err)
  } finally {
    loading.value = false
  }
}

const handleChange = () => {
  const item = bedList.value.find((item) => item.id == dataForm.value.expectOverheadChargeId)
  dataForm.value.amount = Number(item?.price)
  // 在tree中找到这棵树的上一级
  let node = findTreeNode(treeList.value, item?.superiorsId, 'id', 'childrenList')
  // 找到对应的名称
  const res = getParentNodesById(treeList.value, node.parentId, node.id)
  // 只保留最后两位
  if(res.length - 2 > 0){
    for(let i = 0; i <= res.length - 2; i++){
      res.pop()
    }
  }
  dataForm.value.categoryName = res.reverse().join('-')
  // 如果没有打折
  if(!dataForm.value.discount){
    dataForm.value.actualAmount = dataForm.value.amount
  }else{
    handleBlur(dataForm.value, 1)
  }
  for (const item of bedList.value){
    if(item.id==dataForm.value.expectOverheadChargeId){
      dataForm.value.expectName = item.chargeName
      break
    }
  }
}

// 是否启用打折
const handleSwitch = () => {
  dataForm.value.actualAmount = dataForm.value.amount
  dataForm.value.discountAmount = ''
  dataForm.value.discount = undefined
  discount.value = undefined
  discountAmount.value = ''
}

// 折扣和折扣率换算
const handleBlur = (item, type = 0) => {
  if (type == 1) {
    // 折扣价格
    item.discountAmount = discountAmount.value
    item.actualAmount = item.amount - discountAmount.value
    item.discount = item.discountAmount ? (1000 - (item.discountAmount / item.amount) * 1000) * 10 / 1000 : ''
    discount.value = item.discount
  } else if (type == 2) {
    item.discount = discount.value
    item.actualAmount = item.amount * (((item.discount / 100) * 10 * 100) / 100)
    item.discountAmount = ((item.amount * (1 - item.discount / 10)) / 10) * 10
    discountAmount.value = formatNum(((item.amount * (1 - item.discount / 10)) / 10) * 10)
  }
  item.totalAmount = item.isDiscount
    ? item.discount
      ? item.actualAmount
      : item.amount
    : item.amount
}

//let overheadChargeId = 0;
const handleSelectElder = (item) => {
  dataForm.value.idCard = item.idCard
  dataForm.value.elderName = item.elderName
  dataForm.value.overheadChargeId = item.overheadChargeId
  dataForm.value.originalId = item.bedId
  dataForm.value.originalName = item.bedName
  dataForm.value.originalAmount = item.actualAmount
  //overheadChargeId = item.overheadChargeId
}

const handleChangeBed = () => {
  for (const item of bedList.value){
    if(item.id==dataForm.value.expectOverheadChargeId){
      dataForm.value.expectName = item.chargeName
      break
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  dataForm.value = {...resetFormField}
  formRef.value?.resetFields()
}

const disabledDate = (time) =>{
  const now = new Date()
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
  const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0)
  return time < startOfMonth || time > endOfMonth
}

const processType = ref()
const getProcess = async (id, type, status) => {
  const res = await getBusinessId(id)
  init(res.businessId, true, status)
  processType.value = type
}

const setTenantId = (tId) => {
  dataForm.value.tenantId = tId
}

defineExpose({ init, submitForm, getProcess, resetForm, setTenantId }) // 提供 open 方法，用于打开弹窗
</script>
<style lang="scss" scoped>
.bed-change-form {
  .info {
    position: relative;

    .right {
      position: absolute;
      right: 10px;
      top: 20px;
    }
  }

  .price {
    color: #ff801d;
  }
}
</style>
