<!--
@ 作者: 秦东
@ 时间: 2023-07-19 08:39:34
@ 备注: 抽屉
-->
<script lang="ts" setup>
import { ref, nextTick, watch, onMounted, onUnmounted } from "vue";
import { aceEdit } from "@/api/DesignForm/utils";
import { treeStruct } from "@/api/DesignForm/type";

const props = withDefaults(
  defineProps<{
    data?: object;
    modelValue: boolean;
    // eslint-disable-next-line vue/require-default-prop
    title?: string;
    direction?: "rtl" | "ltr";
    content: string;
    id?: string;
    // eslint-disable-next-line vue/require-default-prop
    codeType?: string;
  }>(),
  {
    id: "editJson",
    content: "",
    direction: "ltr",
  }
);

const emits = defineEmits<{
  (e: "beforeClose"): void;
  (e: "confirm", content: string): void;
  (e: "confirmTree", content: string): void;
  (e: "update:modelValue", val: boolean): void;
}>();
const editor = ref<any>({});
const visible = ref(false);

// const treeSelectAry = ref<treeStruct[]>(props.data.content ? props.data.content : []); //树形数据
const editTitleFormRef = ref(ElForm); //编辑表单
const editTitleInfoRef = ref(ElForm);
let jibuqi = 0; //计步器计算最大值
const isTopHeader = ref(false); //是否为添加顶级树脂
const guodu = ref<treeStruct>({}); //数据中转使用
const addIsShow = ref(false); //添加数据
const treeSelectTitle = reactive<treeStruct>({
  value: "1",
  label: "",
}); //编辑表格结构及数据
const butLoad = ref(false); //按钮状态
/**
 * 表单验证规则
 */
const editTitleRules = reactive({
  label: [{ required: true, message: "请输入名称", trigger: "blur" }],
});

const treeSelectAry = computed({
  get() {
    return props.data.content ? props.data.content : [];
  },
  set(val: treeStruct[]) {
    // emits("confirmTree", val);
    return val;
  },
});

/**
@ 作者: 秦东
@ 时间: 2024-12-02 11:22:18
@ 功能: 递归查数
*/
const jiShuDiGui = (val: []) => {
  if (!Array.isArray(val)) return (jibuqi = 0);
  val.forEach((item: any) => {
    jibuqi++;
    // console.log("递归查数", jibuqi);
    if (item.children && item.children.length > 0) {
      jiShuDiGui(item.children);
    }
  });
};

watch(
  () => visible,
  (val: booble) => {
    jiShuDiGui(props.data?.content);
  },
  { deep: true }
);

watch(
  () => props.modelValue,
  (val: boolean) => {
    visible.value = val;
    if (val) {
      initEditor();
    }
  }
);
const initEditor = () => {
  nextTick(() => {
    editor.value = aceEdit(props.content, props.id, props.codeType);
  });
};
const dialogConfirm = () => {
  const editVal = editor.value.getValue();
  emits("confirm", editVal);
};
const drawerBeforeClose = () => {
  emits("update:modelValue", false);
  emits("beforeClose");
  treeSelectAry.value = [];
};
onMounted(() => {
  // console.log("预览视图--------------------------------》", props.data);
});
onUnmounted(() => {
  if (Object.keys(editor.value).length !== 0) {
    editor.value.destroy();
    editor.value.container.remove();
  }
});

