<template>
  <el-card style="margin-bottom: 0.5vh;background-color: rgb(243,250,254);">
    <div class="condition1">
      <div class="search">
        <el-text size="large" style="width:4vw;">{{ t('common.name') }}</el-text>
        <el-input v-model="searchForm.name" :placeholder="t('common.pleaseInputName')" style="width:9vw;" clearable />
      </div>
      <div class="search">
        <el-text size="large" style="width:4vw;">{{ t('common.jwcode') }}</el-text>
        <el-input v-model="searchForm.jwcode" :placeholder="t('common.jwcodePlaceholder')" style="width:9vw;" clearable />
      </div>
      <div class="search">
        <el-text size="large" style="width:4vw;">{{ t('common.productName') }}</el-text>
        <el-cascader v-model="searchForm.goodsName" :options="productList" style="width: 10vw;" clearable />
      </div>
      <div class="search" v-if="adminData.markets === t('common.markets.headquarter')">
        <el-text size="large" style="width:4vw;">{{ t('common.market') }}</el-text>
        <el-cascader style="width: 9vw;" v-model="searchForm.markets" :options="market" :placeholder="t('common.marketPlaceholder')"
          clearable />
      </div>
      <div class="search">
        <el-text size="large" style="width:4vw;">{{ t('common.refundCurrency') }}</el-text>
        <el-select v-model="searchForm.refundCurrency" style="width:9vw;" clearable>
          <el-option v-for="item in currencies" :key="item" :label="item" :value="item" />
        </el-select>
      </div>
    </div>
    <div class="condition1">
      <div class="search2">
        <el-text size="large" style="width:4vw;">{{ t('common.refundMethod') }}</el-text>
        <el-select v-model="searchForm.refundChannels" style="width:9vw;" clearable>
          <el-option v-for="item in channelOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </div>
      <div class="search2">
        <el-text size="large" style="width:4vw;">{{ t('common.orderStatus') }}</el-text>
        <el-select v-model="searchForm.statuses" style="width:9vw;" clearable>
          <el-option v-for="item in statusList" :label="item" :value="item" :key="item" />
        </el-select>
      </div>
      <div class="search2" style="width: 25.5vw;">
        <el-text size="large" style="width:4vw;">{{ t('common.refundTime') }}</el-text>
        <el-date-picker v-model="dateRange" type="datetimerange" :range-separator="t('common.to')" 
        :start-placeholder="t('common.startTime')"
        :end-placeholder="t('common.endTime')" style="width:18vw;" clearable :disabled-date="disabledDate"
          :default-time="defaultTime" />
      </div>
      <div>
        <el-button type="primary" size="medium" @click="getRefund">{{ t('common.search') }}</el-button>
        <el-button type="success" size="medium" @click="reset">{{ t('common.reset') }}</el-button>
      </div>
    </div>
  </el-card>

  <el-card style="background-color: rgb(231,244,253);height:80vh;">
    <el-table :data="tableData" style="height:70vh;width:82vw;">
      <el-table-column type="index" :label="t('common_list.id')" width="60" fixed="left">
        <template #default="scope">
          {{ scope.$index + 1 + (pagination.pageNum - 1) * pagination.pageSize }}
        </template>
      </el-table-column>
      <el-table-column prop="jwcode" label="Homily ID" width="120" fixed="left" />
      <el-table-column prop="name" :label="t('common_list.name')" width="120" fixed="left" show-overflow-tooltip />
      <el-table-column prop="marketName" :label="t('common_list.market')" width="120" />
      <el-table-column prop="goodsName" :label="t('common_list.productName')" width="120" />
      <el-table-column prop="goodsNum" :label="t('common_list.productNum')" width="120" />
      <el-table-column prop="refundModel" :label="t('common_list.refundModel')" width="140">
        <template #default="scope">
          {{ scope.row.refundModel === 1 ? t('common_list.refundModelPart') : t('common_list.refundModelAll') }}
        </template>
      </el-table-column>
      <el-table-column prop="refundCurrency" :label="t('common_list.refundCurrency')" width="120">
        <template #default="scope">
          <div v-if="!scope.row.refundCurrency">
            <text style="color: #FA5A1E;">{{ t('common_list.toSupply') }}</text>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="refundAmount" :label="t('common_list.refundAmount')" width="120">
        <template #default="scope">
          <div v-if="!scope.row.refundAmount">
            <text style="color: #FA5A1E;">{{ t('common_list.toSupply') }}</text>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="refundChannels" :label="t('common_list.refundChannels')" width="120">
        <template #default="scope">
          <div v-if="!scope.row.refundChannels">
            <text style="color: #FA5A1E;">{{ t('common_list.toSupply') }}</text>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="refundVoucher" :label="t('common_list.refundVoucher')" width="120">
        <template #default="scope">
          <el-image v-if="scope.row.refundVoucher" :src="scope.row.refundVoucher"
            @click="previewImage(scope.row.refundVoucher)"
            style="width: 40px; height: 40px; cursor: pointer;z-index: 99999;" fit="cover" />
          <span v-else style="color: #FA5A1E;">{{ t('common_list.toSupply') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="refundTime" :label="t('common_list.refundTime')" width="180">
        <template #default="scope">
          <div v-if="!scope.row.refundTime">
            <text style="color: #FA5A1E;">{{ t('common_list.toSupply') }}</text>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="t('common_list.orderStatus')" width="120">
        <template #default="scope">
          {{ scope.row.status === 41 ? t('common_list.refundSuccess') : t('common_list.pending') }}
        </template>
      </el-table-column>
      <el-table-column prop="operation" :label="t('common_list.operation')" fixed="right" width="100px">
        <template #default="scope">
          <div class="operation">
            <el-button v-if="scope.row.status === 40" type="primary" text @click="showEditDialog(scope.row)">
              {{ t('common.submit') }}
            </el-button>
            <el-button v-else type="primary" text @click="showEditDialog(scope.row)">
              {{ t('common.edit') }}
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
      @size-change="handlePageSizeChange" @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" style="margin-top: 1vh;" />
  </el-card>

  <el-dialog v-model="showEdit" class="edit" overflow draggable
    style="width: 40vw; background-color: #F3FAFE !important;">
    <div style="display: flex;">
      <div class="left">
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.jwcode') }}</el-text>
          <el-input v-model="editRow.jwcode" style="width:10vw;" disabled />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.customerName') }}</el-text>
          <el-input v-model="editRow.name" style="width:10vw;" disabled />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.market') }}</el-text>
          <el-input v-model="editRow.marketName" style="width:10vw;" disabled />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.productName') }}</el-text>
          <el-input v-model="editRow.goodsName" style="width:10vw;" disabled />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.refundModel') }}</el-text>
          <el-select v-model="editRow.refundModel" style="width:10vw;" disabled>
            <el-option :label="t('common_add.refundModelAll')" :value="0"></el-option>
            <el-option :label="t('common_add.refundModelPart')" :value="1"></el-option>
          </el-select>
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.payCurrency') }}</el-text>
          <el-input v-model="editRow.paymentCurrency" style="width:10vw;" disabled />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.payAmount') }}</el-text>
          <el-input v-model="editRow.paymentAmount" style="width:10vw;" disabled />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.payMethod') }}</el-text>
          <el-input v-model="editRow.payType" style="width:10vw;" disabled />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.payTime') }}</el-text>
          <el-input v-model="editRow.payTime" style="width:10vw;" disabled />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.submitter') }}</el-text>
          <el-input v-model="editRow.submitter" style="width:10vw;" disabled />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.transferVoucher') }}</el-text>
          <img v-if="editRow.payVoucher" :src="editRow.payVoucher"
            style="width: 80px; height: 80px; object-fit: cover;">
          <div v-else>
            {{ t('common_add.noTransferVoucher') }}
          </div>
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.remark') }}</el-text>
          <el-input v-model="editRow.payRemark" style="width:10vw;" :row="3" disabled maxlength="100" type="textarea"
            show-word-limit clearable />
        </div>
      </div>
      <div class="right">
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.refundCurrency') }}</el-text>
          <el-select v-model="editForm.refundCurrency" :placeholder="t('common_add.refundCurrencyPlaceholder')" style="width:10vw;">
            <el-option v-for="item in currencies" :key="item" :label="item" :value="item" />
          </el-select>
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.refundAmount') }}</el-text>
          <el-input v-model="editForm.refundAmount" :placeholder="t('common_add.refundAmountPlaceholder')" style="width:10vw;" clearable />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.refundChannels') }}</el-text>
          <el-select v-model="editForm.refundChannels" :placeholder="t('common_add.refundChannelsPlaceholder')" style="width:10vw;">
            <el-option v-for="item in channelOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.refundTime') }}</el-text>
          <el-date-picker v-model="editForm.refundTime" type="datetime" :placeholder="t('common_add.refundTimePlaceholder')" style="width:10vw;"
            clearable />
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.refundVoucher') }}</el-text>
          <el-upload ref="uploadRef" :http-request="customUpload" list-type="picture-card" :auto-upload="false"
            :on-change="handleImageChange" :before-upload="beforeUpload" :show-file-list="false">
            <template #default>
              <img v-if="editForm.imageUrl" :src="editForm.imageUrl"
                style="width: 80px; height: 80px; object-fit: cover;">
              <el-icon v-else>
                <Plus />
              </el-icon>
            </template>
          </el-upload>
        </div>
        <div class="dialog-item">
          <el-text style="width:4vw;">{{ t('common_add.remark') }}</el-text>
          <el-input v-model="editForm.refundRemark" :placeholder="t('common_add.remarkPlaceholder')" style="width:10vw;" :rows="3" maxlength="100"
            show-word-limit type="textarea" clearable />
        </div>
        <div style="display:flex;justify-content: center;margin-top: 5vh;">
          <el-button type="default" @click="hideEditDialog" style="margin-right: 2vw;">{{ t('common.cancel') }}</el-button>
          <el-button type="primary" @click="submitRefund">{{ t('common.submit') }}</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import API from '@/util/http.js'
import dayjs from 'dayjs'
import { useAdminStore } from "@/store/index.js"
import { storeToRefs } from "pinia"
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { productList, CurrencyForId } from '@/views/moneyManage/receiveDetail/utils/staticData.js'
const adminStore = useAdminStore()
const { adminData, menuTree } = storeToRefs(adminStore)
import { permissionMapping, findMenuById } from "@/utils/menuTreePermission.js"
import moment from 'moment'
import { isNumber } from 'lodash'
// 国际化
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const uploadUrl = 'https://api.homilychart.com/hljw/api/aws/upload'
const dateRange = ref([])
const tableData = ref([])
const editRow = ref({})// 编辑回显
const statusList = ref([t('cash.pending'), t('cash.refundSuccess')])
const pagination = ref({
  pageNum: 1,
  pageSize: 50,
  total: 0
})
const market = ref([])
const uploadRef = ref(null)
const searchForm = ref({
  jwcode: '',
  markets: []
})
const showEdit = ref(false)
const editForm = ref({
  jwcode: ''
})
// 查全部
const getRefund = async function () {
  try {
    const statusesParam = [40, 41] // 默认：看不到进度没到这里的
    if (searchForm.value.statuses === '待处理') {
      statusesParam.value = [40]
    } else if (searchForm.value.statuses === '退款成功') {
      statusesParam.value = [41]
    } else {
      statusesParam.value = [40, 41]
    }

    const goodsName = searchForm.value.goodsName && searchForm.value.goodsName.length > 0
      ? searchForm.value.goodsName[searchForm.value.goodsName.length - 1] : ''

    if (searchForm.value.jwcode) {
      const isPositiveInteger = /^[1-9]\d*$/.test(searchForm.value.jwcode);
      if (!isPositiveInteger) {
        ElMessage.error(t('elmessage.checkJwcodeFormat'))
        return;
      }
    }
    // 增加精网号长度限制，防止后端400错误
    if (searchForm.value.jwcode.length > 8) {
      ElMessage.error(t('elmessage.limitJwcodeLength'))
      return;
    }

    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      cashRecordDTO: {
        jwcode: searchForm.value.jwcode,
        name: searchForm.value.name,
        markets: searchForm.value.markets && searchForm.value.markets.length > 0 ? [searchForm.value.markets[searchForm.value.markets.length - 1]] : [],
        goodsName: goodsName,
        statuses: statusesParam.value,//10：地区财务待审核；12：地区财务驳回；
        // 20：地区负责人待审核；22：地区负责人驳回；
        // 30：总部财务待审核；32：总部财务驳回；
        // 40：执行人待处理；41：执行人已处理，退款完成；
        paymentCurrency: CurrencyForId(searchForm.value.paymentCurrency),
        refundCurrency: searchForm.value.refundCurrency,
        sTime: dateRange.value && dateRange.value[0] ? dayjs(dateRange.value[0]).format('YYYY-MM-DD HH:mm:ss') : "",
        eTime: dateRange.value && dateRange.value[1] ? dayjs(dateRange.value[1]).format('YYYY-MM-DD HH:mm:ss') : "",
        adminId: adminData.value.id,
        executor: adminData.value.account,
        refundChannels: searchForm.value.refundChannels
      }
    }

    const result = await API({
      url: '/Money/exSelect',
      method: 'POST',
      data: params
    })

    tableData.value = result.data.list || []
    pagination.value.total = result.data.total || 0
  } catch (error) {
    ElMessage.error(error.message || t('elmessage.searchFailed'))
  }
}
// 提交
const submitRefund = async function () {
  try {
    const numberReg = /^[0-9]+(\.[0-9]+)?$/
    if (!numberReg.test(editForm.value.refundAmount)) {
      ElMessage.error(t('elmessage.checkNumberOrDecimal'))
      return
    }
    const params = {
      refundVoucher: editForm.value.imageUrl,
      refundTime: editForm.value.refundTime ? dayjs(editForm.value.refundTime).format('YYYY-MM-DD HH:mm:ss') : "",
      refundRemark: editForm.value.refundRemark,
      id: editRow.value.id,
      refundCurrency: editForm.value.refundCurrency,
      refundAmount: editForm.value.refundAmount,
      refundChannels: editForm.value.refundChannels,
      status: 41,
      auditId: editRow.value.auditId,
      executor: adminData.value.account
    }
    const result = await API({
      url: '/Money/executor',
      data: params
    })
    if (result.code === 200) {
      ElMessage.success(t('elmessage.submitSuccess'))
      hideEditDialog()
      getRefund()
    } else {
      ElMessage.error(result.msg || t('elmessage.submitFailed'))
    }
  } catch (error) {
    ElMessage.error(error.message || t('elmessage.submitFailed'))
  }
}
const getMarket = async function () {
  try {
    const result = await API({

      url: '/market/selectMarket',
    })
    console.log('看看地区树', result)

    const transformTree = (nodes) => {
      const allChildren = nodes.flatMap(node => node.children || []);

      return allChildren.map(child => {
        const grandchildren = child.children && child.children.length
          ? transformTree([child])
          : null;

        return {
          value: child.id,
          label: child.name,
          children: grandchildren
        };
      });
    };
    market.value = transformTree(result.data)
    console.log('转换后的地区树==============', market.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
const showEditDialog = (row) => {
  editRow.value = row
  editForm.value.refundCurrency = ''
  editForm.value.refundAmount = ''
  editForm.value.channels = []
  editForm.value.refundTime = ''
  editForm.value.refundRemark = ''
  editForm.value.imageUrl = ''
  showEdit.value = true
}
const hideEditDialog = () => {
  showEdit.value = false
  editForm.value = {
    jwcode: ''
  }
}
// const currencies = ref(['美元(USD)', '港币(HKD)', '新币(SGD)', '马币(MYR)', '泰铢(THB)', '加币(CAD)', '越南盾(VND)', '韩元(KRW)'])
const currencies = ref([
    t('cash.currency.usd'),   // 美元(USD)
    t('cash.currency.hkd'),   // 港币(HKD)
    t('cash.currency.sgd'),   // 新币(SGD)
    t('cash.currency.myr'),   // 马币(MYR)
    t('cash.currency.thb'),   // 泰铢(THB)
    t('cash.currency.cad'),   // 加币(CAD)
    t('cash.currency.vnd'),   // 越南盾(VND)
    t('cash.currency.krw')    // 韩元(KRW)
])
// const channelOptions = ref(["Stripe-链接收款", "PaymentAsia-链接收款", "Ipay88-链接收款", "银行转账", "刷卡", "现金", "支票", "Grabpay", "Nets", "E-Transfer", "Paypal"])
const channelOptions = ref([
    t('cash.payMethods.stripe'),
    t('cash.payMethods.paymentAsia'),
    t('cash.payMethods.ipay88'),
    t('cash.payMethods.bankTransfer'),
    t('cash.payMethods.card'),
    t('cash.payMethods.cash'),
    t('cash.payMethods.check'),
    t('cash.payMethods.grabpay'),
    t('cash.payMethods.nets'),
    t('cash.payMethods.transfer'),
    t('cash.payMethods.paypal'),
])


// 预览图片函数
const previewImage = (imageUrl) => {
  // 使用 element-plus 的 el-image 组件实现图片预览功能
  const imageElement = document.createElement('img');
  imageElement.src = imageUrl;
  imageElement.style.maxWidth = '80vw';
  imageElement.style.maxHeight = '80vh';

  const viewer = document.createElement('div');
  viewer.style.position = 'fixed';
  viewer.style.top = '0';
  viewer.style.left = '0';
  viewer.style.width = '100vw';
  viewer.style.height = '100vh';
  viewer.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
  viewer.style.display = 'flex';
  viewer.style.justifyContent = 'center';
  viewer.style.alignItems = 'center';
  viewer.style.zIndex = '9999';
  viewer.style.overflow = 'auto';

  viewer.appendChild(imageElement);
  document.body.appendChild(viewer);

  viewer.addEventListener('click', () => {
    document.body.removeChild(viewer);
  });
};

const handleImageChange = (file) => {
  uploadRef.value.submit()
}
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt1 = file.size / 1024 < 2048
  if (!isJPG && !isPNG) {
    ElMessage.error(t('elmessage.onlyUploadJPGPNG'))
    return false
  }
  if (!isLt1) {
    ElMessage.error(t('elmessage.limitImageSize2MB'))
    return false
  }
  return true
}
const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    const response = await API({
      url: uploadUrl,
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    if (response.code === 200 && response.data) {
      editForm.value.imageUrl = response.data.url
      ElMessage.success(response.msg || t('elmessage.uploadSuccess'))
    } else {
      ElMessage.error(response.msg || t('elmessage.uploadFailed'))
    }
  } catch (error) {
    console.error('上传错误:', error)
    ElMessage.error(t('elmessage.uploadFailed') + `: ${error.msg || error.message || t('elmessage.inNetworkError')}`)
  }
}
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]
const disabledDate = (time) => {
  const limitDate = new Date(2025, 0, 1);
  return time.getTime() < limitDate.getTime();
}
const reset = function () {
  searchForm.value = {
    jwcode: '',
    markets: [],
    statuses: []
  }
  // 重置页码
  pagination.value.pageNum = 1
  dateRange.value = []
  getRefund()
}
const handlePageSizeChange = function (val) {
  pagination.value.pageSize = val
  getRefund()
}
const handleCurrentChange = function (val) {
  pagination.value.pageNum = val
  getRefund()
}
onMounted(() => {
  console.log('???????????????????', adminData.value)
  getRefund()
  getMarket()
})
</script>
<style scoped>
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
:deep(.el-table__body td) {
  background-color: #F3FAFE !important;
}

:deep(.el-table__header th) {
  background-color: #F3FAFE !important;
}

:deep(.el-image-viewer) {
  z-index: 3000 !important;
  /* 确保高于固定列和对话框的层级 */
}

/* 若固定列仍遮挡，强制提高固定列容器的层级（可选） */
:deep(.el-table__fixed),
:deep(.el-table__fixed-right) {
  z-index: 10 !important;
  /* 低于预览层的 3000 即可 */
}

.condition1 {
  width: 82vw;
  display: flex;
  align-items: center;
  height: 4vh;

  .search {
    width: 18%;
    display: flex;
    align-items: center;
    margin-bottom: 1vh;
    margin-right: 0.5vw;
  }

  .search2 {
    width: 18%;
    display: flex;
    align-items: center;
    margin-right: 0.5vw;
  }
}

.edit {
  .left {
    width: 45%;
    height: 60vh;
    padding: 0 2vw;

    .dialog-item {
      display: flex;
      align-items: center;
      margin-bottom: 1vh;
    }

    .image {
      width: 4vw !important;
      height: 4vw !important;
    }

    :deep(.el-upload--picture-card) {
      width: 4vw !important;
      height: 4vw !important;
      padding: 0 !important;
    }
  }

  .right {
    width: 50%;

    .dialog-item {
      display: flex;
      align-items: center;
      margin-bottom: 1vh;
    }
  }
}
</style>