<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { ElButton, ElDescriptions, ElDescriptionsItem, ElUpload, ElInput, ElIcon, ElImageViewer } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

import { downloadByUrl } from '#/utils/file/download';

import { uploadApi } from '#/api/core/upload';
import { requestClient } from '#/api/request';

const route = useRoute();
const id = computed(() => route.params.id as string);

// 交接详情数据
const handoverDetail = ref<any>(null);
// 加载状态
const loading = ref(true);
// 保存状态
const saving = ref(false);
// 确认交接状态
const confirming = ref(false);
// 图片预览相关
const previewVisible = ref(false);
const previewUrl = ref('');

// 获取交接详情
const getHandoverDetail = async () => {
  try {
    loading.value = true;
    const response = await requestClient.get(`/gasHandoverMain/main/${id.value}`);
    handoverDetail.value = response;
  } catch (error) {
    ElMessage.error('获取交接详情失败');
    console.error('获取交接详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 保存交接项
const saveItem = async (item: any) => {
  try {
    saving.value = true;
    await requestClient.put('/gasHandoverItems/items', {
      id: item.id,
      attachments: item.attachments,
      photos: item.photos,
      textContent: item.textContent,
    });
    ElMessage.success('保存成功');
  } catch (error) {
    ElMessage.error('保存失败');
    console.error('保存失败:', error);
  } finally {
    saving.value = false;
  }
};

// 自定义上传方法
const handleUpload = async (options: any, item: any, fieldName: string) => {
  try {
    const res = await uploadApi(options.file);
    const fileName = res.originalFilename || res.newFileName || res.fileName;
    const responseData = { 
      url: res.url,
      name: fileName // 使用原始文件名作为显示名称
    };
    
    // 根据字段名设置对应的fileName
    if (fieldName === 'photos') {
      item.photos = item.photos ? `${item.photos},${res.fileName}` : res.fileName;
      item.photosUrl = item.photosUrl ? `${item.photosUrl},${res.url}` : res.url;
    } else if (fieldName === 'attachments') {
      item.attachments = item.attachments ? `${item.attachments},${res.fileName}` : res.fileName;
      item.attachmentsUrl = item.attachmentsUrl ? `${item.attachmentsUrl},${res.url}` : res.url;
    }
    
    options.onSuccess(responseData);
  } catch (error) {
    console.error('上传失败:', error);
    options.onError(error);
  }
};

// 删除文件处理
const handleRemove = (file: any, fileList: any[], item: any, fieldName: string) => {
  // 从字段值中移除对应的fileName
  if (fieldName === 'photos' && item.photos) {
    item.photos = item.photos.split(',').filter(fileName => fileName !== file.name).join(',');
    item.photosUrl = item.photosUrl.split(',').filter(url => url !== file.url).join(',');
  } else if (fieldName === 'attachments' && item.attachments) {
    item.attachments = item.attachments.split(',').filter(fileName => fileName !== file.name).join(',');
    item.attachmentsUrl = item.attachmentsUrl.split(',').filter(url => url !== file.url).join(',');
  }
  return true;
};

// 预览文件处理
const handlePreview = (file: any) => {
  // 判断是否是图片文件
  const isImage = /\.(jpg|jpeg|png|gif|bmp)$/i.test(file.name);
  
  if (isImage) {
    // 图片预览
    previewUrl.value = file.url;
    previewVisible.value = true;
  } else {
    // 附件下载
    downloadByUrl({
      url: file.url,
      fileName: file.name
    });
  }
};

// 生成文件列表
const generateFileList = (item: any, fieldName: string) => {
  const newData = [];
  let urls, fileNames;
  
  // 根据字段名获取对应的URL和文件名
  if (fieldName === 'photos') {
    urls = item.photosUrl;
    fileNames = item.photos;
  } else if (fieldName === 'attachments') {
    urls = item.attachmentsUrl;
    fileNames = item.attachments;
  } else {
    return newData;
  }
  
  // 处理URL
  if (urls) {
    if (Array.isArray(urls)) {
      urls.forEach((url: string, index: number) => {
        // 从 fileNames 中获取对应的文件名
        const fileNameArray = fileNames ? fileNames.split(',') : [];
        let fileName = fileNameArray[index] || '';
        
        // 如果没有获取到文件名，从URL中提取
        if (!fileName) {
          fileName = url.split('/').pop()?.split('?')[0] || '';
        }
        
        newData.push({
          url: url.includes('http') ? url : `/common/upload/${url}`,
          name: fileName
        });
      });
    } else if (typeof urls === 'string') {
      // 处理字符串形式的URL
      const urlArray = urls.split(',');
      const fileNameArray = fileNames ? fileNames.split(',') : [];
      
      urlArray.forEach((url: string, index: number) => {
        let fileName = fileNameArray[index] || '';
        
        // 如果没有获取到文件名，从URL中提取
        if (!fileName) {
          fileName = url.split('/').pop()?.split('?')[0] || '';
        }
        
        newData.push({
          url: url.includes('http') ? url : `/common/upload/${url}`,
          name: fileName
        });
      });
    }
  }
  
  return newData;
};

// 确认交接
const handleConfirmHandover = async () => {
  try {
    confirming.value = true;
    await requestClient.put(`/gasHandoverMain/main/process/${handoverDetail.value.id}`);
    ElMessage.success('确认交接成功');
    // 重新获取交接详情，更新状态
    await getHandoverDetail();
  } catch (error) {
    ElMessage.error('确认交接失败');
    console.error('确认交接失败:', error);
  } finally {
    confirming.value = false;
  }
};

// 初始化
onMounted(() => {
  getHandoverDetail();
});
</script>

<template>
  <div class="handover-process-container">
    <div class="flex items-center gap-4 jiayi_header">
      <div style="width: 4px; height: 12px; background-color: #215acd"></div>
      <span class="text-lg font-bold text-gray-800" style="font-size: 14px; font-weight: 600">
        站长交接详情
      </span>
    </div>
    
    <!-- 基本信息 -->
    <ElDescriptions :column="4" class="task-info">
      <ElDescriptionsItem label="片区">{{ handoverDetail?.areaIdName }}</ElDescriptionsItem>
      <ElDescriptionsItem label="油站">{{ handoverDetail?.stationName }}</ElDescriptionsItem>
      <ElDescriptionsItem label="移交人">{{ handoverDetail?.transferPersonName }}</ElDescriptionsItem>
      <ElDescriptionsItem label="接收人">{{ handoverDetail?.receiver || '未指定' }}</ElDescriptionsItem>
      <ElDescriptionsItem label="监交人">{{ handoverDetail?.supervisorName }}</ElDescriptionsItem>
      <ElDescriptionsItem label="交接开始时间">{{ handoverDetail?.handoverStartTime }}</ElDescriptionsItem>
      <ElDescriptionsItem label="交接完成时间">
        {{ handoverDetail?.handoverEndTime || '未完成' }}
      </ElDescriptionsItem>
    </ElDescriptions>

    <!-- 交接项列表 -->
    <div v-if="handoverDetail?.gasHandoverItemsList && handoverDetail.gasHandoverItemsList.length > 0">
      <div v-for="item in handoverDetail.gasHandoverItemsList" :key="item.id">
        <div class="flex items-center gap-4">
          <div style="width: 4px; height: 12px; background-color: #215acd"></div>
          <span class="text-lg font-bold text-gray-800" style="font-size: 14px; font-weight: 600">
            {{ item.linkName }}({{ item.isMandatory === 1 ? '必做' : '可选' }})
          </span>
        </div>
        
        <ElDescriptions :column="4" class="task-info">
          <ElDescriptionsItem label="交接事项">{{ item.handoverItem }}</ElDescriptionsItem>
          <ElDescriptionsItem label="建议时长">{{ item.suggestDuration }} 天</ElDescriptionsItem>
          <ElDescriptionsItem label="负责人">{{ item.principal || '未指定' }}</ElDescriptionsItem>
          <ElDescriptionsItem label="要求/指引" :span="4">{{ item.requirementGuide }}</ElDescriptionsItem>
        </ElDescriptions>
        
        <div class="task-info">
          <!-- 文本内容 -->
          <div v-if="item.hasTextBox === 1" class="form-item">
            <label>文本内容:</label>
            <ElInput
              type="textarea"
              v-model="item.textContent"
              placeholder="请输入文本内容"
              :rows="4"
              class="w-full"
            />
          </div>

          <!-- 照片 -->
          <div v-if="item.hasPhoto === 1" class="form-item">
            <label>照片:</label>
            <div class="photo-upload">
              <ElUpload
                action="#"
                accept=".jpg,.jpeg,.png"
                list-type="picture-card"
                :auto-upload="true"
                :http-request="(options) => handleUpload(options, item, 'photos')"
                :on-remove="(file, fileList) => handleRemove(file, fileList, item, 'photos')"
                :on-preview="handlePreview"
                :file-list="generateFileList(item,'photos')"
              >
                <div v-if="handoverDetail && !handoverDetail.handoverEndTime">
                  <ElIcon class="el-upload__icon">
                    <Plus size="30" />
                  </ElIcon>
                </div>
              </ElUpload>
            </div>
          </div>

          <!-- 附件 -->
          <div v-if="item.hasAttachment === 1" class="form-item">
            <label>附件:</label>
            <div class="attachment-upload">
              <ElUpload
                action="#"
                list-type="text"
                :auto-upload="true"
                :http-request="(options) => handleUpload(options, item, 'attachments')"
                :on-remove="(file, fileList) => handleRemove(file, fileList, item, 'attachments')"
                :on-preview="handlePreview"
                :file-list="generateFileList(item ,'attachments')"
              >
                <ElButton type="primary" v-if="handoverDetail && !handoverDetail.handoverEndTime">
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  上传附件
                </ElButton>
              </ElUpload>
            </div>
          </div>
        </div>
        
        <!-- 保存按钮 -->
        <div class="item-actions" style="margin-right: 20px;" v-if="handoverDetail && !handoverDetail.handoverEndTime">
          <ElButton type="primary" @click="saveItem(item)" :loading="saving">
            保存
          </ElButton>
        </div>
      </div>
    </div>

    <div v-else-if="!loading" class="no-data">
      暂无交接事项
    </div>
    
    <!-- 确认交接按钮 -->
    <div v-if="handoverDetail && !handoverDetail.handoverEndTime" class="confirm-handover-btn">
      <ElButton type="primary" size="large" @click="handleConfirmHandover" :loading="confirming">
        确认交接
      </ElButton>
    </div>
    
    <!-- 图片预览组件 -->
    <ElImageViewer
      v-if="previewVisible"
      :url-list="[previewUrl]"
      @close="() => previewVisible = false"
    />
  </div>
</template>

<style scoped lang="scss">
.jiayi_header {
  padding-top: 18px !important;
  padding-bottom: 4px !important;
  padding-left: 0px !important;
  border-bottom: none !important;
}

// 去掉描述列表的边框
:deep(.el-descriptions) {
  border: none !important;
}

// 去掉描述列表项的边框
:deep(.el-descriptions__cell) {
  border: none !important;
}

.task-info {
  padding: 0px 15px 15px 15px;
  
  :deep(.el-descriptions__label) {
    font-size: 14px;
    font-weight: 400;
    color: var(--text-color-secondary);
  }

  :deep(.el-descriptions__content) {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-color-primary);
  }
  
  :deep(.el-descriptions__table) {
    background: transparent !important;
  }
}

.handover-process-container {
  background: #ffffff;
  margin: 15px;
}

.form-item {
  margin-top: 20px;
  margin-bottom: 20px;
  
  label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
  }
}

.photo-upload,
.attachment-upload {
  margin-top: 8px;
}

.item-actions {
  margin-top: 20px;
  margin-bottom: 20px;
  text-align: right;
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.confirm-handover-btn {
  margin-top: 40px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  text-align: center;
}
</style>