/**
@ 作者: 秦东
@ 时间: 2024-09-27 16:03:26
@ 功能: 打开添加弹窗
*/
const pickAdd = (val: treeStruct) => {
  guodu.value = val;
  isTopHeader.value = false;
  addIsShow.value = true;
};
/**
@ 作者: 秦东
@ 时间: 2024-09-27 16:06:41
@ 功能: 关闭弹窗
*/
const pickAddClose = () => {
  guodu.value = {};
  treeSelectTitle.label = "";
  addIsShow.value = false;
  butLoad.value = false;
  editTitleFormRef.value.resetFields();
};
/**
@ 作者: 秦东
@ 时间: 2024-09-27 16:09:53
@ 功能: 添加顶级分类
*/
const addTopClass = () => {
  isTopHeader.value = true;
  addIsShow.value = true;
};
/**
@ 作者: 秦东
@ 时间: 2024-09-27 16:10:27
@ 功能: 确定添加分类
*/
const pickIsTrue = () => {
  butLoad.value = true;
  editTitleFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      jibuqi++;
      if (isTopHeader.value) {
        treeSelectAry.value.push({
          value: jibuqi,
          label: treeSelectTitle.label,
          children: [],
        });
      } else {
        if (guodu.value.children) {
          guodu.value.children.push({
            value: jibuqi,
            label: treeSelectTitle.label,
            children: [],
          });
        } else {
          guodu.value.children = [
            {
              value: jibuqi,
              label: treeSelectTitle.label,
              children: [],
            },
          ];
        }
      }

      pickAddClose();
    } else {
      butLoad.value = false;
    }
  });
};
/**
@ 作者: 秦东
@ 时间: 2024-09-27 08:38:35
@ 功能: 回填主表值
*/
const dialogConfirmTree = () => {
  // let drawer = ({
  // 	visible: false,
  // 	type: '',
  // 	title: '',
  // 	codeType: '',
  // 	direction: undefined, //弹出方向rtl / ltr
  // 	callback: ''
  // })
  // let opt = new Array
  // treeSelectAry.forEach((item:treeStruct) => {
  // 	opt.push({
  // 		value: item.value,
  // 		label: item.label,
  // 		children: item.children
  // 	})
  // })

  // emits('confirm', treeSelectAry)
  // console.log("回填主表值", treeSelectAry.value);
  emits("confirmTree", treeSelectAry.value, props.data.type);
  drawerBeforeClose();
};
/**
@ 作者: 秦东
@ 时间: 2024-09-27 13:51:31
@ 功能: 删除指定节点数据
*/
const pickDel = (val: treeStruct) => {
  // console.log("要删除得节点-->", val.value);
  delDiGui(treeSelectAry.value, val);
  // console.log("删除指定节点数据---结果-->", treeSelectAry);
};
/**
@ 作者: 秦东
@ 时间: 2024-09-27 14:13:23
@ 功能: 执行递归删除
*/
const delDiGui = (tree: treeStruct[], val: treeStruct) => {
  // console.log("要删除得节点-11->", tree, val.value);
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.value == val.value) {
      tree.splice(i, 1);

      return;
    }
    if (Array.isArray(node.children) && node.children.length) {
      return delDiGui(node.children, val);
    }
  }
};
const edisIsShow = ref(false);
const butLoadEdit = ref(false);
/**
@ 作者: 秦东
@ 时间: 2024-09-29 13:29:17
@ 功能: 编辑级联舒体
*/
const pickEdis = (val: treeStruct) => {
  guodu.value = val;
  treeSelectTitle.label = val.label;
  edisIsShow.value = true;
};
/**
@ 作者: 秦东
@ 时间: 2024-09-29 13:33:51
@ 功能: 关闭编辑窗体
*/
const pickEditClose = () => {
  guodu.value = {};
  treeSelectTitle.label = "";
  edisIsShow.value = false;
  butLoadEdit.value = false;
  editTitleInfoRef.value.resetFields();
};
/**
@ 作者: 秦东
@ 时间: 2024-09-29 13:36:30
@ 功能: 确定修改
*/
const pickEditIsTrue = () => {
  butLoadEdit.value = true;
  editTitleInfoRef.value.validate((isValid: boolean) => {
    if (isValid) {
      guodu.value.label = treeSelectTitle.label;
      pickEditClose();
    } else {
      butLoad.value = false;
    }
  });
};
</script>
<template>
  <el-drawer
    v-model="visible"
    size="60%"
    :title="title"
    :direction="direction as any"
    class="ace-dialog"
    :append-to-body="true"
    :before-close="drawerBeforeClose"
  >
    <template #header>
      <div v-html="title"></div>
    </template>
    <div v-if="['cascader', 'treeSelect'].includes(props.data.type)">
      <el-table :data="treeSelectAry" row-key="value" default-expand-all>
        <el-table-column prop="label" label="名称" />
        <el-table-column label="操作" width="200" align="center">
          <template #header>
            <el-button type="success" @click="addTopClass">添加顶级分类</el-button>
          </template>
          <template #default="scope">
            <el-button-group>
              <el-button text type="success" @click="pickAdd(scope.row)">添加</el-button>
              <el-button text type="warning" @click="pickEdis(scope.row)">修改</el-button>
              <el-button text type="danger" @click="pickDel(scope.row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-else :id="id"></div>
    <div class="dialog-footer">
      <el-button
        v-if="['cascader', 'treeSelect'].includes(props.data.type)"
        type="primary"
        size="small"
        @click="dialogConfirmTree"
      >
        确定
      </el-button>
      <el-button v-else type="primary" size="small" @click="dialogConfirm">
        确定
      </el-button>
    </div>

    <el-dialog v-model="addIsShow" title="编辑" width="500" :before-close="pickAddClose">
      <el-form
        ref="editTitleFormRef"
        :rules="editTitleRules"
        :model="treeSelectTitle"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="名称：" prop="label">
          <el-input v-model="treeSelectTitle.label" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pickAddClose">取消</el-button>
          <el-button v-loading="butLoad" type="primary" @click="pickIsTrue"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="edisIsShow"
      title="编辑"
      width="500"
      :before-close="pickEditClose"
    >
      <el-form
        ref="editTitleInfoRef"
        :rules="editTitleRules"
        :model="treeSelectTitle"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="名称：" prop="label">
          <el-input v-model="treeSelectTitle.label" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pickEditClose">取消</el-button>
          <el-button v-loading="butLoadEdit" type="primary" @click="pickEditIsTrue"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </el-drawer>
</template>
<style lang="scss" scoped>
#editJson,
#editJsonCopy {
  width: 100%;
  height: calc(100vh - 90px);
}
</style>
