<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" v-dialogDrag append-to-body @open="onDialogOpen" @opened="onDialogOpened">
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="父级栏目" prop="parentId">
              <TreeSelect
                v-model="formData.parentId"
                :options="workorderTypeTree"
                :normalizer="normalizer"
                placeholder="请选择父级栏目"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单类型" prop="name">
              <el-input v-model="formData.name" placeholder="请输入工单类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="流程类型" prop="processType">
              <el-select v-model="formData.processType" placeholder="请选择流程类型">
                <el-option label="策略类工单" :value="1" />
                <el-option label="操作类工单" :value="2" />
                <el-option label="运维商工单" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="运维商" prop="suplier">
              <!-- <el-input v-model="formData.suplier" placeholder="请输入运维商id" /> -->
              <el-checkbox-group v-model="checkList">
                <el-checkbox v-for="item in suplierList" :key="item.id" :label="item.id" name="suplier">
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>

            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="需求描述" prop="requirement">
              <div class="rich-editor-wrapper" v-if="editorVisible">
                <quill-editor v-model="formData.requirement" :options="quillOptions" style="height: 150px;" ref="requirementEditor" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="资料上传提示" prop="uploadInfo">
              <div class="rich-editor-wrapper" v-if="editorVisible">
                <quill-editor v-model="formData.uploadInfo" :options="quillOptions" style="height: 150px;" ref="uploadInfoEditor" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
              <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as WorkorderTypeApi from '@/api/server/WorkorderType';
    import TreeSelect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { quillEditor } from 'vue-quill-editor';
  import 'quill/dist/quill.core.css';
  import 'quill/dist/quill.snow.css';
  import 'quill/dist/quill.bubble.css';
    export default {
    name: "WorkorderTypeForm",
    components: {
                  TreeSelect,
                  quillEditor
            },
    data() {
      return {
        suplierList: [],
        checkList: [],
        // 弹出层标题
        dialogTitle: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
        formLoading: false,
        // 表单参数
        formData: {
                            id: undefined,
                            parentId: undefined,
                            name: undefined,
                            status: undefined,
                            suplier: [],
                            requirement: undefined,
                            uploadInfo: undefined,
                            processType: undefined,
        },
        // 表单校验
        formRules: {
                        name: [{ required: true, message: '工单类型名称不能为空', trigger: 'blur' }],
                        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
                        processType: [{ required: true, message: '流程类型不能为空', trigger: 'blur' }],
        },
                       workorderTypeTree: [], // 树形结构
        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,
        },
        editorVisible: false,
      };
    },
    methods: {
      /** 打开弹窗 */
     async open(id) {
        this.dialogVisible = true;
        this.reset();
        // 修改时，设置数据
        if (id) {
          this.formLoading = true;
          try {
            const res = await WorkorderTypeApi.getWorkorderType(id);
            this.formData = res.data;
            this.title = "修改工单类型";
            this.checkList = this.formData.suplier
            ? this.formData.suplier.split(',').map(id => Number(id))
            : [];
          } finally {
            this.formLoading = false;
          }
        }
        this.title = "新增工单类型";
        await this.getWorkorderTypeTree();
        this.$nextTick(() => {
          if (this.$refs.uploadInfoEditor && this.$refs.uploadInfoEditor.quill) {
            this.$refs.uploadInfoEditor.quill.blur();
          }
          if (this.$refs.requirementEditor && this.$refs.requirementEditor.quill) {
            this.$refs.requirementEditor.quill.blur();
          }
            // 强制滚动到顶部
          const dialogBody = document.querySelector('.el-dialog__body');
          if (dialogBody) {
            dialogBody.scrollTop = 0;
          }
        });
      },
      /** 提交按钮 */
      async submitForm() {
        // 校验主表
        await this.$refs["formRef"].validate();
                  this.formLoading = true;
        try {
          const data = this.formData;
                  // 修改的提交
          if (data.id) {
            data.suplier = this.checkList.join(',');
            await WorkorderTypeApi.updateWorkorderType(data);
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.$emit('success');
            return;
          }
          // 添加的提交
          data.suplier = this.checkList.join(',');
          await WorkorderTypeApi.createWorkorderType(data);
          this.$modal.msgSuccess("新增成功");
          this.dialogVisible = false;
          this.$emit('success');
        } finally {
          this.formLoading = false;
        }
      },
                  /** 获得工单类型树 */
         async getWorkorderTypeTree() {
            this.workorderTypeTree = [];
            const res = await WorkorderTypeApi.getWorkorderTypeList();
            const root = { id: 0, name: '顶级工单类型', children: [] };
            root.children = this.handleTree(res.data, 'id', 'parentId')
            this.workorderTypeTree.push(root)
          },
                  /** 转换工单类型数据结构 */
          normalizer(node) {
            if (node.children && !node.children.length) {
              delete node.children;
            }
                return {
                  id: node.id,
                  label: node.name,
                  children: node.children
                };
          },
      /** 表单重置 */
      reset() {
        this.formData = {
                            id: undefined,
                            parentId: undefined,
                            name: undefined,
                            status: undefined,
                            suplier: undefined,
                            requirement: undefined,
                            uploadInfo: undefined,
                            processType: undefined,
        };
        this.resetForm("formRef");
        this.checkList = [];
      },
      //查询运维商
      async getSuplierList() {
        const res = await WorkorderTypeApi.suplierList();
        this.suplierList = res.data;
      },
      onDialogOpen() {
        this.editorVisible = false;
      },
      onDialogOpened() {
        this.editorVisible = true;
        this.$nextTick(() => {
          if (this.$refs.requirementEditor && this.$refs.requirementEditor.quill) {
            this.$refs.requirementEditor.quill.blur();
          }
          if (this.$refs.uploadInfoEditor && this.$refs.uploadInfoEditor.quill) {
            this.$refs.uploadInfoEditor.quill.blur();
          }
        });
      },
    },
    created() {
      this.getSuplierList();
    }
  };
</script>

<style scoped>
 .rich-editor-wrapper {
height: 250px;
}/*
.rich-editor-wrapper .ql-toolbar {
  border-radius: 4px 4px 0 0;
}
.rich-editor-wrapper .ql-container {
  min-height: 120px;
  border-radius: 0 0 4px 4px;
} */
</style>
