<template>
  <el-dialog
    v-model="dialogVisible"
    :title="diaTitle"
    width="1343px"
    class="info-dialog"
    @close="closeDia"
  >
    <div class="dialog-content">
      <div class="title">
        {{ t('Ucard.GlobalOrder.info1') }}
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <div class="payout">
        <div class="payout_pay">
          <div class="money">
            {{ detailData.deductionAmount?.toFixed(2) || '- -' }}
          </div>
          <div class="pay-bot">
            <img :src="currencyIcon(detailData.sendCurrency)" alt="" />
            <span>
              {{ detailData.sendCurrency }}
            </span>
          </div>
        </div>
        <div class="arrow">
          <img src="@/assets/image/card/globalOrder/icon-arrow.svg" alt="" />
        </div>
        <div class="payout_pay">
          <div class="money">
            {{ detailData.transferAmount?.toFixed(2) || '- -' }}
          </div>
          <div class="pay-bot">
            <img :src="currencyIcon(detailData.payoutCurrency)" alt="" />
            <span>
              {{ detailData.payoutCurrency }}
            </span>
          </div>
        </div>
      </div>
      <div class="payout_info">
        <el-row>
          <el-col v-for="(info, index) in payoutInfo" :key="index" :span="6">
            <div class="info-item">
              <div class="item-tit">
                {{ t(`Ucard.GlobalOrder.infoT${index + 1}`) }}
              </div>
              <div class="item-desc">
                {{ getInfoValue(index) }}
                <span
                  v-if="index === 0"
                  class="item-other"
                  @click="copyText(detailData.merchantOrderNo)"
                >
                  <img src="@/assets/image/card/globalOrder/icon-copy.svg" alt="" />
                </span>
                <span v-else-if="index === 1" class="item-other">
                  {{ detailData.payoutCurrency }}
                </span>
                <span v-else-if="index === 2" class="item-other">
                  {{ detailData.fee ? detailData.payoutCurrency : '' }}
                </span>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-tabs v-model="activeName" class="tabs" @tab-click="tabsClick">
        <el-tab-pane :label="t('Ucard.GlobalOrder.sender')" name="1">
          <div class="tab-item">
            <el-row>
              <el-col v-for="(item, index) in list.sender" :key="index" :span="6">
                <div class="item-tit">
                  {{ item.name }}
                </div>
                <div class="item-desc">
                  {{ item.value || '- -' }}
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="t('Ucard.GlobalOrder.receiver')" name="2">
          <div class="tab-item">
            <el-row>
              <el-col v-for="(item, index) in list.receiver" :key="index" :span="6">
                <div class="item-tit">
                  {{ item.name }}
                </div>
                <div class="item-desc">
                  {{ item.value || '- -' }}
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-form
        v-if="type === '2'"
        ref="formRef"
        :model="approveForm"
        :rules="rules"
        class="dialogCheck_form"
        label-width="135px"
      >
        <el-form-item :label="t('card.Form.f53') + '：'" prop="status">
          <el-select
            v-model="approveForm.status"
            :placeholder="t('Placeholder.Choose')"
            class="crm_search_down form-w300"
          >
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="approveForm.status == 3"
          :label="t('Label.Descr') + '：'"
          prop="approveDesc"
        >
          <el-select
            v-model="approveForm.approveDesc"
            :placeholder="t('Placeholder.Choose')"
            allow-create
            class="crm_search_down form-w300"
            filterable
            @change="selectChange"
          >
            <el-option
              v-for="item in reasonsList"
              :key="item.id"
              :label="langZh ? item.content : item.enContent"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <el-form
        v-if="complianceStatus"
        ref="complianceFormRef"
        :model="complianceForm"
        label-width="200"
      >
        <div v-if="complianceItems.senderItems.length" class="title">
          {{ t('Ucard.GlobalOrder.SenderComSubmit') }}
          <el-divider></el-divider>
        </div>
        <div v-for="field in complianceItems.senderItems" :key="field.fieldName">
          <el-form-item :label="field.fieldTitle" :prop="field.fieldName" :rules="getRules(field)">
            <el-input
              v-if="field.fieldType === 'input'"
              v-model="complianceForm[field.fieldName]"
              :disabled="field.disabled"
              class="form-w300"
              :placeholder="field.fieldDescription"
              @change="() => clearFieldValidate(field.fieldName)"
            />
            <!-- 下拉框 -->
            <el-select
              v-else-if="field.fieldType === 'select'"
              v-model="complianceForm[field.fieldName]"
              :disabled="field.disabled"
              class="form-w300"
              :placeholder="field.fieldDescription"
              @change="clearFieldValidate(field.fieldName)"
            >
              <el-option
                v-for="opt in field.availableDtos || []"
                :key="opt.valueId"
                :label="t('global.available')[opt.value] || opt.value"
                :value="opt.valueId"
              />
            </el-select>
            <!-- 日期 -->
            <el-date-picker
              v-else-if="field.fieldType === 'date'"
              v-model="complianceForm[field.fieldName]"
              :disabled="field.disabled"
              type="date"
              style="width: 300px !important"
              value-format="YYYY-MM-DD"
              :start-placeholder="t('Placeholder.Start')"
              :end-placeholder="t('Placeholder.End')"
              @change="clearFieldValidate(field.fieldName)"
            />
            <!-- 文件 -->
            <div v-if="field.fieldType === 'file'">
              <div v-if="!field.disabled">
                <el-upload
                  class="avatar-uploader"
                  :http-request="(e) => comUpload(e, field)"
                  :disabled="field.disabled"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                >
                  <img
                    v-if="
                      complianceForm[field.fieldName] && !isPdf(complianceForm[field.fieldName])
                    "
                    :src="complianceForm[field.fieldName]"
                    class="avatar"
                    alt=""
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <a
                  v-if="complianceForm[field.fieldName] && isPdf(complianceForm[field.fieldName])"
                  class="upload-pdf"
                  target="_blank"
                  :href="complianceForm[field.fieldName]"
                >
                  {{ getFieldName(complianceForm[field.fieldName]) }}
                  <el-icon><Document /></el-icon>
                </a>
              </div>
              <div v-else>
                <a
                  v-if="complianceForm[field.fieldName] && isPdf(complianceForm[field.fieldName])"
                  class="upload-pdf"
                  target="_blank"
                  :href="complianceForm[field.fieldName]"
                >
                  {{ getFieldName(complianceForm[field.fieldName]) }}
                  <el-icon><Document /></el-icon>
                </a>
                <el-image
                  v-else
                  style="width: 100px; height: 100px"
                  :lazy="false"
                  :src="complianceForm[field.fieldName]"
                  :preview-src-list="[complianceForm[field.fieldName]]"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
            </div>
          </el-form-item>
        </div>
        <div v-if="complianceItems.receiverItems.length" style="margin-bottom: 20px">
          {{ t('Ucard.GlobalOrder.ReceiverComSubmit') }}
        </div>
        <div v-for="field in complianceItems.receiverItems" :key="field.fieldName">
          <el-form-item :label="field.fieldTitle" :prop="field.fieldName" :rules="getRules(field)">
            <el-input
              v-if="field.fieldType === 'input'"
              v-model="complianceForm[field.fieldName]"
              :disabled="field.disabled"
              :placeholder="field.fieldDescription"
              @change="clearFieldValidate(field.fieldName)"
            />
            <!-- 下拉框 -->
            <el-select
              v-else-if="field.fieldType === 'select'"
              v-model="complianceForm[field.fieldName]"
              :disabled="field.disabled"
              :placeholder="field.fieldDescription"
              @change="clearFieldValidate(field.fieldName)"
            >
              <el-option
                v-for="opt in field.availableDtos || []"
                :key="opt.valueId"
                :label="t('global.available')[opt.value] || opt.value"
                :value="opt.valueId"
              />
            </el-select>
            <!-- 日期 -->
            <el-date-picker
              v-else-if="field.fieldType === 'date'"
              v-model="complianceForm[field.fieldName]"
              :disabled="field.disabled"
              type="date"
              value-format="YYYY-MM-DD"
              :start-placeholder="t('Placeholder.Start')"
              :end-placeholder="t('Placeholder.End')"
              @change="clearFieldValidate(field.fieldName)"
            />
            <!-- 文件 -->
            <div v-if="field.fieldType === 'file'">
              <div v-if="!field.disabled">
                <el-upload
                  class="avatar-uploader"
                  :http-request="(e) => comUpload(e, field)"
                  :disabled="field.disabled"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                >
                  <img
                    v-if="
                      complianceForm[field.fieldName] && !isPdf(complianceForm[field.fieldName])
                    "
                    :src="complianceForm[field.fieldName]"
                    class="avatar"
                    alt=""
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <a
                  v-if="complianceForm[field.fieldName] && isPdf(complianceForm[field.fieldName])"
                  class="upload-pdf"
                  target="_blank"
                  :href="complianceForm[field.fieldName]"
                >
                  {{ getFieldName(complianceForm[field.fieldName]) }}
                  <el-icon><Document /></el-icon>
                </a>
              </div>
              <div v-else>
                <a
                  v-if="complianceForm[field.fieldName] && isPdf(complianceForm[field.fieldName])"
                  class="upload-pdf"
                  target="_blank"
                  :href="complianceForm[field.fieldName]"
                >
                  {{ getFieldName(complianceForm[field.fieldName]) }}
                  <el-icon><Document /></el-icon>
                </a>
                <el-image
                  v-else
                  style="width: 100px; height: 100px"
                  :lazy="false"
                  :src="complianceForm[field.fieldName]"
                  :preview-src-list="[complianceForm[field.fieldName]]"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <el-button v-if="type === '2'" type="primary" @click="toConfirm()">
        {{ t('card.Btn.Submit') }}
      </el-button>
      <el-button v-if="type === '3'" type="primary" @click="toComConfirm()">
        {{ t('card.Btn.Submit') }}
      </el-button>
      <el-button @click="closeDia">
        {{ t('Btn.Cancel') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref, reactive, computed, watch, onMounted, nextTick, inject } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    complianceStatusEnum,
    payoutMethod,
    transferType,
    approvalText,
  } from '@/enum/card/globalOrder'
  import Service from '@/service/financial'
  import CardService from '@/service/ucard'
  import Config from '@/config'
  import isImageType from '@/utils/isImageType'
  import UcardService from '@/service/ucard'
  import { safeGetUser } from '@/utils/safeJson'
  import { copyText } from '@/utils/utils'
  import { Document, Picture, Plus } from '@element-plus/icons-vue'
  import _ from 'lodash'

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

  // 定义props
  const props = defineProps({
    // 1 详情窗口，2 审批窗口, 3 提交合规性检查资料
    type: {
      type: String,
      required: true,
      default: '1',
    },
    visible: {
      type: Boolean,
      required: true,
    },
    detailData: {
      type: Object,
      required: true,
    },
  })

  // 定义emits
  const emit = defineEmits(['close', 'update'])

  // 响应式数据
  const dialogVisible = ref(props.visible)
  const formRef = ref(null)
  const complianceFormRef = ref(null)
  const activeName = ref('1')
  const imageUrl = ref('')
  const reasons = ref({})

  const approveForm = reactive({
    status: '',
    approveDesc: '',
  })

  const complianceForm = reactive({})

  const list = reactive({
    sender: [],
    receiver: [],
  })

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

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

  // 监听dialogVisible变化
  watch(dialogVisible, (val) => {
    if (!val) {
      emit('close')
    }
  })

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

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

  const approverDesc = computed(() => {
    if (!reasons.value) return ''
    const data = reasons.value[props.detailData.approveDesc]
    return langZh.value ? data?.content : data?.enContent
  })

  const diaTitle = computed(() => {
    const titles = {
      1: t('R-Business-Single'),
      2: t('R-Business-Approve'),
      3: t('R-GlobalOrder-Btn'),
    }
    return titles[props.type] || ''
  })

  const complianceStatus = computed(() => {
    if (props.type === '1') {
      return props.detailData.complianceStatus !== 'pending_check'
    }
    return props.type === '3'
  })

  const complianceItems = computed(() => {
    let senderItems = []
    let receiverItems = []

    if (props.detailData?.dataDtos) {
      const processItems = (customerType) => {
        return props.detailData.dataDtos
          .filter((item) => item.customerType === customerType)
          .map((item) => {
            const fieldName = `${item.customerType}_${item.fieldName}`
            const fieldTitle = t(`global.fieldName.${fieldName}.fieldTitle`) + ':'
            const fieldDescription = t(`global.fieldName.${fieldName}.fieldDescription`)
            const disabled = [
              complianceStatusEnum.Approved,
              complianceStatusEnum.Pending,
              complianceStatusEnum.Rejected,
            ].includes(item.status)

            // 如果处于只读状态，设置表单值
            if (disabled) {
              complianceForm[fieldName] =
                item.fieldType === 'file' ? Host85 + item.rfiValueUrl : item.rfiValue
            }

            return {
              ...item,
              fieldName,
              fieldTitle,
              fieldDescription,
              disabled,
            }
          })
      }

      senderItems = processItems('sender')
      receiverItems = processItems('receiver')
    }
    return {
      senderItems: senderItems || [],
      receiverItems: receiverItems || [],
    }
  })

  const payoutInfo = computed(() => {
    return [
      { label: t('Ucard.GlobalOrder.infoT1') },
      { label: t('Ucard.GlobalOrder.infoT2') },
      { label: t('Ucard.GlobalOrder.infoT3') },
      { label: t('Ucard.GlobalOrder.infoT4') },
    ]
  })

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

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

  // 方法
  const currencyIcon = (currency) => {
    try {
      return new URL(`../../../../assets/image/card/globalOrder/${currency}.png`, import.meta.url)
        .href
    } catch (e) {
      return ''
    }
  }

  const isPdf = (url) => {
    return /\.pdf(\?.*)?$/i.test(url)
  }

  const tabsClick = (e) => {
    activeName.value = e.name
  }

  const getFieldName = (url) => {
    console.log('getFieldName', url)
    try {
      const urlObj = new URL(url)
      const pathname = urlObj.pathname
      const filename = pathname.split('/').pop()
      return filename || ''
    } catch (error) {
      console.error('无效的URL:', error)
      return ''
    }
  }

  const getInfoValue = (index) => {
    switch (index) {
      case 0:
        return props.detailData.merchantOrderNo
      case 1:
        return props.detailData.transferAmount
      case 2:
        return props.detailData.fee || '- - '
      case 3:
        return props.detailData.exchangeRate ? `1 : ${props.detailData.exchangeRate}` : '- - '
      default:
        return ''
    }
  }

  const closeDia = (update) => {
    Object.keys(approveForm).forEach((key) => (approveForm[key] = ''))
    Object.keys(complianceForm).forEach((key) => delete complianceForm[key])
    if (update === true) {
      emit('update')
    }
    dialogVisible.value = false
  }

  // 审批
  const toConfirm = async () => {
    if (!formRef.value) return

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

    const res = await CardService.globalOrderApprove({
      ...props.detailData,
      ...approveForm,
      operateUser: user.value.cId,
    })

    if (res.code == Code.StatusOK) {
      ElMessage.success(res.msg)
      closeDia(true)
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 提交合规性文件
  const toComConfirm = async () => {
    if (!complianceFormRef.value) return

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

    const list = [
      ...(complianceItems.value.senderItems ?? []),
      ...(complianceItems.value.receiverItems ?? []),
    ]

    const rfiInfos = list.map((item) => {
      const { fieldType, rfiId } = item
      let rfiValue = ''
      let rfiValueUrl = ''

      if (fieldType === 'file') {
        rfiValueUrl = complianceForm[item.fieldName]?.split(Host85)[1] || ''
      } else {
        rfiValue = complianceForm[item.fieldName] || ''
      }

      return {
        rfiId,
        fieldType,
        rfiValueUrl,
        rfiValue,
      }
    })

    const params = {
      cId: user.value.cId,
      orderNo: props.detailData.orderNo,
      rfiInfos,
    }

    const res = await CardService.globalSupplementary(params)

    if (res.code == Code.StatusOK) {
      ElMessage.success(res.msg)
      closeDia(true)
    } else {
      ElMessage.error(res.msg)
    }
  }

  const selectChange = () => {}

  // 获取原因列表
  const searchReasons = async () => {
    const res = await Service.reasonsRefusalList({ type: 10 })
    if (res.code == Code.StatusOK) {
      reasons.value = res.data || {}
    } else {
      ElMessage.error(res.msg)
    }
  }

  const clearFieldValidate = (fieldName) => {
    nextTick(() => {
      if (complianceFormRef.value) {
        complianceFormRef.value.clearValidate(fieldName)
      }
    })
  }

  // 表单校验
  const getRules = (field) => {
    const rules = []
    if (field.required) {
      rules.push({
        required: true,
        message: field.fieldDescription,
        trigger: 'blur',
      })
    }
    if (field.regex) {
      try {
        const reg = new RegExp(field.regex)
        rules.push({
          pattern: reg,
          message: `${field.fieldTitle}格式不正确`,
          trigger: 'blur',
        })
      } catch (e) {
        console.warn('Invalid regex:', field.regex)
      }
    }
    return rules
  }

  // 合规性检测文件上传
  const comUpload = async (field, item) => {
    const formData = new FormData()
    formData.append('category', 'globalTransfer')
    formData.append('file', field.file)

    try {
      const res = await UcardService.ucardUpload(formData)
      if (res.code === 200 && res.data) {
        complianceForm[item.fieldName] = Host85 + res.data
        ElMessage.success(t('Ucard.Business.ms11'))
      } else {
        ElMessage.error(res.msg)
      }
    } catch (e) {
      ElMessage.error(t('Ucard.Business.ms12'))
    }
  }

  const beforeUpload = (file) => {
    const isJPG = isImageType.checkFile(file.type)
    const isLt2M = isImageType.checkSize(file.size)

    if (!isJPG) {
      ElMessage.error(t('Msg.JPG1'))
    }
    if (!isLt2M) {
      ElMessage.error(t('Msg.3IMG'))
    }
    return isJPG && isLt2M
  }

  // 生命周期
  onMounted(() => {
    // 审批才需要原因列表 详情也需要展示
    if (props.type == '2' || props.detailData.approverStatus != '1') {
      searchReasons()
    }
    const fieldDtos = _.cloneDeep(props.detailData.fieldDtos)
    console.log(fieldDtos, '12')
    const sender =
      fieldDtos
        ?.sort((a, b) => a.sorting - b.sorting)
        .filter((item) => item.fieldUserType === 'sender')
        .map((item) => {
          const key = Object.keys(props.detailData).find(
            (k) => k.toLowerCase() === item.fieldName.toLowerCase()
          )
          const name = t(`global.fieldName.${item.fieldName}.fieldTitle`)
          let value = key ? props.detailData[key] : item.fixedValue
          if (item.fieldType === 'select' && !['transferType', 'payoutMethod'].includes(key)) {
            value = props.detailData[key + 'Value']
          }
          return { name, value }
        }) || []

    const receiver =
      fieldDtos
        ?.sort((a, b) => a.sorting - b.sorting)
        .filter((item) => item.fieldUserType === 'receiver')
        .map((item) => {
          const key = Object.keys(props.detailData).find(
            (k) => k.toLowerCase() === item.fieldName.toLowerCase()
          )
          const name = t(`global.fieldName.${item.fieldName}.fieldTitle`)
          let value = key ? props.detailData[key] : item.fixedValue
          if (item.fieldType === 'select' && !['transferType', 'payoutMethod'].includes(key)) {
            value = props.detailData[key + 'Value']
          }
          return { name, value }
        }) || []

    list.sender = sender
    list.receiver = receiver
  })
</script>

<style lang="scss" scoped>
  @import 'dialog.scss';
</style>
