<template>
  <div class="ele-body">
    <el-card shadow="never">
      <ele-split-layout
        width="300px"
        allow-collapse
        :right-style="{ overflow: 'hidden' }"
      >
        <div class="ele-border-lighter sys-organization-list">
          <el-tree
            :data="treeList"
            :props="defaultProps"
            ref="treeRef"
            :default-expanded-keys="current && current.id ? [current.id] : []"
            :highlight-current="true"
            node-key="id"
            @node-click="handleNodeClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              {{( isCode == 1 ? data.code : '' )+ ' ' + data.name }}
            </span>
          </el-tree>
        </div>

        <template v-slot:content>
          <div class="ele-border-lighter form-content" v-loading="loading">
            <div class="form-wrapper">
              <el-form size="mini" label-width="100px" class="ele-form-detail">
                <el-row :gutter="15" v-if="current.parentId == 0">
                  <el-col v-bind="styleResponsive ? { sm: 6 } : { span: 6 }">
                    <el-form-item label="类型编码:">
                      <div class="ele-text-secondary">
                        {{ current.code }}
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col v-bind="styleResponsive ? { sm: 6 } : { span: 6 }">
                    <el-form-item label="类型名称:">
                      <div class="ele-text-secondary">
                        {{ current.name }}
                      </div>
                    </el-form-item>
                  </el-col>

                  <el-col v-bind="styleResponsive ? { sm: 8 } : { span: 8 }">
                    <el-form-item label="描述:">
                      <div class="ele-text-secondary">
                        {{ current.remark }}
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col v-bind="styleResponsive ? { sm: 4 } : { span: 4 }">
                    <el-form-item label="状态:">
                      <div class="ele-text-secondary">
                        {{
                          current.isEnabled == 0
                            ? '停用'
                            : current.isEnabled == 1
                            ? '启用'
                            : ''
                        }}
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="15" v-else>
                  <el-col v-bind="styleResponsive ? { sm: 6 } : { span: 6 }">
                    <el-form-item label="节点编码:">
                      <div class="ele-text-secondary">
                        {{ currentData.categoryLevelPathCode }}
                      </div>
                    </el-form-item>
                  </el-col>

                  <el-col v-bind="styleResponsive ? { sm: 6 } : { span: 6 }">
                    <el-form-item label="节点名称:">
                      <div class="ele-text-secondary">
                        {{ current.name }}
                      </div>
                    </el-form-item>
                  </el-col>

                  <el-col v-bind="styleResponsive ? { sm: 8 } : { span: 8 }">
                    <el-form-item label="层级全览:">
                      <div class="ele-text-secondary">
                        {{ currentData.categoryLevelPath }}
                      </div>
                    </el-form-item>
                  </el-col>

                  <el-col v-bind="styleResponsive ? { sm: 4 } : { span: 4 }">
                    <el-form-item label="状态:">
                      <div class="ele-text-secondary">
                        {{
                          current.isEnabled == 0
                            ? '停用'
                            : current.isEnabled == 1
                            ? '启用'
                            : ''
                        }}
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>

            <IndexSearch ref="searchRef" @search="reload" />

            <!-- //产品 -->
            <IndexData
              ref="listData"
              v-if="current"
              :current-id="current.id"
              :data="current"
              :rootTreeId="rootTreeId"
              :currentData="currentData"
              :rootId="rootId"
              :oneProduct="true"
              cacheKeyUrl="57ac3878-product-oneProduct"
              lyType="cp"
            >
            </IndexData>
          </div>
        </template>
      </ele-split-layout>
    </el-card>
  </div>
