<template>
  <div>
    <modal :show.sync="modelShow" v-ref:modal backdrop="false">
      <header slot="modal-header" class="modal-header">
        <h4 class="modal-title">附件查看与审核</h4>
      </header>
      <article slot="modal-body" class="modal-body" style="min-height: 30vh;">
        <tab-button-manage v-ref:tabs>
          <!-- 附件查看 Tab -->
          <tabs-manage header="附件查看">
            <div v-if="loading" class="loading-container">
              <div class="loading-spinner"></div>
              <p>加载中...</p>
            </div>
            <div v-if="!loading && error" class="error-container">
              <p>{{ error }}</p>
            </div>
            <div v-if="!loading && !error && (!attachments || attachments.length === 0)" class="no-data-container">
              <p>暂无附件</p>
            </div>
            <div v-if="!loading && !error && attachments && attachments.length > 0" class="attachments-list">
              <div class="showList col-sm-12" style="padding: 10px;margin-top: 10px">
                <div class="col-sm-6" style="padding:10px 10px 0px 10px;height: auto;box-sizing: border-box"
                     v-for="attachment in attachments" :key="attachment.id">
                  <div class="showData">
                    <div class="left">
                      <img v-if="isImageFile(attachment)" :src="attachment.f_downloadpath || '#'" />
                      <div v-else class="file-icon">
                        <i class="glyphicon" :class="getFileIconClass(attachment)"></i>
                      </div>
                    </div>
                    <div class="right">
                      <ul class="buttonList top">
                        <li v-if="['jpg','jpeg','png','gif','bmp'].includes(attachment.f_filetype.toLowerCase())">
                            <a target="_blank" :href="attachment.f_downloadpath">预览</a>
                        </li>
                        <li>
                          <a href="javascript:void(0)" @click="downloadAttachment(attachment)">下载</a>
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </tabs-manage>
          
          <!-- 审核留言 Tab -->
          <tabs-manage header="审核留言">
            <div class="review-comments-container">
              <!-- 历史留言展示 -->
              <div class="comments-history">
                <div v-if="reviewComments.length === 0" style="text-align: center; color: #999; padding: 20px;">
                  暂无留言记录
                </div>
                <div v-else>
                  <div v-for="comment in reviewComments" :key="comment.id" 
                       class="comment-item" 
                       style="margin-bottom: 15px; padding: 12px; background-color: white; border-left: 4px solid #5CB95C; border-radius: 3px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                      <span style="font-weight: bold; color: #333;">{{comment.f_operator}}</span>
                      <span style="color: #666; font-size: 12px;">{{comment.f_audit_date}}</span>
                    </div>
                    <div style="color: #555; line-height: 1.5;">{{comment.f_comments}}</div>
                  </div>
                </div>
              </div>
              
              <!-- 新增留言输入区域 - 固定在底部 -->
              <div class="new-comment-section">
                <div>
                  <!-- <label style="margin-bottom: 5px; font-weight: bold; color: #333;">留言内容：</label> -->
                  <textarea v-model="newComment.content" 
                            placeholder="请输入审核意见..." 
                            class="comment-textarea"
                            maxlength="200"></textarea>
                  <div style="text-align: right; font-size: 12px; color: #999; margin-top: 5px;">
                    {{newComment.content.length}}/200
                  </div>
                </div>
                <div style="text-align: right;">
                  <button class="button_search button_spacing" @click="submitComment" :disabled="!newComment.content.trim()">提交留言</button>
                </div>
              </div>
            </div>
          </tabs-manage>
        </tab-button-manage>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button class="button_clear button_spacing" @click="close">关闭</button>
      </footer>
    </modal>
  </div>
</template>

<script>
import { HttpResetClass } from 'vue-client'
import TabButtonManage from "../common/TabButton"
import TabsManage from "../common/Tabs"

