<template>
  <view>
    <next-tree
      ref="nextTreeRef"
      ui-mode="page"
      check-strictly
      func-mode="checkbox"
      select-parent
      :if-search="false"
      :tree-data="treeData"
      theme-color="#2a56f7"
      page-height="92vh"
      @change="change"
    >
      <template #fixedBottomBar>
        <view style="padding: 20upx; margin-bottom: 20upx">
          <u-button type="primary" text="保存" @click="fnSubmit" />
        </view>
      </template>
    </next-tree>
  </view>
</template>

<script>
import { getInspectionStandards } from "@/api";

export default {
  data() {
    return {
      treeData: [],
      checkList: [],
      currentCheckList: [],
    };
  },
  mounted() {
    this.getOpenerEventChannel().on("inspectionStandardsEdit", (event) => {
      this.checkList = event;
      this.getData();
    });
  },
  methods: {
    async getData() {
      const resData = await getInspectionStandards();
      this.treeData = this.listTransTree(resData.list, "id", "pid", "children");
      this.echoDefault(this.treeData, this.checkList);
    },
    echoDefault(treeData, selectIds) {
      (treeData || []).forEach((item) => {
        item.checked = selectIds.indexOf(item.id) !== -1;
        if (item.children && item.children.length) {
          this.echoDefault(item.children, selectIds);
        }
      });
    },
    listTransTree(json, idStr, pidStr, childrenStr) {
      const r = [];
      const hash = {};
      const id = idStr;
      const pid = pidStr;
      const children = childrenStr;
      let i = 0;
      let j = 0;
      const len = json.length;
      for (; i < len; i++) {
        hash[json[i][id]] = json[i];
      }
      for (; j < len; j++) {
        const aVal = json[j];
        const hashVP = hash[aVal[pid]];
        if (hashVP) {
          !hashVP[children] && (hashVP[children] = []);
          hashVP[children].push(aVal);
        } else {
          r.push(aVal);
        }
      }
      return r;
    },
    change(event) {
      this.currentCheckList = event;
    },
    fnSubmit() {
      const checkList = [];
      for (let i = 0; i < this.currentCheckList.length; i++) {
        if (!this.currentCheckList[i].children) {
          checkList.push({
            CONTENT_ID: this.currentCheckList[i].id,
            // CONTENT_ID: uni.$u.guid(),
            SUPERVISE_INSPECT_STANDARD_ITEM_ID: this.currentCheckList[i].id,
            INSPECT_CONTENT: this.currentCheckList[i].label,
            INSPECT_CONTENT_SOURCE: 1,
            INSPECT_STATE: "",
            DISPOSE: this.currentCheckList[i].DISPOSE,
            HIDDENDESCR: this.currentCheckList[i].HIDDENDESCR,
          });
        }
      }
      this.getOpenerEventChannel().emit("inspectionStandardsAdd", {
        checkList,
        checkListAll: this.currentCheckList,
      });
      // uni.navigateBack()
    },
  },
};
</script>

<style scoped lang="scss"></style>
