<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧工单信息 -->
      <el-col :span="16">
        <el-card>
          <div slot="header" class="clearfix">
            <span>工单审核</span>
          </div>

          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <!-- 基本信息 -->
            <el-divider content-position="left">基本信息</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工单分类">
                  <el-input v-model="form.category" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发起者">
                  <el-input v-model="form.creator" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                <el-form-item label="实施运维商">
                  <el-input v-model="form.techOperator" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门用户">
                  <el-input v-model="form.user" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="发起时间">
                  <el-input :value="parseTime(form.createTime,'{y}-{m}-{d} {h}:{i}:{s}')" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="工单描述">
              <div class="finish-text-content"
                v-html="form.requirement"
                style="
                  padding: 12px;
                  border: 1px solid #ebeef5;
                  border-radius: 4px;
                  background-color: #f5f7fa;
                  color: #606266;
                  line-height: 1.5;
                  white-space: pre-wrap;
                  min-height: 60px;
                "
              ></div>
            </el-form-item>

            <!-- 附件信息 -->
            <el-form-item label="附件列表">
              <div class="attachment-list">
                <div style="word-break: break-all;" v-html="uploadinfo"></div>
                <el-table :data="form.requiredInfoFj" size="small" border style="width: 100%">
                  <el-table-column prop="name" label="文件名称" />
                  <el-table-column prop="size" label="文件大小" width="120">
                    <template slot-scope="scope">
                      {{ formatFileSize(scope.row.size) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="上传时间" width="160">
                    <template slot-scope="scope">
                      {{ parseTime(scope.row.createTime,'{y}-{m}-{d} {h}:{i}:{s}') }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120" align="center">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click="handleDownload(scope.row)"
                      >
                        <i class="el-icon-download"></i> 下载
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form-item>
            <!-- 资料备注 -->
            <el-form-item label="附件备注" v-if="form.requiredInfo">
              <el-input disabled type="textarea" v-model="form.requiredInfo" :rows="4" placeholder="请输入资料备注" style="width: 100%;" />
            </el-form-item>
            <!-- 审核信息 -->
            <el-divider content-position="left">{{form.status == '60' ? '处理信息' : form.status == '41' ? '审核信息' : '核实信息'}}</el-divider>

            <el-form-item v-if="form.status != '60'" :label="form.status == '41' ? '审核意见' : '核实信息'" prop="auditOpinion">
              <el-input type="textarea" v-model="form.auditOpinion" :rows="4" placeholder="请输入" />
            </el-form-item>
            <el-form-item v-if="form.status == '60'" label="完成情况" prop="finishText" style="margin-bottom: 90px;">
              <!-- <el-input type="textarea" v-model="form.auditOpinion" :rows="4" placeholder="请输入完成情况" /> -->
              <quill-editor ref="quillEditor" v-model="form.finishText" :options="quillOptions" style="height: 300px; max-width: 770px;" />
            </el-form-item>

            <!-- 完成需要增加一个附件 -->
            <el-form-item label="处理结果附件" prop="attachment" v-if="form.status === '60'">
              <FileUpload v-model="form.attachment"
                          :file-size="uploadConfig.fileSize"
                          :file-type="uploadConfig.fileType"
                          :limit="uploadConfig.limit"
                          :required="uploadConfig.required"/>
            </el-form-item>

            <el-form-item :label="form.status == '60' ? '处理结果' : form.status == '41' ? '审核结果' : '核实结果'" prop="auditResult">
              <el-radio-group v-model="form.auditResult" @change="handleAuditResultChange">
                <el-radio v-if="form.status === '60'" :label="1">完成工单</el-radio>
                <el-radio v-else :label="1">通过</el-radio>
                <el-radio v-if="form.status !== '60' && rejectOptions.length > 0" :label="2">驳回</el-radio>
              </el-radio-group>
              <!-- 驳回选择 -->
              <el-select
                v-model="form.rejectTo"
                placeholder="请选择驳回对象"
                v-if="form.auditResult === 2"
                style="margin-left: 20px; width: 200px;"
              >
                <el-option
                  v-for="item in rejectOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item class="form-footer">
              <el-button v-if="form.status === '60'" type="primary" @click="handleSubmit">完成工单</el-button>
              <el-button v-else type="primary" @click="handleSubmit">提交审核</el-button>
              <el-button @click="handleCancel">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧审批记录 -->
      <el-col
       :span="8"
      >
        <el-card class="approve-card" style="max-height: 960px;">
          <div class="approve-title">工单流转记录</div>
          <el-timeline v-if="approveList?.length" class="custom-timeline">
            <el-timeline-item
              v-for="(item, idx) in approveList"
              :key="idx"
              :timestamp="
                idx !== approveList.length - 1 || ['70', '0'].includes(item.status)
                  ? parseTime(item.createTime)
                  : ''
              "
              :color="
                idx === approveList.length - 1 && item.status === '70'
                  ? 'green'
                  : idx !== approveList.length - 1
                  ? 'green'
                  : ''
              "
              class="timeline-item"
            >
              <div class="approve-item">
                <div class="approve-item-header">
                  <div class="approve-creator">{{ item.deptName }}</div>
                  <!-- <dict-tag type="trs_workorder_status" :value="item.status" /> -->
                  <el-tag :type="statusType(item.status)" v-if=" item.status!== approveList.length - 1 || ['70', '0'].includes(item.status)
                  ? parseTime(item.createTime)
                  : ''">{{
                    statusText(item.status)
                  }}</el-tag>
                </div>
                <div
                  v-if="item.name"
                  class="approve-comment"
                  style="margin-bottom: 10px"
                >
                  负责人：{{ item.name }}
                </div>
                <div v-if="item.phone" class="approve-comment" style="margin-bottom: 10px;">
                  联系方式：{{ item.phone }}
                </div>
                <div v-if="item.reviewComments" class="approve-comment">
                  审核意见：{{ item.reviewComments }}
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as WorkorderInfosApi from '@/api/server/WorkorderInfos';
import * as WorkorderTypeApi from '@/api/server/WorkorderType';
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import FileUpload from '@/components/FileUpload';
import { getFileForConfigPage } from '@/api/server/fileforconfig'; // 引入文件配置分页API



// 自定义图片处理器
const imageHandler = function() {
  const input = document.createElement('input');
  input.setAttribute('type', 'file');
  input.setAttribute('accept', 'image/*');
  input.click();

  input.onchange = () => {
    const file = input.files[0];
    if (file) {
      // 检查文件大小
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return;
      }

      // 检查文件类型
      const isImage = file.type.indexOf('image/') === 0;
      if (!isImage) {
        this.$message.error('请上传图片文件!');
        return;
      }

      // 将图片转换为base64
      const reader = new FileReader();
      reader.onload = (e) => {
        const base64 = e.target.result;
        // 获取编辑器实例
        const quill = this.$refs.quillEditor.quill;
        // 获取光标位置
        const length = quill.getSelection() ? quill.getSelection().index : 0;
        // 插入图片
        quill.insertEmbed(length, 'image', base64);
        // 光标向后移动一位
        quill.setSelection(length + 1);
      };
      reader.readAsDataURL(file);
    }
  };
};

