<template>
  <basic-container>
    <avue-crud
      v-bind="bindVal"
      v-on="onEvent"
      v-model="form"
      :page.sync="page"
      @on-load="getList"
    >
      <template slot="menuLeft">
        <!-- <el-button
          v-if="!isSelAnnual"
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          @click="handleDelete"
        >
          删 除
        </el-button> -->
        <el-button
          v-if="!isSelAnnual"
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          @click="handleImport"
        >
          导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          @click="handleExport"
        >
          导出
        </el-button>
        <print-table-btn @click="printTable" />

      </template>
      
      <template slot="body">
        <h3 class="page-title">{{ pageTitle }}</h3>
      </template>
    </avue-crud>

    <upload-excel-dialog ref="uploadExcelDialog" :uploadAfter="uploadAfter"/>

    <WideTablePrinter
      ref="printWideTable"
      :columns="wideTableColumns"
      :data="data"
      :print-title="pageTitle"
      :rows-per-page="30"
      :default-landscape="true"
      :zoom="80"
    />
  </basic-container>
</template>

<script>
import { getList as getSubjectTreeList } from "@/api/basicResource/subjectSetting";
import {exportBlob} from "@/api/common";
import UploadExcelDialog from "@/components/upload-excel-dialog";
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";
import { mapGetters } from "vuex";


export default window.$crudCommon({
  components: {
    UploadExcelDialog,
  },
  data() {
    return {
      treeData: [],

      wideTableColumns: [],
    };
  },
  mounted() {
    this.getMenuData();
  },
  computed: {
    ...mapGetters(['tag']),
    pageTitle() {
      return this.tag.label;
    }
  },
  methods: {
    loopData(data, level) {
      level++;
      return data.map(item => {
        item.level = level;
        item.disabled = level === 4 ? false : true;

        if (item.children && item.children.length) {
          this.loopData(item.children, level);
        }
        
        return item;
      });
    },
    getMenuData() {
      getSubjectTreeList().then(res => {
        this.loading = false;
        if (res.data.code == 200) {

          const column = this.findObject(this.option.column, "subjectId");
          column.dicData = this.loopData(JSON.parse(JSON.stringify(res.data.data)), 0);

          this.treeData = column.dicData;
        }
      })
    },
    handleImport() {
      this.$refs.uploadExcelDialog.open('/api/kd-scientific/subject/enterprise/import');
    },
    uploadAfter() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    handleExport() {
      exportBlob(`/api/kd-scientific/subject/enterprise/export?${this.website.tokenHeader}=${getToken()}`, this.params).then(res => {
        downloadXls(res.data, `${this.pageTitle}.xlsx`);
      });
    },
    /**
     * 打印表格
     * @param isLandscape 是否横向打印
     */
    printTable(isLandscape) {
      this.wideTableColumns = this.printOption.column;
      this.$nextTick(() => {
        this.$refs.printWideTable.printTable(isLandscape);
      })
    },
    findParentNames(categories, childId, parentNames = []) {
      const child = categories.find(cat => cat.id == childId);
      
      if (!child || !child.parentId) {
        return parentNames;
      }
      
      const parent = categories.find(cat => cat.id == child.parentId);
      if (parent) {
        parentNames.unshift(parent.name); // 添加到数组开头保持顺序
        return this.findParentNames(categories, parent.id, parentNames);
      }
      
      return parentNames;
    },
    getFormData() {
      let newList = [];
      const getAllList = data => {
        data.forEach(element => {
          newList.push(element);
          if (element.children && element.children.length) {
            getAllList(element.children)
          }
        });
      }
      getAllList(this.treeData);
      let parentNames = this.findParentNames(newList, this.form.subjectId);
      
      return { ...this.form, subjectName: `${parentNames.join('\\')}\\${this.form.$subjectId}` };
    },
  },
}, {
  // 模块路径
  name: 'basicResource/compSubjectSetting',
  res: ({ data }) => {
    data.records = data.records.map(item => {
      item.rdSubject = item.rdSubjectEnable === 1 ? item.subjectName : '';
      item.adSubject = item.adSubjectEnable === 1 ? item.subjectName : '';
      return item;
    });
    return data;
  },
});
</script>