</template>
<script>
  import IndexData from './components/index-data.vue';
  import IndexSearch from './components/index-search.vue';

  import dictMixins from '@/mixins/dictMixins';
  import { getTreeByPid } from '@/api/classifyManage';

  import { getInfoById } from '@/api/classifyManage';

  import { deepClone } from '@/utils';
  import { parameterGetByCode } from '@/api/system/dictionary/index.js';

  export default {
    name: 'oneProductIndex',

    components: {
      IndexData,
      IndexSearch
    },
    mixins: [dictMixins],
    data() {
      return {
        loading: false,
        current: {},
        isCode:0,
        curNode: {},
        currentData: {},
        treeList: [],
        treeLoading: false,
        formData: {},
        rootTreeId: null,
        where: {},
        defaultProps: {
          children: 'children',
          label: 'name'
        }
      };
    },
    activated() {
      // this.getTreeData();
      this.$nextTick(() => {
        this.$refs.listData.reloadNew(this.where);
      });
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      },

      rootId() {
        return this.$route.query.id;
      },

      fullName() {
        let str = '';
        let codeStr = '';
        let node = this.curNode;
        while (node?.data?.name) {
          str = node.data.name + '-' + str;
          codeStr = node.data.code + '-' + codeStr;
          node = node?.parent;
        }

        return str.substring(str, str.length - 1);
      }
    },
    created() {
      this.getTreeData();
            //是否显示code
      parameterGetByCode({
        code: 'mian_product_code'
      }).then((res) => {
        if (res.value) {
          this.isCode = res.value;
        }
      });
    },
    methods: {
      async getTreeData() {
        try {
          this.treeLoading = true;

          const res = await getTreeByPid(9);
          this.treeLoading = false;
          if (res?.code === '0') {
            this.treeList = res.data;

            if (!this.$route.query.categoryLevelId) {
              this.$nextTick(() => {
                //默认高亮第一级树节点;
                if (this.treeList[0]) {
                  this.rootTreeId = this.treeList[0].id;
                  this.getDetail(this.treeList[0].id);
                  console.log(this.treeList[0].id, 'rootTreeId');
                  this.publicfun(this.treeList[0]);
                }
              });
            } else {
              this.getDetail(this.$route.query.categoryLevelId);
              this.$nextTick(() => {
                this.$refs.treeRef.setCurrentKey(
                  this.$route.query.categoryLevelId
                );
              });
              const objByid = this.findNodeById(
                this.treeList,
                this.$route.query.categoryLevelId
              );
              console.log(objByid, '当前选择的产品');
              this.publicfun(objByid);
            }
            return this.treeList;
          }
        } catch (error) {}
        this.treeLoading = false;
      },

      async getDetail(id) {
        this.loading = true;
        const res = await getInfoById(id);
        this.loading = false;
        if (res.code == '0') {
          this.current = res.data;
          this.$nextTick(() => {
            this.$refs.treeRef.setCurrentKey(this.current.id);
          });
        }
      },

      findNodeById(tree, targetId) {
        function traverse(nodes) {
          for (let node of nodes) {
            if (node.id === targetId) {
              return node;
            } else if (node.children && node.children.length > 0) {
              const foundNode = traverse(node.children);
              if (foundNode) {
                return foundNode;
              }
            }
          }
          return null;
        }

        return traverse(tree);
      },
      handleNodeClick(data, node) {
        this.$route.query.categoryLevelId = '';

        if (this.$refs.searchRef) {
          this.$refs.searchRef.resetAllSearch();
        }

        this.curNode = node;
        this.publicfun(data);

        this.getDetail(data.id);
      },

      publicfun(data) {
        this.pathList = this.findParent([], data, this.treeList);
        this.rootTreeId = null;
        if (this.pathList.length == 0) {
          this.rootTreeId = data.id;
        } else {
          this.rootTreeId =
            this.pathList[this.pathList.length - 1] &&
            this.pathList[this.pathList.length - 1].id;
        }

        let ruleCode = null;
        if (this.pathList.length == 0) {
          ruleCode = data.ruleCode;
        } else {
          ruleCode =
            this.pathList[this.pathList.length - 1] &&
            this.pathList[this.pathList.length - 1].ruleCode;
        }

        this.pathList.unshift(data);
        const PathInfo = {
          categoryLevelPath: '',
          categoryLevelPathId: [],
          categoryLevelPathCode: '',
          categoryLevelId: '',
          categoryLevelName: '',
          ruleCode: ''
        };
        const pathName = [];
        const pathCode = [];
        this.pathList.map((item) => {
          pathName.unshift(item.name);
          pathCode.unshift(item.code);
          PathInfo.categoryLevelPathId.unshift(item.id);
          // PathInfo.rootCategoryLevelId = item.rootCategoryLevelId;
        });
        PathInfo.categoryLevelPath = pathName.join('-');
        PathInfo.categoryLevelPathId = PathInfo.categoryLevelPathId.join(',');
        PathInfo.categoryLevelId = data.id;
        PathInfo.categoryLevelName = data.name;
        PathInfo.ruleCode = ruleCode;
        PathInfo.categoryLevelPathCode = pathCode.join('-');
        this.currentData = deepClone(PathInfo);
        console.log(this.currentData, '选中的产品分类');
      },

      /* 刷新表格 */
      reload(where) {
        this.where = where;
        this.$refs.listData.reload(where);
      },

      // parents:用于返回的数组，childNode:要查询的节点，treeList：json树形数据
      findParent(parents, childNode, treeList) {
        for (let i = 0; i < treeList.length; i++) {
          // 父节点查询条件
          if (treeList[i].id === childNode.parentId) {
            // 如果找到结果,保存当前节点
            parents.push(treeList[i]);
            // 用当前节点再去原数据查找当前节点的父节点
            this.findParent(parents, treeList[i], this.treeList);
            break;
          } else {
            if (treeList[i].children instanceof Array) {
              //	没找到，遍历该节点的子节点
              this.findParent(parents, childNode, treeList[i].children);
            }
          }
        }
        return parents;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .sys-organization-list {
    height: calc(100vh - 165px);
      x-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    overflow: auto;
  }

  .sys-organization-list :deep(.el-tree-node__content) {
    height: 30px;

    & > .el-tree-node__expand-icon {
      margin-left: 10px;
    }
  }

  .form-content {
    height: 50px;
    border: 1px solid;
    box-sizing: border-box;
  }

  .form-wrapper {
    padding: 12px 24px;
  }
</style>
