<template>
  <view>
    <next-tree
        uiMode="page"
        ref="nextTreeRef"
        checkStrictly
        funcMode="checkbox"
        selectParent
        :ifSearch="false"
        :treeData="treeData"
        themeColor="#2a56f7"
        @change="change"
        page-height="92vh"
    >
      <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 || []).map(item => {
        item.checked = selectIds.indexOf(item.id) !== -1;
        if (item.children && item.children.length) {
          this.echoDefault(item.children, selectIds);
        }
      });
    },
    listTransTree(json, idStr, pidStr, childrenStr) {
      var r = [],
        hash = {},
        id = idStr,
        pid = pidStr,
        children = childrenStr,
        i = 0,
        j = 0,
        len = json.length;
      for (; i < len; i++) {
        hash[json[i][id]] = json[i];
      }
      for (; j < len; j++) {
        var aVal = json[j],
          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,
          });
        }
      }
      this.getOpenerEventChannel().emit("inspectionStandardsAdd", {
        checkList,
        checkListAll: this.currentCheckList,
      });
      // uni.navigateBack()
    },
  },
}
</script>

<style scoped lang="scss">

</style>
