<template>
  <div class="workorder-add-container">
    <el-row :gutter="20" type="flex">
      <!-- 左侧表单 -->
      <el-col style="flex: 1">
        <el-card>
          <el-form :model="form" ref="formRef" label-width="110px">
            <el-row :gutter="20">
              <el-col :span="12">
                <!-- 工单分类（下拉树形） -->
                <el-form-item label="工单分类" prop="categoryId">
                  <TreeSelect
                    v-model="form.categoryId"
                    :options="categoryTree"
                    :normalizer="normalizer"
                    placeholder="请选择工单分类"
                    @select="handleCategorySelect"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- 处理运维商 -->
                <el-form-item label="处理运维商" prop="techOperatorId">
                  <el-select
                    disabled
                    v-model="form.techOperatorId"
                    placeholder="请选择运维商"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in operatorList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <!-- 所属用户 -->
                <el-form-item label="部门用户" prop="userId">
                  <el-select
                    disabled
                    v-model="form.userId"
                    placeholder="请选择用户"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in userList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- 期望完成时间 -->
                <el-form-item
                  label="期望完成时间"
                  prop="expectedCompletionDate"
                >
                  <el-date-picker
                    disabled
                    value-format="yyyy-MM-dd HH:mm:ss"
                    v-model="form.expectedCompletionDate"
                    type="datetime"
                    placeholder="请选择期望完成时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="需求描述" prop="requirement">
              <quill-editor
                disabled
                v-model="form.requirement"
                :options="quillOptions"
                style="height: 300px; max-width: 770px"
              />
            </el-form-item>
            <!-- 资料上传 -->
            <el-form-item
              label="资料上传"
              prop="requiredInfoFj"
              style="margin-top: 90px; max-width: 500px"
            >
              <div style="word-break: break-all" v-html="uploadInfo"></div>
              <el-upload
                action="#"
                :file-list="form.requiredInfoFj"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :http-request="handleUpload"
                multiple
                list-type="text"
                disabled
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">支持多文件上传</div>
                <template v-slot:file="{ file }">
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-file-name">{{
                      file.name
                    }}</span>
                    <el-button
                      type="text"
                      icon="el-icon-download"
                      @click.stop="handleDownload(file)"
                      style="margin-left: 10px"
                    >
                      下载
                    </el-button>
                  </span>
                </template>
              </el-upload>
            </el-form-item>
            <!-- 资料备注 -->
            <el-row :gutter="20" v-if="form.uploadinfo">
              <el-col :span="24">
                <el-form-item label="资料备注" prop="uploadinfo">
                  <el-input
                    disabled
                    type="textarea"
                    v-model="form.uploadinfo"
                    :rows="4"
                    placeholder="请输入资料备注"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>


            <!-- 完成需要增加一个附件 -->
            <el-row :gutter="18" v-if="form.attachment">
              <el-col :span="24">
                <el-form-item label="处理结果附件">
                  <FilePreview v-model="form.attachment"/>
                </el-form-item>
              </el-col>
            </el-row>


            <!-- 实施情况 -->
            <el-row :gutter="18" v-if="form.finishText">
              <el-col :span="24">
                <el-form-item label="实施情况" prop="finishText">
                  <div style="margin-bottom: 10px;max-width: 770px;word-wrap: break-word;overflow-wrap: break-word;white-space: normal;width: 100%;" v-html="form.finishText" class="finish-text-content"></div>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 提交按钮 -->
            <el-form-item style="text-align: center">
              <!-- <el-button type="success" @click="submitForm('saveAndSubmit')">保存并提交</el-button>
              <el-button type="info" @click="submitForm('save')">保存</el-button> -->
              <el-button type="info" @click="submitForm('cancel')"
                >返回</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <!-- 右侧审批记录 -->
      <el-col
        style="width: 350px; max-width: 40vw"
        v-if="this.$route.params.type != 'add'"
      >
        <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 || (idx === approveList.length - 1 && (item.status === '0' || item.status === '70'))
                  ? parseTime(item.createTime)
                  : ''
              "
              :color="
                idx === approveList.length - 1 &&
                (item.status === '70' || item.status === '0')
                  ? '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 && item.status != '60'" class="approve-comment">
                  审核意见：{{ item.reviewComments }}
                </div>
                <!-- <div v-html="item.reviewComments"></div> -->
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
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 * as WorkorderTypeApi from "@/api/server/WorkorderType";
import * as WorkorderInfosApi from "@/api/server/WorkorderInfos";
import TreeSelect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import FilePreview from '@/components/FilePreview';

