<template>
  <div class="workorder-add-container">
    <el-row :gutter="20" type="flex">
      <!-- 左侧表单 -->
      <el-col style="flex:1;">
        <el-card>
          <el-form :model="form" :rules="rules" 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"
                        :disable-branch-nodes="true"
                        placeholder="请选择工单分类"
                        @select="handleCategorySelect"
                    />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- 处理运维商 -->
                <el-form-item label="处理运维商" prop="techOperatorId">
                  <el-select 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 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 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 :options="quillOptions" v-model="form.requirement" 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"
                :on-exceed="handleExceed"
                multiple
                :limit="uploadConfig.limit"
                list-type="text"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip" style="color: red;">
                  支持多文件上传，单个文件不超过{{ uploadConfig.fileSize }}MB，最多上传{{ uploadConfig.limit }}个文件，支持{{ uploadConfig.fileType.join(',') }}格式
                </div>
              </el-upload>
            </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"
                :on-exceed="handleExceed"
                multiple
                :limit="5"
                list-type="text"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip" style="color: red;">支持多文件上传，单个文件不超过30MB，最多上传5个文件，支持doc,docx,pdf,xls,xlsx,jpg,jpeg,png,gif,zip,rar,7z格式</div>
              </el-upload>
            </el-form-item>-->
            <!-- 资料备注 -->
             <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="资料备注" prop="uploadinfo">
                  <el-input type="textarea" v-model="form.uploadinfo" :rows="4" placeholder="请输入资料备注" style="width: 100%;" />
              </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="warning" @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.query.type != 'add' && getApproveList.length > 0">
        <el-card>
          <div class="approve-title">工单流转记录</div>
          <el-timeline>
            <el-timeline-item
              v-for="(item, idx) in approveList"
              :key="idx"
              :timestamp="item.time"
              :color="item.status === '通过' ? 'green' : 'red'"
            >
              <div>{{ item.user }}：{{ item.status }}</div>
              <div>审核意见：{{ item.comment }}</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 * as UserApi from "@/api/system/user";