export default {
  components: {
    TabButtonManage,
    TabsManage
  },
  props: {
    businessId: {
      type: [String, Number],
      required: true
    },
    tableName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      modelShow: true,
      show:[0],
      loading: true,
      error: null,
      attachments: [],
      reviewComments: [],
      newComment: {
        content: null,
        status: null
      },
      reviewStatusOptions: [
        {label: '通过', value: '通过'}, 
        {label: '拒绝', value: '拒绝'}, 
        {label: '待审', value: '待审'}
      ]
    }
  },
  created() {
    this.fetchAttachments()
    this.loadReviewComments()
  },
  methods: {
    fetchAttachments() {
      this.loading = true
      this.error = null
      
      try {
        if(!this.businessId || !this.tableName){
          this.error = '业务ID和表名不能为空'
          this.loading = false
          return
        }
        const HttpReset = new HttpResetClass()
        HttpReset.load('POST', 'rs/sql/singleTable_OrderBy', {
          data: {
            items: 'id,F_DOWNLOADPATH,f_filename,f_filetype',
            condition: `F_TABLE_NAME='${this.tableName}' and F_BUSINESSID = '${this.businessId}'`,
            tablename: 't_files',
            orderitem: 'id'
          }
        },{rejectMsg:null,resolveMsg:null}).then((response) => {
          this.attachments = response.data || []
          // 处理文件路径，确保完整URL
          this.attachments.forEach(item => {
            if (item.f_downloadpath && !item.f_downloadpath.startsWith('http')) {
              let temp = item.f_downloadpath
              let URL = temp.substring(temp.lastIndexOf(":\\") + 2)
              // 将反斜杠替换为正斜杠
              URL = URL.replace(/\\/g, '/')
              item.f_downloadpath = "http://" + location.host + "/" + URL
            } else {
              item.f_downloadpath = item.f_downloadpath
            }
          })
          this.loading = false
        }).catch((error) => {
          this.error = '获取附件失败：' + (error.message || '未知错误')
          this.loading = false
        })
        
      } catch (error) {
        this.error = '获取附件失败：' + (error.message || '未知错误')
        this.loading = false
      }
    },
    previewAttachment(attachment) {
      // 根据附件类型处理预览
      alert('预览附件：' + attachment.fileName)
    },
    downloadAttachment(attachment) {
      this.$downFileR(attachment.f_downloadpath,attachment.f_filename,true)
    },
    close() {
      this.modelShow = false
      this.$emit('close')
    },
    isImageFile(file) {
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      const fileExt = file.f_filetype.toLowerCase();
      return imageExtensions.indexOf(fileExt) !== -1;
    },
    getFileIconClass(file) {
      const fileType = file.f_filetype.toLowerCase();
      
      if (fileType === 'pdf') {
        return 'glyphicon-file text-danger';
      } else if (['doc', 'docx'].indexOf(fileType) !== -1) {
        return 'glyphicon-file text-primary';
      } else if (['xls', 'xlsx'].indexOf(fileType) !== -1) {
        return 'glyphicon-file text-success';
      } else {
        return 'glyphicon-file';
      }
    },
    // 加载历史留言（模拟数据）
    loadReviewComments() {
      // 这里先使用模拟数据，实际项目中应该调用后端API
      const HttpReset = new HttpResetClass()
        HttpReset.load('POST', 'rs/sql/singleTable_OrderBy', {
          data: {
            items: 'id,f_audit_date,f_operator,f_comments',
            condition: `f_business_table='${this.tableName}' and f_businessid = '${this.businessId}'`,
            tablename: 't_audit',
            orderitem: 'f_audit_date desc'
          }
        },{rejectMsg:null,resolveMsg:null}).then((response) => {
          this.reviewComments = response.data || []
        })
    },
    clearNewComment() {
      this.newComment = {
        content: null,
        status: null
      };
    },
    async submitComment() {
      if (!this.newComment.content.trim()) {
        this.$showAlert('请输入留言内容', 'warning', 3000)
        return;
      }
      
      try {
        const HttpReset = new HttpResetClass()
        HttpReset.load('POST', 'rs/logic/runSQL', {
          sql: `insert into t_audit (id,f_business_table,f_businessid,f_comments,f_operator,f_operatorid, f_depname, f_depid, f_orgid, f_orgname) values (SEQ_AUDIT_ID.nextval,'${this.tableName}','${this.businessId}','${this.newComment.content}','${this.$login.f.name}','${this.$login.f.id}','${this.$login.f.deps}','${this.$login.f.depids}','${this.$login.f.orgid}','${this.$login.f.orgs}')`
        }, {resolveMsg: null, rejectMsg: null})
        
        this.reviewComments.unshift({
          id: Date.now(),
          f_audit_date: new Date().toLocaleString('zh-CN'),
          f_operator: this.$login.f.name,
          f_comments: this.newComment.content
        });
        
        this.$showAlert('留言提交成功', 'success', 3000)
        this.clearNewComment();
        
      } catch (error) {
        console.error('提交留言失败:', error);
        this.$showAlert('提交留言失败，请重试', 'error', 3000)
      }
    },
  }
}
</script>

