<template>
  <Dialog
    v-model="dialogVisible"
    :title="itemTitle"
    class="out-refund-form"
    width="82%"
    :scroll="dataForm.isRefund == '1'"
    @close="handleClosed"
  >
    <el-form
      class="-mb-15px"
      :model="dataForm"
      ref="formRef"
      label-width="90px"
      :rules="dataRule"
      :toggleType="isDetail"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="外出类型" prop="type">
            <TgSelect
              v-model="dataForm.type"
              :list="getDictOptions(DICT_TYPE.OUTING_REFUND_TYPE)"
              @change="handleChangeType"
            >
              <el-option
                v-for="(n, i) in getIntDictOptions(DICT_TYPE.OUTING_REFUND_TYPE)"
                :key="i"
                :label="n.label"
                :value="n.value"
              />
            </TgSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="是否退费" prop="isRefund">
            <TgRadio
              v-model="dataForm.isRefund"
              clearable
              :list="getDictOptions(DICT_TYPE.COMMON_STATUS6)"
            >
              <el-radio
                v-for="(item, index) in getIntDictOptions(DICT_TYPE.COMMON_STATUS6)"
                :key="index"
                :value="item.value"
                >{{ item.label }}</el-radio
              >
            </TgRadio>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item label="状态" prop="status">
            <TgRadio
              v-model="dataForm.status"
              clearable
              :list="getDictOptions(DICT_TYPE.COMMON_STATUS2)"
            >
              <el-radio
                v-for="(item, index) in getIntDictOptions(DICT_TYPE.COMMON_STATUS2)"
                :key="index"
                :value="item.value"
                >{{ item.label }}</el-radio
              >
            </TgRadio>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <TgTextarea
              v-model="dataForm.remarks"
              show-word-limit
              :maxlength="120"
              placeholder="请输入外出类型描述"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <template v-if="dataForm.isRefund == '1'">
        <div class="wrap">
          <div style="display: flex; align-items: center; flex-direction: row">
            <div style="font-weight: bold">退费条件</div>
            <el-radio-group v-model="dataForm.configType" style="margin-left: 38px">
              <el-radio :value="0" size="large">统一退费条件</el-radio>
              <el-radio :value="1" size="large">单独退费条件</el-radio>
            </el-radio-group>
          </div>
          <div class="desc" v-show="dataForm.configType == 0">
            外出超过
            <TgInputNumber class="w50 ml2 mr2" v-model="dataForm.maximumDays" />天满足退费条件
            其中自外出后第
            <TgInputNumber
              class="w50 ml2 mr2"
              v-model="dataForm.minimumDays"
            />天，开始退费，并且返院当日
            <!-- :max="Number(dataForm.maximumDays)" -->
            <TgRadio
              class="inline ml5"
              v-model="dataForm.isSameDayRefund"
              :list="getDictOptions(DICT_TYPE.REFUND_TERMS_TYPE)"
            >
              <el-radio
                v-for="(item, index) in getIntDictOptions(DICT_TYPE.REFUND_TERMS_TYPE)"
                :key="index"
                :value="item.value"
                >{{ item.label }}</el-radio
              >
            </TgRadio>
          </div>
          <div style="height: 20px; color: transparent" v-show="dataForm.configType != 0">--</div>
        </div>

        <div class="wrap">
          <p
            >退费项目
            <el-button class="ml10" type="primary" @click="handleAdd" v-if="!isDetail">
              <Icon icon="ep:zoom-in" />添加退费项目
            </el-button></p
          >
          <el-table :data="dataForm.items" style="width: 100%">
            <el-table-column width="55" v-if="!isDetail">
              <template #default="scope">
                <Icon
                  class="mt1"
                  :size="26"
                  color="#f09d31"
                  icon="ep:remove"
                  @click="handleDelete(scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="date" label="序号" width="55">
              <template #default="scope">
                <span class="text-num">{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="退费项目类型" width="210">
              <template #default="scope">
                <el-tree-select
                  v-if="!isDetail"
                  v-model="scope.row.categoryId"
                  :data="treeList"
                  :render-after-expand="false"
                  :props="defaultProps"
                  @change="getItemList(scope.row, true, shouldAutoFill(scope.row))"
                  filterable
                />
                <span v-else>{{
                  treeList
                    ? findTreeNode(treeList, scope.row.categoryId, 'id', 'childrenList').name
                    : scope.row.categoryId
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="退费项目" width="260">
              <template #default="scope">
                <TgSelect
                  v-model="scope.row.itemId"
                  placeholder="请选择"
                  clearable
                  :list="scope.row.itemList"
                  dictLabel="chargeName"
                  dict-value="id"
                >
                  <el-option
                    v-for="item in scope.row.itemList"
                    :key="item.id"
                    :label="item.chargeName + '(' + item.price + '元)'"
                    :value="item.id"
                  />
                </TgSelect>
              </template>
            </el-table-column>
            <el-table-column label="自定义项目金额" width="200">
              <template #default="scope">
                <el-input
                  v-model="scope.row.customAmount"
                  style="max-width: 300px"
                  placeholder="输入金额"
                  type="number"
                  :disabled="scope.row.isCustom == 0 || isDetail"
                  class="input-with-select"
                >
                  <template #prepend>
                    <el-select
                      v-model="scope.row.isCustom"
                      :disabled="isDetail"
                      placeholder="请选择"
                      style="width: 85px"
                    >
                      <el-option label="启用" :value="1" />
                      <el-option label="禁用" :value="0" />
                    </el-select>
                  </template>
                </el-input>
              </template>
            </el-table-column>

            <el-table-column prop="address" width="220">
              <template #default="scope">
                <el-radio-group
                  v-if="!isDetail"
                  v-model="scope.row.type"
                  @change="handleChangeScopeType(scope.row)"
                >
                  <el-radio-button
                    v-for="(n, i) in getIntDictOptions(DICT_TYPE.COST_TYPE)"
                    :key="i"
                    :label="n.label"
                    :value="n.value"
                  />
                </el-radio-group>
                <span v-else>{{ getDictLabel(DICT_TYPE.COST_TYPE, scope.row.type) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="200">
              <template #default="scope">
                <span v-if="scope.row.type == 2"
                  ><TgInputNumber v-model="scope.row.proportion" class="w120" />%</span
                >
                <span v-else>
                  <TgInputNumber
                    :disabled="scope.row.type == 3"
                    v-model="scope.row.amount"
                    class="w120"
                  />
                  元</span
                >
              </template>
            </el-table-column>
            <el-table-column
              v-if="dataForm.configType == 1"
              prop="amount2"
              label="退费条件"
              width="900"
            >
              <template #default="scope">
                <div style="display: flex; flex-direction: row; align-items: center">
                  <div
                    style="height: 60px; align-items: center; display: flex; flex-direction: row"
                  >
                    外出超过
                    <TgInputNumber
                      class="w50 ml2 mr2"
                      v-model="scope.row.maximumDays"
                    />天满足退费条件 其中自外出后第
                    <TgInputNumber
                      class="w50 ml2 mr2"
                      v-model="scope.row.minimumDays"
                    />天，开始退费，并且返院当日
                    <!-- :max="Number(scope.row.maximumDays)" -->
                    <TgRadio
                      class="inline ml5"
                      v-model="scope.row.isSameDayRefund"
                      :list="getDictOptions(DICT_TYPE.REFUND_TERMS_TYPE)"
                    >
                      <el-radio
                        v-for="(item, index) in getIntDictOptions(DICT_TYPE.REFUND_TERMS_TYPE)"
                        :key="index"
                        :value="item.value"
                        >{{ item.label }}</el-radio
                      >
                    </TgRadio>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>

      <!--      <div class="content">-->
      <!--        <div class="left">-->
      <!--          <img :src="counter" alt="" />-->
      <!--          <div class="column">-->
      <!--            <span class="text">外出退费计算器</span>-->
      <!--            <span>输入外出起止日期，测试一下退费金额吧。</span>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--        <el-button type="primary" round @click="handleTest">点击测试</el-button>-->
      <!--      </div>-->
    </el-form>
    <template #footer>
      <el-button @click="handleClosed">关闭</el-button>
      <el-button v-loading="formLoading" type="primary" @click="submitForm" v-if="!isDetail"
        >确定</el-button
      >
    </template>
    <Counter ref="counterRef" />
  </Dialog>
</template>
<script setup lang="ts">
import {
  getOutboundRefundDetail,
  addOutboundRefund,
  editOutboundRefund
} from '@/api/elderly/fee/out-refund'
import counter from '@/assets/svgs/elderly/counter.svg'
import { getOverheadPage } from '@/api/elderly/fee/overheadCharge'
import { getChargeCategoryTree } from '@/api/elderly/fee/chargeCategory'
import { filteredTreeData, findTreeNode } from '@/utils/tree'
import { OutRefundFormType } from '../types'
import Counter from './Counter.vue'
import {
  DICT_TYPE,
  getDictLabel,
  getDictOptions,
  getIntDictOptions,
  getStrDictOptions
} from '@/utils/dict'
defineOptions({ name: 'OutRefundForm' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const dialogVisible = ref(false) // 弹窗
const formRef = ref() // 表单 Ref
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const isDetail = ref(false)
const loading = ref(false)
const radioRule = ref(1)
const state = reactive<OutRefundFormType>({
  dataForm: {
    // 表单字段
    id: '',
    name: '',
    type: '',
    isRefund: '',
    isSameDayRefund: '',
    configType: 0,
    status: 1,
    remarks: '',
    maximumDays: undefined,
    minimumDays: undefined,
    items: [],
    tenantId: undefined
  },
  dataRule: {
    // 表单规则
    isRefund: [{ required: true, message: '是否退费不能为空', trigger: ['blur', 'change'] }],
    type: [{ required: true, message: '外出类型不能为空', trigger: ['blur', 'change'] }]
  }
})
const { dataForm, dataRule } = toRefs(state)
const resetFormField = reactive({ ...dataForm.value })

// 弹窗标题
const itemTitle = computed(() => {
  return isDetail.value ? '详情' : !dataForm.value.id ? '新增' : '修改'
})

/** 打开弹窗 */
const open = async (tenantId, id, detail) => {
  dialogVisible.value = true
  isDetail.value = detail
  dataForm.value.tenantId = tenantId
  await getTreeData()
  if (id) {
    try {
      const res = await getOutboundRefundDetail(id)
      dataForm.value = res
      dataForm.value.items.map(async (item) => {
        getItemList(item, false, false)
      })
    } finally {
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  let result = false
  // 判断列表退费项是否有重复
  dataForm.value.items.map((item, index) => {
    dataForm.value.items.map((m, i) => {
      if (item.itemId == m.itemId && index != i) {
        result = true
      }
      if (item.isCustom == 1 && item.customAmount == '') {
        result = true
      }
    })
  })
  if (result) {
    message.error('退费项目不能重复，并且金额不能为空')
    return
  }
  // 提交请求
  formLoading.value = true
  let params = { ...dataForm.value }
  params.items.map((item) => {
    item.itemList = undefined
  })
  try {
    const res = dataForm.value.id
      ? await editOutboundRefund(params)
      : await addOutboundRefund(params)
    if (res) {
      message.success(t('common.updateSuccess'))
      handleClosed()
      // 发送操作成功的事件
      emit('success')
    }
  } finally {
    formLoading.value = false
  }
}

// 关闭表单
const handleClosed = () => {
  dataForm.value = { ...resetFormField }
  dataForm.value.items = []
  formRef.value?.resetFields()
  dialogVisible.value = false
}

const handleAdd = () => {
  dataForm.value.items.push({
    categoryId: '',
    itemId: '',
    type: 3,
    isCustom: 0, //是否自定义
    customAmount: '', //自定义金额
    maximumDays: '',
    minimumDays: '',
    isSameDayRefund: '',
    amount: undefined,
    itemList: [],
    __isNew: true
  })
}
const handleDelete = (index: number) => {
  dataForm.value.items.splice(index, 1)
}

const counterRef = ref()
const handleTest = () => {
  counterRef.value.open(dataForm.value.minimumDays, dataForm.value.isSameDayRefund)
}

// 项目类别
const treeList = ref()
const defaultProps = ref({
  // 树形属性
  children: 'childrenList',
  label: 'name',
  value: 'id',
  disabled: 'disabled'
})
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 itemList = ref<{chargeName: string, id: string}>([])
const shouldAutoFill = (row) => {
  // 只有新增行才参与自动补齐/自动回填
  if (!row?.__isNew) return false
  if (!row?.categoryId) return false

  // 如果该分类存在“缺失的子项”，就允许自动补齐（用于你删除某个子项后再新增补回）
  const sameCategoryRows = dataForm.value.items.filter(
    (item) => item !== row && item.categoryId === row.categoryId
  )
  const existingItemIdSet = new Set(sameCategoryRows.map((item) => item.itemId).filter(Boolean))
  if (!Array.isArray(row.itemList) || row.itemList.length === 0) return true
  const missing = row.itemList.find((it) => it?.id && !existingItemIdSet.has(it.id))
  return Boolean(missing)
}

// 项目名称
// const itemList = ref<{chargeName: string, id: string}>([])
const getItemList = async (row, flag = true, flag2 = false) => {
  const prevCategoryId = row.categoryId
  if (flag) {
    row.itemId = ''
  }
  try {
    const data = await getOverheadPage({
      pageNum: 1,
      pageSize: 500,
      categoryId: row.categoryId
    })
    row.itemList = data.list

    // 如果该类型下的所有项目都已经在表格中存在，则禁止再次新增该类型
    if (row?.__isNew && Array.isArray(row.itemList) && row.itemList.length > 0) {
      const sameCategoryRows = dataForm.value.items.filter(
        (item) => item !== row && item.categoryId === row.categoryId
      )
      const existingItemIdSet = new Set(sameCategoryRows.map((item) => item.itemId).filter(Boolean))
      const allExist = row.itemList.every((it) => it?.id && existingItemIdSet.has(it.id))
      if (allExist) {
        message.warning('该退费类型下的所有项目已存在，请选择其他类型')
        row.categoryId = ''
        row.itemId = ''
        row.itemList = []
        return
      }
    }

    // 如果需要自动添加子项（仅补齐缺失，不删除/不重置已有行，避免误清空 customAmount）
    if (flag2 && Array.isArray(row.itemList) && row.itemList.length > 0) {
      // 新增行在成功触发自动补齐/回填后，避免后续再次触发
      if (row?.__isNew) {
        row.__isNew = false
      }
      const sameCategoryRows = dataForm.value.items.filter(
        (item) => item.categoryId === row.categoryId
      )
      const existingItemIdSet = new Set(sameCategoryRows.map((item) => item.itemId).filter(Boolean))

      // 当前行如果还没选子项：优先回填“缺失的子项”
      if (!row.itemId) {
        const missing = row.itemList.find((it) => it?.id && !existingItemIdSet.has(it.id))
        row.itemId = missing?.id || row.itemList[0]?.id || ''
        if (row.itemId) {
          existingItemIdSet.add(row.itemId)
        }
      }

      // 把该分类下剩余缺失的子项补充为新行（只新增，不动旧行）
      for (let i = 0; i < row.itemList.length; i++) {
        const id = row.itemList[i]?.id
        if (!id || existingItemIdSet.has(id)) continue
        existingItemIdSet.add(id)

        dataForm.value.items.push({
          categoryId: row.categoryId,
          itemId: id,
          type: 3,
          isCustom: 0, // 是否自定义
          customAmount: '', // 自定义金额
          maximumDays: '',
          minimumDays: '',
          isSameDayRefund: '',
          amount: undefined,
          itemList: row.itemList
        })
      }
    }
  } finally {
  }
}

const handleChangeType = (val) => {
  getDictOptions(DICT_TYPE.OUTING_REFUND_TYPE).map((item) => {
    if (item.value == val) {
      dataForm.value.name = item.label
    }
  })
}

const handleChangeScopeType = (row) => {
  row.proportion = ''
  row.amount = ''
}
</script>
<style lang="scss" scoped>
.out-refund-form {
  .w50 {
    display: inline-block;
    width: 80px;
  }

  .w120 {
    display: inline-block;
    width: 120px;
  }

  .wrap {
    p {
      font-weight: bold;
    }

    .desc {
      background-color: #f2f5fc;
      padding: 20px;
      border-radius: 10px;
      margin-bottom: 20px;
    }
  }

  .content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    margin: 50px 0;
    box-sizing: border-box;
    background: #f6f9fb;
    border-radius: 10px;

    .left {
      display: flex;
      align-items: center;

      .column {
        display: flex;
        flex-direction: column;
        margin-left: 10px;

        .text {
          color: #9e9e9e;
        }
      }
    }
  }
}
</style>