export default {
  name: 'WorkorderInfosCheck',
  components: { quillEditor,FileUpload },
  data() {
    return {
      form: {
        orderNo: '', // 工单编号
        category: '', // 工单分类
        creator: '', // 发起者
        createTime: '', // 发起时间
        maintainer: '', // 运维商
        status: '', // 工单状态
        description: '', // 工单描述
        auditOpinion: '', // 审核意见
        auditResult: '', // 审核结果
        rejectTo: '', // 驳回对象
        attachment: '',//结果附件
        finishText: '' // 完成情况
      },
      rules: {
        auditOpinion: [
          { required: true, message: '请输入审核意见', trigger: 'blur' }
        ],
        auditResult: [
          { required: true, message: '请选择最终结果', trigger: 'change' }
        ]
      },
      // 文件上传配置
      uploadConfig: {
      fileSize: 15, // 默认值，单位MB
        fileType: ['doc', 'docx', 'wps', 'pdf'], // 默认文件类型
        limit: 1, // 默认限制数量
        required: false // 默认必填
      },
      // 审批记录数据
      approveList: [],
      // 附件列表
      attachments: [],
      // 驳回选项
      rejectOptions: [],
      // 附件信息
      uploadinfo: '',
      // 工单描述
      requirement: '',
      quillOptions: {
        placeholder: '请输入内容',
        theme: 'snow',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'list': 'ordered'}, { 'list': 'bullet' }],
              [{ 'script': 'sub'}, { 'script': 'super' }],
              [{ 'indent': '-1'}, { 'indent': '+1' }],
              [{ 'direction': 'rtl' }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'color': [] }, { 'background': [] }],
              [{ 'font': [] }],
              [{ 'align': [] }],
              ['clean'],
              ['image']
            ],
            handlers: {
              'image': imageHandler.bind(this)
            }
          }
        }
      }
    }
  },
  methods: {
    /** 获取文件上传配置 */
    async fetchUploadConfig() {
      try {
        // 假设通过分页接口获取所有配置，然后根据配置键筛选
        const params = {
          pageNo: 1,
          pageSize: 100 // 获取足够多的配置
        };
        const res = await getFileForConfigPage(params);
        const configs = res.data.list;
        // 假设配置键为 'harmful_info_report_upload'
        const config = configs.find(item => item.configKey === 'WorkorderInfosResult');
        if (config) {
          // 假设配置值是一个JSON字符串，包含fileSize, fileType, limit, required等属性
          this.uploadConfig = {
            fileSize: config.fileMaxSize || 15, // 使用 fileMaxSize
            fileType: config.fileTypes ? config.fileTypes.split(',') : ['doc', 'docx', 'wps', 'pdf'], // 将字符串转换为数组
            limit: config.fileMaxCount || 1, // 使用 fileMaxCount
            required: config.fileOther=='true' || true // 默认true
          };
        }
      } catch (error) {
        console.error('获取文件上传配置失败', error);
        // 使用默认配置
      }
    },

        //查询审批记录
        async getApproveList() {
      const res = await WorkorderInfosApi.getApproveList(this.$route.query.id);
      this.approveList = res.data;
      console.log(this.approveList);
    },
    // 获取工单状态对应的类型
    getStatusType(status) {
      const statusMap = {
        '待审核': 'warning',
        '已通过': 'success',
        '已驳回': 'danger'
      }
      return statusMap[status] || 'info'
    },
    // 格式化文件大小
    formatFileSize(size) {
      if (size < 1024) {
        return size + 'B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + 'KB'
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + 'MB'
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
      }
    },
    // 处理文件下载
    handleDownload(file) {
      // TODO: 实现文件下载逻辑
      this.$message.success(`开始下载文件：${file.name}`)
      window.open(file.url)
    },
    // 处理审核结果变更
    handleAuditResultChange(value) {
      if (value === 1) {
        this.form.rejectTo = ''
      }
    },
    // 提交审核
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }
        if (this.form.auditResult === 2 && !this.form.rejectTo) {
          this.$message.warning('请选择驳回对象')
          return
        }
        WorkorderInfosApi.checkWorkorderInfos(this.form).then(res => {
          this.$message.success('提交成功')
          this.$router.back()
        })
      })
    },
    // 取消
    handleCancel() {
      this.$router.go(-1)
    },
    // 获取工单信息
    async getWorkorderInfo() {
      var res  = await WorkorderInfosApi.getWorkorderInfos(this.$route.query.id)
      this.form = res.data
      this.form.requiredInfoFj = res.data.requiredInfo
      this.form.requiredInfo = res.data.uploadinfo
      WorkorderTypeApi.getWorkorderType(this.form.categoryId).then(res => {
        this.requirement = res.data.requirement;
        this.uploadinfo = res.data.uploadInfo;
      })
    },
    statusType(status) {
      if (status === "70") return "success";
      if (status === "10") return "info";
      if (status === "0") return "danger";
      if (["21", "31", "41", "51","60"].includes(status)) return "success";
      if (["22", "32", "42", "52"].includes(status)) return "danger";
      return "";
    },
    statusText(status) {
      if (status === "70") return "已完成";
      if (status === "10") return "新建";
      if (status === "60") return "处理中";
      if (status === "0") return "已关闭";
      if (["21", "31", "41", "51"].includes(status)) return "通过";
      if (["22", "32", "42", "52"].includes(status)) return "已退回";
      return status;
    },
    async rejectList() {
      const res = await WorkorderInfosApi.rejectList(this.$route.query.id);
      this.rejectOptions = res.data;
      this.form.rejectTo = this.rejectOptions[0].id;
    }
  },
  mounted() {
    // 确保编辑器正确初始化
    this.$nextTick(() => {
      if (this.$refs.quillEditor) {
        const quill = this.$refs.quillEditor.quill;
        // 重新绑定图片处理器
        const toolbar = quill.getModule('toolbar');
        toolbar.addHandler('image', imageHandler.bind(this));
      }
    });
  },
  created() {
    this.getWorkorderInfo()
    this.getApproveList();
    this.rejectList();
    this.fetchUploadConfig();
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.el-divider {
  margin: 24px 0;
}
.el-tag {
  font-size: 14px;
}
.timeline-wrapper {
  padding: 10px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}
.timeline-card {
  margin-bottom: 10px;
}
.timeline-card h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #303133;
}
.timeline-card p {
  margin: 5px 0;
  font-size: 13px;
  color: #606266;
}
.attachment-list {
  margin-top: 10px;
}
.form-footer {
  text-align: center;
  margin-top: 20px;
}
.approve-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
}
.approve-item-header {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center; /* 垂直居中 */
  margin-bottom: 6px; /* 与下方内容间距 */
}
.approve-card {
  overflow-y: auto;
  height: 100%;
  max-height: 960px;
}

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

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

.approve-card::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.approve-card::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.finish-text-content {
  width: 100%;
}
.finish-text-content :deep(img) {
  max-width: 100%;
  height: auto;
  object-fit: contain;
}
</style>
