<template>
  <div>
    <crud-template class="as-weight" :ref="(el) => (crudRef = el)" :home-data="field" @btnSearch="btnSearch"
      @submit="submit" @refreshLeft="refreshLeft" :tableData="tableData" @CurrentChange="handleCurrentChange"
      @pageSizeChange="(val) => {
      field.paging.currentPage = 1
      field.paging.pageSize = val
      getList()
    }
      ">
      <template #search>
        <el-input maxlength="60" v-trim clearable v-model="searchForm.id" style="width: 200px"
          placeholder="请输入消息批量导入记录id" />
        <el-select clearable v-model="searchForm.messageClientId" placeholder="请选择客户端" style="width: 200px">
          <el-option v-for="item in MESSAGE_TYPE" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-date-picker unlink-panels v-model="timeValue" type="daterange" range-separator="到"
          start-placeholder="查询开始日期" end-placeholder="查询结束日期" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD"
          @change="dateChangeHandle" :default-time="[
      new Date(2000, 1, 1, 0, 0, 0),
      new Date(2000, 2, 1, 23, 59, 59),
    ]" />
        <el-select clearable v-model="searchForm.status" placeholder="请选择审核状态" style="width: 200px">
          <el-option v-for="item in AUDIT_STATUS" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </template>

      <template #CustomButton>
        <el-button type="primary" @click="handleSmsPush">短信信息推送</el-button>
        <el-button type="success" @click="handleWechatPush">公众号信息推送</el-button>
        <el-button type="warning" @click="handleAppletPush">小程序信息推送</el-button>
      </template>

      <template #operation="{ scope }">
        <el-button type="success" @click="handleData(scope, 'detail')" size="small">
          详情
        </el-button>
        <el-button v-if="scope.row.status === '审核中'" type="primary" @click="handleData(scope, 'edit')" size="small">
          编辑
        </el-button>
        <el-button type="primary" @click="handleData(scope, 'toExamine')" size="small"
          v-if="scope.row.status == '审核中'">
          审批
        </el-button>
        <!-- <el-button type="primary" @click="handleData(scope, 'operation')" size="small">
          操作日志
        </el-button> -->
      </template>
    </crud-template>
    <detailDialog 
      :data-list="selectedData" 
      :detail-info="[]"
      :column="2"
      v-model="isDetailShow" 
    />
    <editDialog 
      :data-list="selectedData" 
      :MESSAGE_TYPE="MESSAGE_TYPE"
      :AUDIT_STATUS="AUDIT_STATUS"
      @success="getList"
      v-model="isEditShow" 
    />
    <examineApproveDialog @handleSuccess="getList" :data-list="selectedData" v-model="isToExamine" />
    <operationDialog :data-list="selectedData" v-model="isOperation" :SHORT_AUDIT_STATE="SHORT_AUDIT_STATE" />
    <smsPushDialog v-model="isSmsPushShow" @handleSendSuccess="handleSendSuccess" v-if="updateShow" :dataList="selectedData"
      :addOrEditText="addOrEditText" />
    <wechatPushDialog v-model="isWechatPushShow" :title="wechatTitle" :dataList="selectedData" @handleSendSuccess="handleSendSuccess"
      v-if="updateShow" @handleClose="handleClose" />
    <appletPushDialog v-model="isAppletPushShow" :title="appletTitle" :dataList="selectedData" @handleSendSuccess="handleSendSuccess"
      v-if="updateShow" @handleClose="handleClose" :miniProgramStateOptions="miniProgramStateOptions"
      :langOptions="langOptions" />
  </div>
</template>

