<template>
  <el-dialog
    :title="isEditMode ? '编辑服务日志' : '新增服务日志'"
    :visible.sync="visible"
    width="70%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="dataForm"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      label-position="right"
    >
      <!-- 服务前图片 -->
      <el-form-item label="服务前图片">
        <el-upload
          ref="beforeUpload"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :file-list="beforeImageList"
          :on-success="(res, file, fileList) => handleUploadSuccess(res, file, fileList, 'before')"
          :on-error="handleUploadError"
          :on-remove="(file, fileList) => handleRemove(file, fileList, 'before')"
          :before-upload="beforeUpload"
          list-type="picture-card"
          :limit="9"
          accept="image/*"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <div class="upload-tip">最多上传9张图片，单张图片不超过10MB</div>
      </el-form-item>

      <!-- 服务后图片 -->
      <el-form-item label="服务后图片">
        <el-upload
          ref="afterUpload"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :file-list="afterImageList"
          :on-success="(res, file, fileList) => handleUploadSuccess(res, file, fileList, 'after')"
          :on-error="handleUploadError"
          :on-remove="(file, fileList) => handleRemove(file, fileList, 'after')"
          :before-upload="beforeUpload"
          list-type="picture-card"
          :limit="9"
          accept="image/*"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <div class="upload-tip">最多上传9张图片，单张图片不超过10MB</div>
      </el-form-item>

      <!-- 反馈备注 -->
      <el-form-item label="反馈备注" prop="remark">
        <el-input
          v-model="dataForm.remark"
          type="textarea"
          :rows="4"
          placeholder="请输入反馈备注"
          :maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 科技部备注 -->
      <el-form-item label="科技部备注">
        <el-input
          v-model="dataForm.kjbRemark"
          type="textarea"
          :rows="4"
          placeholder="请输入科技部备注"
          :maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="dataFormSubmit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ServiceLogFormDialog',
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      visible: false,
      isEditMode: false,
      submitting: false,
      consumeId: null,
      logId: null,
      dataForm: {
        remark: '',
        kjbRemark: ''
      },
      dataRule: {
        remark: [
          { required: true, message: '反馈备注不能为空', trigger: 'blur' }
        ]
      },
      beforeImageList: [],
      afterImageList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/file/Uploader/annexpic',
      uploadHeaders: {
        'Authorization': this.$store.getters.token
      }
    }
  },
  methods: {
    init(consumeId, logId = null) {
      this.consumeId = consumeId
      this.logId = logId
      this.isEditMode = !!logId
      this.visible = true
      this.resetForm()
      
      if (this.isEditMode) {
        this.loadServiceLogDetail()
      }
    },
    
    resetForm() {
      this.dataForm = {
        remark: '',
        kjbRemark: ''
      }
      this.beforeImageList = []
      this.afterImageList = []
      this.$nextTick(() => {
        if (this.$refs.dataForm) {
          this.$refs.dataForm.clearValidate()
        }
      })
    },
    
    async loadServiceLogDetail() {
      if (!this.logId) return
      
      try {
        const res = await request({
          url: `/api/Extend/lqxhfeedback/GetInfo/${this.logId}`,
          method: 'GET'
        })
        
        if (res.code === 200 && res.data) {
          const log = res.data
          this.dataForm.remark = log.remark || ''
          this.dataForm.kjbRemark = log.kjbRemark || ''
          
          // 加载图片数据
          this.beforeImageList = this.parseImageJson(log.beforeImage)
          this.afterImageList = this.parseImageJson(log.afterImage)
        } else {
          this.$message.error(res.msg || '加载服务日志详情失败')
        }
      } catch (error) {
        console.error('加载服务日志详情失败:', error)
        this.$message.error('加载服务日志详情失败')
      }
    },
    
    parseImageJson(imageStr) {
      if (!imageStr) return []
      try {
        const images = JSON.parse(imageStr)
        return images.map(img => {
          let url = img.url || ''
          const name = img.name || img.fileId || ''
          // 如果 URL 不是完整路径，需要添加 baseUrl
          if (url && !url.startsWith('http')) {
            url = this.baseUrl + url
          }
          return {
            name: name,
            url: url,
            response: {
              code: 200,
              data: {
                url: img.url || '', // 保存原始 URL（相对路径）
                name: name
              }
            }
          }
        })
      } catch (error) {
        console.error('解析图片数据失败:', error)
        return []
      }
    },
    
    beforeUpload(file) {
      const isImage = file.type.indexOf('image') !== -1
      const isLt10M = file.size / 1024 / 1024 < 10
      
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return false
      }
      return true
    },
    
    handleUploadSuccess(response, file, fileList, type) {
      if (response && response.code === 200 && response.data) {
        // Element UI 会自动更新 fileList，但需要确保 response 格式正确
        if (!file.response) {
          file.response = response
        }
        // 确保 url 正确设置（保存相对路径，用于提交）
        if (response.data && response.data.url) {
          // 保存原始相对路径到 response.data.url
          // file.url 用于显示，会自动添加 baseUrl
          file.url = this.baseUrl + response.data.url
        }
        // 更新对应列表
        if (type === 'before') {
          this.beforeImageList = fileList
        } else {
          this.afterImageList = fileList
        }
      } else {
        this.$message.error((response && response.msg) || '图片上传失败')
        // 移除失败的文件
        const targetList = type === 'before' ? this.beforeImageList : this.afterImageList
        const index = targetList.findIndex(item => item.uid === file.uid)
        if (index !== -1) {
          targetList.splice(index, 1)
        }
      }
    },
    
    handleUploadError(err, file, fileList) {
      console.error('上传失败:', err)
      this.$message.error('图片上传失败，请重试')
    },
    
    handleRemove(file, fileList, type) {
      // 同步更新对应的文件列表
      if (type === 'before') {
        this.beforeImageList = fileList
      } else {
        this.afterImageList = fileList
      }
    },
    
    dataFormSubmit() {
      this.$refs.dataForm.validate((valid) => {
        if (!valid) {
          return false
        }
        
        // 检查是否有图片正在上传
        const uploadingBefore = this.beforeImageList.some(file => file.status === 'uploading')
        const uploadingAfter = this.afterImageList.some(file => file.status === 'uploading')
        
        if (uploadingBefore || uploadingAfter) {
          this.$message.warning('请等待图片上传完成')
          return false
        }
        
        this.submitServiceLog()
      })
    },
    
    async submitServiceLog() {
      try {
        this.submitting = true
        
        // 准备图片数据
        const beforeImages = this.beforeImageList
          .filter(file => {
            // 过滤掉上传失败的文件和正在上传的文件
            if (file.status === 'fail' || file.status === 'uploading') {
              return false
            }
            // 只要有 response 或 url，就认为是有效的
            return file.response || file.url
          })
          .map(file => {
            // 优先使用 response.data，其次使用 file 本身的属性
            const data = (file.response && file.response.data) || {}
            let url = data.url || file.url || ''
            const name = data.name || file.name || ''
            // 如果 URL 是完整路径，需要转换为相对路径
            if (url && url.startsWith(this.baseUrl)) {
              url = url.replace(this.baseUrl, '')
            }
            // 如果 url 为空，跳过这个文件
            if (!url) {
              return null
            }
            return {
              name: name || 'image',
              url: url,
              fileId: name || 'image'
            }
          })
          .filter(item => item !== null) // 过滤掉 null 项
        
        const afterImages = this.afterImageList
          .filter(file => {
            // 过滤掉上传失败的文件和正在上传的文件
            if (file.status === 'fail' || file.status === 'uploading') {
              return false
            }
            // 只要有 response 或 url，就认为是有效的
            return file.response || file.url
          })
          .map(file => {
            // 优先使用 response.data，其次使用 file 本身的属性
            const data = (file.response && file.response.data) || {}
            let url = data.url || file.url || ''
            const name = data.name || file.name || ''
            // 如果 URL 是完整路径，需要转换为相对路径
            if (url && url.startsWith(this.baseUrl)) {
              url = url.replace(this.baseUrl, '')
            }
            // 如果 url 为空，跳过这个文件
            if (!url) {
              return null
            }
            return {
              name: name || 'image',
              url: url,
              fileId: name || 'image'
            }
          })
          .filter(item => item !== null) // 过滤掉 null 项
        
        // 准备提交数据
        const submitData = {
          consumeId: this.consumeId,
          beforeImage: JSON.stringify(beforeImages),
          afterImage: JSON.stringify(afterImages),
          remark: this.dataForm.remark,
          kjbRemark: this.dataForm.kjbRemark
        }
        
        let result
        if (this.isEditMode && this.logId) {
          // 编辑模式：调用更新接口
          result = await request({
            url: '/api/Extend/lqxhfeedback/Update',
            method: 'PUT',
            data: {
              ...submitData,
              id: this.logId
            }
          })
        } else {
          // 新增模式：调用创建接口
          result = await request({
            url: '/api/Extend/lqxhfeedback/Create',
            method: 'POST',
            data: submitData
          })
        }
        
        if (result.code === 200) {
          this.$message.success(this.isEditMode ? '服务日志更新成功！' : '服务日志提交成功！')
          this.$emit('refresh')
          this.handleClose()
        } else {
          this.$message.error(result.msg || (this.isEditMode ? '更新失败！' : '提交失败！'))
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('网络错误，请稍后重试')
      } finally {
        this.submitting = false
      }
    },
    
    handleClose() {
      this.visible = false
      this.resetForm()
      this.consumeId = null
      this.logId = null
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}

::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
</style>