import { getFileForConfigPage } from '@/api/server/fileforconfig'; // 引入文件配置API
export default {
  components: { quillEditor,TreeSelect },
  data() {
    return {
      rules: {
      categoryId: [
        { required: true, message: '请选择工单分类', trigger: 'change' }
      ],
      techOperatorId: [
        { required: true, message: '请选择处理运维商', trigger: 'change' }
      ],
      userId: [
        { required: true, message: '请选择部门用户', trigger: 'change' }
      ],
      expectedCompletionDate: [
        { required: true, message: '请选择期望完成时间', trigger: 'change' }
      ],
      requirement: [
        { required: true, message: '请输入需求描述', trigger: 'blur' }
      ]
    },
      form: {
        categoryId: null,
        techOperatorId: null,
        userId: null,
        expectedCompletionDate: '',
        requirement: '',
        requiredInfo: '',
        requiredInfoFj: []
      },
      categoryTree: [],
      operatorList: [],
      userList: [],
      approveList: [
        { user: '张三', status: '通过', time: '2024-05-01 10:00', comment: '同意' },
        { user: '李四', status: '驳回', time: '2024-05-02 11:00', comment: '资料不全' }
      ],
      categoryTreeList: [],
      requirement:'',
      uploadInfo:'',
      deptId:undefined,
      // 文件上传配置
      uploadConfig: {
        fileSize: 30, // 默认值，单位MB
        fileType: ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'jpg', 'jpeg', 'png', 'gif', 'zip', 'rar', '7z'], // 默认文件类型
        limit: 5 // 默认限制数量
      },
      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: {
    /** 获取文件上传配置 */
    async fetchUploadConfig() {
      try {
        // 通过分页接口获取所有配置，然后根据配置键筛选
        const params = {
          pageNo: 1,
          pageSize: 100 // 获取足够多的配置
        };
        const res = await getFileForConfigPage(params);
        const configs = res.data.list;
        // 根据配置键 'Workorder' 查找配置
        const config = configs.find(item => item.configKey === 'WorkorderInfosCheck');
        if (config) {
          // 直接使用配置对象的属性
          this.uploadConfig = {
            fileSize: config.fileMaxSize || 30,
            fileType: config.fileTypes ? config.fileTypes.split(',') : ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'jpg', 'jpeg', 'png', 'gif', 'zip', 'rar', '7z'],
            limit: config.fileMaxCount || 5
          };
          console.log('文件上传配置加载成功:', this.uploadConfig);
        } else {
          console.warn('未找到工单文件上传配置，使用默认配置');
        }
      } catch (error) {
        console.error('获取文件上传配置失败', error);
        // 使用默认配置
      }
    },
    handleRemove(file, fileList) {
      this.form.requiredInfoFj = fileList;
    },
    handleSuccess(response, file, fileList) {
      this.form.requiredInfoFj = fileList;
    },
    beforeUpload(file) {
      // 获取文件扩展名
      const fileExtension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase();
      const extensionWithoutDot = fileExtension.substring(1); // 去掉点号

      // 检查文件类型
      if (!this.uploadConfig.fileType.includes(extensionWithoutDot)) {
        this.$message.error(`只能上传 ${this.uploadConfig.fileType.join(',')} 格式的文件!`);
        return false;
      }

      // 检查文件大小
      const isLtMaxSize = file.size / 1024 / 1024 < this.uploadConfig.fileSize;
      if (!isLtMaxSize) {
        this.$message.error(`上传文件大小不能超过 ${this.uploadConfig.fileSize}MB!`);
        return false;
      }

      // 检查文件数量
      if (this.form.requiredInfoFj.length >= this.uploadConfig.limit) {
        this.$message.error(`最多只能上传${this.uploadConfig.limit}个文件!`);
        return false;
      }
      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);
    },
    handleExceed(files, fileList) {
      this.$message.error(`最多只能上传${this.uploadConfig.limit}个文件!`);
    },
/*    beforeUpload(file) {
      // 定义允许的文件类型
      const allowedExtensions = ['.doc', '.docx', '.pdf', '.xls', '.xlsx', '.jpg', '.jpeg', '.png', '.gif', '.zip', '.rar', '.7z'];
      const fileExtension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase();

      // 检查文件类型
      if (!allowedExtensions.includes(fileExtension)) {
        this.$message.error('只能上传 Word、Excel、PDF、图片(JPG/PNG/GIF)、ZIP、RAR 格式的文件!');
        return false;
      }

      // 检查文件大小
      const isLt30M = file.size / 1024 / 1024 < 30;
      if (!isLt30M) {
        this.$message.error('上传文件大小不能超过 30MB!');
        return false;
      }

      // 检查文件数量
      if (this.form.requiredInfoFj.length >= 5) {
        this.$message.error('最多只能上传5个文件!');
        return false;
      }
      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);
    },
    handleExceed(files, fileList) {
      this.$message.error('最多只能上传5个文件!');
    },*/
    async submitForm(type) {
      if(type !== 'cancel'){
        try {
              // 校验表单
    await this.$refs.formRef.validate();
          // 先上传所有文件
          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';
          }
          // 资料备注
          this.form.requiredInfo = this.form.uploadinfo;
          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;
    },
      /** 转换工单类型数据结构 */
        normalizer(node) {
          if (node.children && !node.children.length) {
            delete node.children;
          }
              return {
                id: node.id,
                label: node.name,
                children: node.children
              };
        },
        handleCategorySelect(node){
          this.form.requirement = node.requirement
          this.uploadInfo = node.uploadInfo
          this.getOperatorList(node);
        },
        //获取所属用户
        async getUserList() {
          const res = await WorkorderInfosApi.getWorkorderUserList();
          this.userList = res.data;
        },
        //获取处理运维商
        async getOperatorList(node) {
          const res = await WorkorderTypeApi.suplierListWorkorder(node.suplier);
          this.operatorList = res.data;
          // 获取当前用户角色信息
          const userInfo = this.$store.state.user;
          const roles = userInfo.roles
          if(node.processType == 3 && this.deptId != 115 && !roles.includes("super_admin")) {
            this.operatorList = this.operatorList.filter(item => item.id == 115);
          }
          if(node.processType == 2 && this.deptId != 115 && !roles.includes("super_admin")) {
            this.operatorList = this.operatorList.filter(item => item.id == this.deptId);
          }
        },
        //获取工单详情
        async getWorkorderInfo() {
          const res = await WorkorderInfosApi.getWorkorderInfos(this.$route.query.id);
          this.form = res.data;
          this.form.requiredInfoFj = res.data.requiredInfo;
          this.form.uploadinfo = res.data.uploadinfo;
          // 格式化时间戳
          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.requiredInfoFj && Array.isArray(res.data.requiredInfoFj)) {
            this.form.requiredInfoFj = res.data.requiredInfoFj.map(requiredInfoFj => ({
              name: requiredInfoFj.name,
              url: requiredInfoFj.url,
              status: 'success',
              size: requiredInfoFj.size,
              type: requiredInfoFj.type,
              id: requiredInfoFj.id
            }));
          }
          //获取运维商
          const findRecursive = (items) => {
            for (const item of items) {
              if (item.id === this.form.categoryId) return item;
              if (item.children && item.children.length) {
                const found = findRecursive(item.children);
                if (found) return found;
              }
            }
            return null;
          };
          this.getOperatorList(findRecursive(this.categoryTree));
        },
        //查询审批记录
        async getApproveList() {
          const res = await WorkorderInfosApi.getApproveList(this.$route.query.id);
          this.approveList = res.data;
        },
        //获取当前用户部门
        async getUserDept() {
          const userInfo = await UserApi.getUser(this.$store.getters.userId);
          this.deptId = userInfo.data.deptId;
        }
  },
  async created() {
    await this.fetchUploadConfig(); // 获取文件上传配置
    this.getCategoryList();
    this.getUserList();
    // this.getOperatorList();
    if(this.$route.query.id != null){
      this.getWorkorderInfo();
    }
    if(this.$route.query.id != undefined){
      this.getApproveList();
    }
    this.getUserDept();
  }
}
</script>

<style scoped>
.workorder-add-container {
  padding: 20px;
}
.approve-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
}
</style>