export default {
  components: { quillEditor, TreeSelect, FilePreview },
  data() {
    return {
      form: {
        categoryId: null,
        techOperatorId: null,
        userId: null,
        expectedCompletionDate: "",
        requirement: "",
        requiredInfoFj: [],
        requiredInfo: "",
        attachment: null,
      },
      categoryTree: [],
      operatorList: [],
      userList: [],
      approveList: [],
      categoryTreeList: [],
      requirement: "",
      uploadInfo: "",
      quillOptions: {
          placeholder: '请输入内容',
          theme: 'snow',
          modules: {
            toolbar: [
              ['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']
            ]
          },
          focus: false,
        },
    };
  },
  methods: {
    statusType(status) {
      if (status === "70") return "success";
      if (status === "10") return "info";
      if (status === "0") return "warning";
      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 === "0") return "已关闭";
      if (status === "60") return "处理中";
      if (["21", "31", "41", "51"].includes(status)) return "通过";
      if (["22", "32", "42", "52"].includes(status)) return "已退回";
      return status;
    },
    handleRemove(file, fileList) {
      this.form.requiredInfoFj = fileList;
    },
    handleSuccess(response, file, fileList) {
      this.form.requiredInfoFj = fileList;
    },
    beforeUpload(file) {
      return true;
    },
    async handleUpload(options) {
      const { file, onSuccess } = options;
      const fileObj = {
        name: file.name,
        url: URL.createObjectURL(file),
        status: "success",
        raw: file, // 保存原始文件对象，用于后续上传
      };
      this.form.requiredInfoFj.push(fileObj);
      onSuccess(fileObj);
    },
    async submitForm(type) {
      if (type !== "cancel") {
        try {
          // 先上传所有文件
          const uploadPromises = this.form.requiredInfoFj
            .filter((file) => file.raw) // 只上传还未上传的文件
            .map(async (file) => {
              try {
                const res = await WorkorderInfosApi.uploadWorkorderFile(
                  file.raw
                );
                console.log("文件上传返回值:", res); // 打印上传返回值
                // 更新文件URL为后端返回的URL
                // file.url = res.data;
                file.id = res.data;
                delete file.raw; // 删除原始文件对象
                return res;
              } catch (error) {
                this.$message.error(
                  `文件 ${file.name} 上传失败：${error.message}`
                );
                throw error;
              }
            });

          await Promise.all(uploadPromises);

          //下单时间
          var date = new Date();
          // 获取本地时间并格式化为 YYYY-MM-DD HH:MM:SS
          const pad = (num) => num.toString().padStart(2, "0");
          date =
            `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
              date.getDate()
            )} ` +
            `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
              date.getSeconds()
            )}`;
          this.form.orderTime = date;
          //工单状态
          this.form.status = "10";
          // 所有文件上传成功后，提交表单
          if (type === "saveAndSubmit") {
            this.form.type = "push";
          }
          if (this.$route.query.type === "edit") {
            const res = await WorkorderInfosApi.updateWorkorderInfos(this.form);
          } else {
            const res = await WorkorderInfosApi.createWorkorderInfos(this.form);
          }
          this.$message.success("工单保存成功");
          this.$router.back();
        } catch (error) {
          this.$message.error("保存失败：" + error.message);
        }
      } else {
        this.$router.back();
      }
    },
    //获取工单分类
    async getCategoryList() {
      this.categoryTree = [];
      const res = await WorkorderTypeApi.getWorkorderTypeList();
      this.categoryTreeList = res.data;
      const tree = this.handleTree(res.data, "id", "parentId");
      this.categoryTree = tree;
      console.log(this.categoryTree);
    },
    /** 转换工单类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    handleCategorySelect(node) {
      this.requirement = node.requirement;
      this.uploadInfo = node.uploadInfo;
    },
    //获取所属用户
    async getUserList() {
      const res = await WorkorderInfosApi.getUserList();
      this.userList = res.data;
    },
    //获取处理运维商
    async getOperatorList() {
      const res = await WorkorderTypeApi.suplierList();
      this.operatorList = res.data;
    },
    //获取工单详情
    async getWorkorderInfo() {
      const res = await WorkorderInfosApi.getWorkorderInfos(
        this.$route.query.id
      );
      this.form = res.data;
      // 格式化时间戳
      const timestamp = res.data.expectedCompletionDate;
      // 创建Date对象
      const date = new Date(timestamp);
      // 格式化
      const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${date
        .getHours()
        .toString()
        .padStart(2, "0")}:${date
        .getMinutes()
        .toString()
        .padStart(2, "0")}:${date.getSeconds().toString().padStart(2, "0")}`;
      this.form.expectedCompletionDate = formattedDate;

      // 处理文件列表
      if (res.data.requiredInfo && Array.isArray(res.data.requiredInfo)) {
        this.form.requiredInfoFj = res.data.requiredInfo.map(
          (requiredInfo) => ({
            name: requiredInfo.name,
            url: requiredInfo.url,
            status: "success",
            size: requiredInfo.size,
            type: requiredInfo.type,
            id: requiredInfo.id,
          })
        );
      }
      WorkorderTypeApi.getWorkorderType(this.form.categoryId).then((res) => {
        this.requirement = res.data.requirement;
        this.uploadInfo = res.data.uploadInfo;
      });
    },
    //查询审批记录
    async getApproveList() {
      const res = await WorkorderInfosApi.getApproveList(this.$route.query.id);
      this.approveList = res.data;
      console.log(this.approveList);
    },
    handleDownload(file) {
      console.log(file);
      if (!file.url && !file.id) {
        this.$message.error("文件下载链接不存在");
        return;
      }

      // 如果是本地预览的文件URL
      if (file.url && file.url.startsWith("blob:")) {
        if (file.raw) {
          const link = document.createElement("a");
          link.href = URL.createObjectURL(file.raw);
          link.download = file.name;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);
        } else {
          this.$message.error("文件未保存，无法下载");
        }
        return;
      }

      // 如果有文件ID，通过后端接口下载
      if (file.id) {
        window.open(file.url, "_blank");
      } else if (file.url) {
        // 如果有直接的URL，使用URL下载
        window.open(file.url, "_blank");
      }
    },
  },
  created() {
    this.getCategoryList();
    this.getUserList();
    this.getOperatorList();
    if (this.$route.query.id != null) {
      this.getWorkorderInfo();
    }
    this.getApproveList();
  },
};
</script>

<style scoped>
.workorder-add-container {
  padding: 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>
