<template>
  <el-form
    ref="formRef"
    :model="dataForm"
    label-width="110px"
    :rules="dataRule"
    :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" type="2" @elder="handleSelectElder" :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="bedName">
            <TgInput v-model="dataForm.bedName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="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="associateId">
            <TgSelect v-model="dataForm.associateId" @change="handleChangeAssociate">
              <el-option
                v-for="(n, i) in evaluationList"
                :key="i"
                :label="n.processName"
                :value="n.evaluationProcessId"
              />
            </TgSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="能力评估结果">
            <el-button
              :disabled="!dataForm.associateId"
              style="width: 100%"
              @click="handleOpenReport"
              ><Icon icon="ep:document" />{{ propertiesName }}</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="6" :xs="24">
          <el-form-item label="新护理等级" prop="expectId">
            <TgSelect
              v-model="dataForm.expectId"
              placeholder="请选择"
              :disabled="!dataForm.elderlyId"
              clearable
              @change="handleChange"
              :list="nurseList"
              dict-label="chargeName"
              dict-value="id"
            >
              <el-option v-for="t in nurseList" :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="护理费原价">
            <span class="price">¥{{ formatNum(dataForm.amount) }}元/月</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="是否打折">
            <el-switch
              v-model="dataForm.isDiscount"
              inline-prompt
              active-text="是"
              inactive-text="否"
              :active-value="1"
              :inactive-value="0"
              @change="handleSwicth"
            />
          </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 prop="reason" label="变更原因">
            <TgTextarea v-model="dataForm.reason" />
          </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 }"
            />
          </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" />
            </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 />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="床位号" prop="bedName">
              <TgInput v-model="dataForm.bedName" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="阶段评估" prop="evaluationProcessId">
              <TgSelect
                v-model="dataForm.evaluationProcessId"
                @change="handleChangeAssociate"
                :list="evaluationList"
                dict-label="processName"
                dict-value="evaluationProcessId"
              >
                <el-option
                  v-for="(n, i) in evaluationList"
                  :key="i"
                  :label="n.processName"
                  :value="n.evaluationProcessId"
                />
              </TgSelect>
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="能力评估结果">
              <el-button
                :disabled="!!!dataForm.evaluationProcessId"
                style="width: 200px"
                @click="handleOpenReport"
                ><Icon icon="ep:document" />{{ propertiesName }}</el-button
              >
            </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="变更生效日期" />
            </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="originalName">
              <TgInput v-model="dataForm.originalName" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="护理标准价格" prop="originalAmount">
              <TgInput v-model="dataForm.originalAmount" />
            </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" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="info-title">变更后</div>
      <div class="info-wrap">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8">
            <el-form-item label="护理等级" prop="expectId">
              <TgSelect
                v-model="dataForm.expectId"
                placeholder="请选择"
                clearable
                @change="handleChange"
                :list="nurseList"
                dict-label="chargeName"
                dict-value="id"
              >
                <el-option v-for="t in nurseList" :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="actualAmount">
              {{ 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="isDiscount">
              <TgSwitch v-model="dataForm.isDiscount" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="processType == 2 ? 24 : 8" v-show="dataForm.isDiscount==1">
            <el-form-item label="折后价格" prop="actualAmount">
              {{ formatNum(dataForm.actualAmount) }}
            </el-form-item>
          </el-col>

          <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
                v-model="dataForm.changeFiles"
                fun-name="附件"
                :elder="{ elderId: dataForm.elderlyId, elderName: dataForm.elderName }"
                :is-detail="isDetail"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
  </el-form>
  <EvaluationDetail ref="reportRef" />
</template>
<script setup lang="ts">
import { getNursingLevelPage } from '@/api/elderly/nursing'
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 { formatNum } from '@/utils/formatter'
import { getBusinessId } from '@/api/elderly/common'
import { getNurseChangeRecordById, getEvaluationByElderId } from '@/api/elderly/elder/nurse-change'
import EvaluationDetail from '@/views/elderly/assess/synthetic-ability/Detail.vue'
import { getEvaluationProcessConfigList } from '@/api/elderly/assess/evaluation-process'
import { getSyntheticAbilityName } from '@/utils/synthetic-ability'
import { nurseChangeFormType } from '../types'
import { getTenantId } from '@/utils/auth'
defineOptions({ name: 'NurseChangeProcessForm' })
const formRef = ref() // 表单 Ref
const state = reactive<nurseChangeFormType>({
  dataForm: {
    id: '',
    elderlyId: '',
    elderName: '',
    idCard: '',
    originalName: '',
    originalId: '',
    bedName: '',
    categoryName: '',
    overheadChargeId: '',
    expectOverheadChargeId: '',
    expectId: '',
    expectName: '',
    changeDate: formatTime(Date.now(), 'yyyy-MM-dd'),
    associateId: '',
    isDiscount: '',
    amount: 0,
    discountAmount: '',
    discount: undefined,
    actualAmount: 0,
    originalAmount: undefined,
    originalIsDiscount: undefined,
    evaluationProcessId: undefined,
    reason: '',
    changeFiles: [],
    startTenantId: '', // 流程租户id
    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' }],
    // associateId: [{ 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 discountAmount = ref()
const discount = ref()
const isDetail = ref(false)
/** 打开弹窗 */
const init = async (id, detail, status) => {
  dataForm.value.startTenantId = getTenantId()
  await getTreeData()
  await getNurseLevelList()
  isDetail.value = detail
  if (id) {
    const res = await getNurseChangeRecordById(id, status,isDetail.value)
    dataForm.value = res
    dataForm.value.changeFiles = res.changeFiles ? JSON.parse(res.changeFiles) : []
    dataForm.value.associateId = res.evaluationProcessId
    discount.value = formatNum(res.discount)
    discountAmount.value = formatNum(res.discountAmount)
    syntheticAbilityId.value = res.syntheticAbilityId
    await getEvaluation()
    active.value = getSyntheticAbilityName(res.totalScore)
    if(!res.startTenantId){
      dataForm.value.startTenantId = getTenantId()
    }

  }
 await getOverheadList()
  if(id){
    handleChange()
    console.log("AAAA",dataForm.value)
  }

}

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: 5 // 护理变更
    }
  }
}

const nurseLevelList = ref<{ nurseLevelName: string; id: string | number }[]>([])
const getNurseLevelList = async () => {
  try {
    const data = await getNursingLevelPage({
      pageNum: 1,
      pageSize: 100
    })
    nurseLevelList.value = data.list
  } finally {
  }
}

// 查询评估记录表
const evaluationList = ref<
  {
    evaluationProcessId: string
    processName: string
    syntheticAbilityId: number
    type: string
    totalScore: string
  }[]
>([])
const propertiesName = ref('') // 评估登记
const getEvaluation = async () => {
  const res = await getEvaluationByElderId(dataForm.value.elderlyId)
  evaluationList.value = res

  // 获取对应的分数段
  const result = res[0] && res[0].evaluationProcessId ? await getEvaluationProcessConfigList({
    evaluationProcessId: res[0].evaluationProcessId
  }) : []
  const arr = [...result, {propertiesName: '未评估'}]
  // 找到对应的分数段
  if (res.totalScore && res.totalScore >= 0 && res.syntheticAbilityInfoList.length) {
    for (let i = 0; i < arr.length; i++) {
      if (Number(res.totalScore) >= arr[i].minValue && Number(res.totalScore) <= arr[i].maxValue) {
        propertiesName.value = arr[i].propertiesName || '查看'
        return false
      }
    }
  } else {
    propertiesName.value = arr[arr.length - 1].propertiesName
  }
}

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

// 护理标准
const nurseList = ref<{ chargeName: string; id: string; price: number; superiorsId: string }[]>([])
const getOverheadList = async () => {
  const res = await getOverheadListByType(2, dataForm.value.startTenantId)
  nurseList.value = res
}

// 项目类别
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 = () => {
  dataForm.value.expectOverheadChargeId = dataForm.value.expectId
  const item = nurseList.value.find((item) => item.id == dataForm.value.expectId)
  dataForm.value.expectName = item?.chargeName
  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('-')
  handleSwicth()

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

  // 如果没有打折
  if(!dataForm.value.discount){
    dataForm.value.actualAmount = dataForm.value.amount
  }else{
    handleBlur(dataForm.value, 1)
  }
}

// 折扣和折扣率换算
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
}

// 是否打折
const handleSwicth = () => {
  dataForm.value.discountAmount = ''
  dataForm.value.actualAmount = 0
  dataForm.value.discount = undefined
  discount.value = undefined
  discountAmount.value = ''
}

//let overheadChargeId = 0
// 选择长者
const handleSelectElder = (item) => {
  dataForm.value.idCard = item.idCard
  dataForm.value.bedName = item.bedName
  dataForm.value.originalName = item.itemName
  dataForm.value.overheadChargeId = item.overheadChargeId
  dataForm.value.originalId = item.originalId
  dataForm.value.associateId = '' // 清空评估表
  dataForm.value.elderName = item.elderName
  dataForm.value.originalAmount = item.actualAmount
  //overheadChargeId = item.overheadChargeId
  getEvaluation()
}

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

const active = ref()

// 得到评估报告id
const syntheticAbilityId = ref()
const handleChangeAssociate = (val) => {
  let item = evaluationList.value.find((item) => item.evaluationProcessId == val)
  syntheticAbilityId.value = item?.syntheticAbilityId
  // 评估结果
  active.value = getSyntheticAbilityName(item?.totalScore)
}

// 打开评估报告
const reportRef = ref()
const handleOpenReport = () => {
  reportRef.value.open(syntheticAbilityId.value)
}

// 根据流程获取业务id
const processType = ref()
const getProcess = async (id, type, status) => {
  const res = await getBusinessId(id)
  init(res.businessId, true, status)
  processType.value = type
}

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 setTenantId = (tId) => {
  dataForm.value.tenantId = tId
}

defineExpose({ init, submitForm, resetForm, getProcess, setTenantId }) // 提供 open 方法，用于打开弹窗
</script>