<!-- 导入信息审批 -->
<script lang="ts" setup>
  // @ts-ignore crudFrom模板
  import CrudTemplate from '@/crud/index.vue'
  import { ref, onMounted, computed, nextTick } from 'vue'
  import { ElMessage, genFileId } from 'element-plus'
  import { defineAsyncComponent } from 'vue'
  const detailDialog = defineAsyncComponent(() => import('@/views/messagePush/pushManagement/components/detailDialog/index.vue'))
  const examineApproveDialog = defineAsyncComponent(() => import('./components/examineApproveDialog.vue'))
  const operationDialog = defineAsyncComponent(() => import('./components/operationDialog.vue'))
  const editDialog = defineAsyncComponent(() => import('./components/editDialog.vue'))
  const smsPushDialog = defineAsyncComponent(() => import('@/views/messagePush/pushManagement/shortMessage/components/addOrEditDialog.vue'))
  const wechatPushDialog = defineAsyncComponent(() => import('@/views/messagePush/pushManagement/wechatOfficialAccounts/components/addOrEditDialog.vue'))
  const appletPushDialog = defineAsyncComponent(() => import('@/views/messagePush/pushManagement/wechatApplet/components/addOrEditDialog.vue'))
  // 请求函数
  // @ts-ignore
  import BaseService from '@/utils/baseService'

  //crud配置
  import crudConfig from './crudConfig'
  // 拿到配置
  const { field, sendResultOption } = crudConfig()

  const timeValue = ref<any>([])
  function dateChangeHandle(val) {
    if (val) {
      searchForm.value.startTime = val[0]
      searchForm.value.endTime = val[1]
    } else {
      searchForm.value.startTime = ''
      searchForm.value.endTime = ''
    }
  }
  onMounted(() => {
    getList()
  })
  //整个crud虚拟dom
  const crudRef = ref()
  // 获取数据，查询条件
  const searchForm = ref({
    startTime: '', //开始时间
    endTime: '', //结束时间
    status: '',
    messageClientId: '',
    id: '',
  })
  const tableData = ref([])
  // 搜索按钮
  function btnSearch() {
    field.value.paging.currentPage = 1

    getList()
  }
  const selectedData = ref<any>({})
  const isDetailShow = ref(false)
  const isToExamine = ref(false)
  const isOperation = ref(false)
  const isEditShow = ref(false)
  const isSmsPushShow = ref(false)
  const isWechatPushShow = ref(false)
  const isAppletPushShow = ref(false)
  const addOrEditText = ref('推送')
  const wechatTitle = ref('微信公众号信息推送')
  const appletTitle = ref('微信小程序信息推送')
  const updateShow = ref(true)
  
  const handleData = (scope, key) => {
    console.log(scope)
    if (key == 'detail') {
      // 传递数据给detailDialog组件，传递applyId和id
      selectedData.value = {
        applyId: scope.row.id,
        id: scope.row.id
      }
      isDetailShow.value = true
    } else if (key == 'edit') {
      // 编辑 - 需要传递原始数据，而不是转换后的数据
      // 重新获取原始数据用于编辑
      crudRef.value.tableLoding = true
      BaseService.post('/msgw/importReview/view', {
        sendApplyId: scope.row.id
      }).then((res: any) => {
        crudRef.value.tableLoding = false
        if (res && res.code === 0) {
          selectedData.value = res.data.apply || scope.row
          isEditShow.value = true
        } else {
          ElMessage.error(res.message || '获取编辑数据失败')
        }
      }).catch((error) => {
        crudRef.value.tableLoding = false
        console.error('获取编辑数据失败:', error)
        ElMessage.error('获取编辑数据失败')
      })
    } else if (key == 'toExamine') {
      // 审核
      isToExamine.value = true
      selectedData.value = scope.row
    } else {
      isOperation.value = true
      selectedData.value = scope.row
    }
  }
  // 搜索重置
  function refreshLeft() {
    field.value.paging.currentPage = 1
    searchForm.value = {
      startTime: '', //开始时间
      endTime: '', //结束时间
      status: '',
      messageClientId: '',
      id: '',
    }
    tableData.value = []
    timeValue.value = []
    getList()
  }
  function submit(row) {
    BaseService.postN('/settlew/notice/externalsupplement', {
      id: row.id,
      diffRes: row.diffRes,
      totalAmount: row.totalAmount,
      recoverySituation: row.recoverySituation,
    }).then((res: any) => {
      if (res && res.code === 0) {
        crudRef.value.dialogFormVisible = false
        getList()
      } else {
        ElMessage.error(res.message)
      }
    })
  }
  // 处理请求参数
  const handleParams = () => {
    let data: any = {
      pageNo: field.value.paging.currentPage,
      pageSize: field.value.paging.pageSize,
      ...searchForm.value,
    }
    let params: any = {}
    for (let key in data) {
      if (data[key] || data[key] === 0) {
        params[key] = data[key]
      }
    }
    return params
  }

  // @ts-ignore
  import $storeinitData from '@/store/initData' //引入tab vuex
  const SHORT_AUDIT_STATE = computed(() => {
    return $storeinitData.state.dictData['SHORT_AUDIT_STATE'] || []
  })
  // 添加新的字典计算属性
  const AUDIT_STATUS = computed(() => {
    return $storeinitData.state.dictData['AUDIT_STATUS'] || []
  })
  const MESSAGE_TYPE = computed(() => {
    return $storeinitData.state.dictData['MESSAGE_TYPE'] || []
  })

  // 小程序相关选项数据
  const miniProgramStateOptions = [
    { lable: '正式版', value: 'formal' },
    { lable: '开发版', value: 'developer' },
    { lable: '体验版', value: 'trial' },
  ]
  const langOptions = [
    { lable: '简体中文', value: 'zh_CN' },
    { lable: '英文', value: 'en_US' },
    { lable: '繁体中文(中国香港)', value: 'zh_HK' },
    { lable: '繁体中文(中国台湾)', value: 'zh_TW' },
  ]
  
  // 字典转换工具函数
  const getDictLabel = (dictList: any[], value: any) => {
    const item = dictList.find(item => item.value == value)
    return item ? item.label : value
  }
  
  // 获取数据
  function getList() {
    const params = handleParams()
    crudRef.value.tableLoding = true //表格loading效果
    BaseService.post('/msgw/importReview/page', params).then(
      (res: any) => {
        crudRef.value.tableLoding = false
        if (res && res.code === 0) {
          let bizContent = res.data
          let data = bizContent.result || []
          // console.log(data)
          data.forEach((element) => {
            // 转换客户端名称 - 使用MESSAGE_TYPE字典
            element.messageType = getDictLabel(MESSAGE_TYPE.value, element.messageType)
            console.log(element.messageType,'type')
            // 转换审核状态 - 使用AUDIT_STATUS字典
            element.status = getDictLabel(AUDIT_STATUS.value, element.status)
            
            // // 转换发送结果 - 使用sendResultOption
            // element.taskStatus = getDictLabel(sendResultOption, element.sendResult)
          })
          tableData.value = data
          field.value.paging.total = bizContent.totalCount
        } else {
          ElMessage.error(res.message)
        }
      }
    )
  }
  // 处理当前页数
  function handleCurrentChange(val: number) {
    field.value.paging.currentPage = val
    getList()
  }

  // 详情-导入原文件文件下载
  const handleDownLoad = (data) => {
    console.log(data,'文件下载')
    const url = import.meta.env.VITE_APP_UPLOAD_URL + data.attachmentUrl
    const fileName = data.attachmentName || data.temUrl.split('/').pop() || ''
    BaseService.getDownload(url, fileName, true)
  }

  // 短信信息推送
  const handleSmsPush = () => {
    selectedData.value = {}
    addOrEditText.value = '推送'
    isSmsPushShow.value = true
  }

  // 公众号信息推送
  const handleWechatPush = () => {
    selectedData.value = {}
    wechatTitle.value = '微信公众号信息推送'
    isWechatPushShow.value = true
  }

  // 小程序信息推送
  const handleAppletPush = () => {
    selectedData.value = {}
    appletTitle.value = '微信小程序信息推送'
    isAppletPushShow.value = true
  }

  // 消息推送后刷新页面
  const handleSendSuccess = () => {
    getList()
    // 重置页面内容
    updateShow.value = false
    nextTick(() => {
      updateShow.value = true
    })
  }

  // 关闭对话框
  const handleClose = () => {
    selectedData.value = {}
    // 重置页面内容
    updateShow.value = false
    nextTick(() => {
      updateShow.value = true
    })
  }
</script>