<style scoped>
.loading-container, .error-container, .no-data-container {
  text-align: center;
  padding: 30px;
}

.loading-spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.attachments-list {
  width: 100%;
}

.showData {
  height: auto;
  position: relative;
  padding-bottom: 7px;
  border-bottom: solid 1px #c1c1c1;
  font-family: "微软雅黑";
}

.showData .left {
  height: 180px;
  width: 210px;
  background-color: rgb(240, 240, 240);
  overflow: hidden;
  line-height: 180px;
  text-align: center;
}

.showData .left img {
  width: 100%;
  height: auto;
}

.showData .right {
  position: absolute;
  top: 0px;
  left: 220px;
  right: 0px;
  height: 180px;
}

.showData .right .top {
  height: 30px;
  line-height: 30px;
  color: rgb(98, 98, 98);
}

.showData .right ul {
  height: 20px;
  padding: 0px;
  margin: 0px;
  font-size: 0px;
}

.showData .right ul li {
  display: inline-block;
  height: 20px;
  list-style: none;
  font-size: 16px;
  line-height: 20px;
  color: #FFFFFF;
  background-color: #5bb85d;
  padding: 0px 7px;
  margin-right: 10px;
  cursor: pointer;
}

.showData .right ul li:hover {
  background-color: rgb(80, 150, 80);
}

.showData .right ul li:active {
  background-color: rgb(150, 200, 150);
}

.showData .right ul li a {
  width: 100%;
  height: 100%;
  text-decoration: none;
  color: #FFFFFF;
}

.file-icon {
  font-size: 60px;
  color: #999;
}

/* Tab 容器样式 */
.modal-body {
  max-height: 70vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 审核留言样式 */
.review-comments-container {
  font-family: Arial, sans-serif;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 15px;
  max-height: calc(70vh - 120px); /* 减去modal头部和底部的高度 */
}

.comments-history {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
  margin-bottom: 15px;
}

.new-comment-section {
  flex-shrink: 0; /* 防止压缩 */
  border-top: 1px solid #e5e5e5;
  padding-top: 15px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 5px;
  margin-top: auto; /* 推到底部 */
}

.comment-textarea {
  width: 100%;
  height: 80px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 3px;
  resize: vertical;
  font-family: inherit;
}

.comment-textarea:focus {
  border-color: #5CB95C;
  outline: none;
  box-shadow: 0 0 5px rgba(92, 185, 92, 0.3);
}

.comment-item {
  transition: box-shadow 0.2s ease;
}

.comment-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.button_search:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  opacity: 0.6;
}

/* 自定义滚动条样式 */
.comments-history::-webkit-scrollbar {
  width: 6px;
}

.comments-history::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.comments-history::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.comments-history::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style> 