<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('R-GlobalOrder-Batch-Approve')"
    width="600px"
    :close-on-click-modal="false"
    @close="closeDia"
  >
    <el-form
      ref="formRef"
      :rules="rules"
      :model="approvalForm"
      label-width="120px"
      label-position="right"
    >
      <el-form-item prop="amount" :label="t('global.p16') + '：'">
        <el-input
          v-model.trim="approvalForm.amount"
          class="crm-border-radius-no"
          disabled
          clearable
          :placeholder="t('global.p16')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="fee" :label="t('global.p27') + '：'">
        <el-input
          v-model.trim="approvalForm.fee"
          class="crm-border-radius-no"
          disabled
          clearable
          :placeholder="t('global.p27')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="status" :label="t('Label.CheckResults') + '：'">
        <el-select
          v-model="approvalForm.status"
          class="crm_search_down"
          :placeholder="t('Placeholder.Choose')"
        >
          <el-option
            v-for="option in statusOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="approvalForm.status == 3"
        prop="approveDesc"
        :label="t('Label.Descr') + '：'"
      >
        <el-select
          v-model="approvalForm.approveDesc"
          filterable
          class="crm_search_down"
          :placeholder="t('Placeholder.Choose')"
          allow-create
        >
          <el-option
            v-for="item in reasonsList"
            :key="item.id"
            :label="langZh ? item.content : item.enContent"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDia">
          {{ t('Ucard.Business.p32') }}
        </el-button>
        <el-button type="primary" :loading="btnLoading" @click="approve">
          {{ t('card.Btn.Confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref, reactive, computed, watch, inject, defineProps, defineEmits } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessageBox } from 'element-plus'
  import CardService from '@/service/ucard'
  import Config from '@/config/index'
  import { safeGetUser } from '@/utils/safeJson.js'

  const { t } = useI18n()
  const { Code } = Config
  const Session = inject('session')
  const pigeon = inject('pigeon')

  // props
  const props = defineProps({
    visible: Boolean,
    ids: Array,
    reasons: Object,
    allData: Object,
  })

  // emits
  const emit = defineEmits(['close'])

  // 响应式数据
  const dialogVisible = ref(false)
  const formRef = ref(null)
  const btnLoading = ref(false)

  const approvalForm = reactive({
    amount: 0,
    fee: 0,
    approveDesc: null,
    status: null,
  })

  // 计算属性
  const user = computed(() => {
    return safeGetUser(Session)
  })

  const langZh = computed(() => {
    return Session.Get('lang') === 'cn'
  })

  const statusOptions = computed(() => [
    { label: t('Apply_info.VerifiedUser.Agree'), value: 2 },
    { label: t('Apply_info.VerifiedUser.Refused'), value: 3 },
  ])

  const reasonsList = computed(() => {
    return Object.values(props.reasons || {})
  })

  const rules = computed(() => ({
    status: [
      {
        required: true,
        message: t('vaildate.select.empty'),
        trigger: 'blur',
      },
    ],
    approveDesc: [
      {
        required: true,
        message: t('vaildate.select.empty'),
        trigger: 'blur',
      },
    ],
  }))

  // 方法
  const closeDia = (type) => {
    emit('close', type)
  }

  const approve = async () => {
    if (!formRef.value) return

    const valid = await formRef.value.validate()
    if (!valid) return

    const params = {
      ...approvalForm,
      ids: props.ids,
      operateUser: user.value.cId,
    }

    btnLoading.value = true
    try {
      const res = await CardService.globalOrderApprove(params)

      if (res.code == Code.StatusOK) {
        pigeon.success(res.msg)
        closeDia(true)
      } else {
        if (res.msg) {
          pigeon.error(res.msg)
        } else if (res.data) {
          const data = res.data
          const list = Object.entries(data).map(([key, value]) => {
            return `<div>${key}: ${value}</div>`
          })

          await ElMessageBox.alert(list.join(''), t('Ucard.GlobalOrder.approveTitle'), {
            center: true,
            dangerouslyUseHTMLString: true,
            confirmButtonText: t('Confirm'),
          })

          closeDia(true)
        }
      }
    } catch (error) {
      console.error('批量审批失败:', error)
      pigeon.error(t('Msg.SystemError'))
    } finally {
      btnLoading.value = false
    }
  }

  // 监听器
  watch(
    () => props.visible,
    (val) => {
      dialogVisible.value = val
    }
  )

  watch(dialogVisible, (val) => {
    if (!val) {
      closeDia()
    }
  })

  watch(
    () => props.allData,
    (val) => {
      if (val) {
        Object.assign(approvalForm, val)
      }
    },
    { immediate: true }
  )
</script>
