<template>
<div class="page-body">
  <div class="split_wrapper">
      <div class="left">
        <div class="treepanel" :style="'height:' + tableHeight + 'px'">
          <div class="treepanel-header">
            <a @click.stop="treeAdd(row)" title="新增">
              <a-icon type="plus-circle" />
            </a>
            <a @click.stop="treeEdit(row)" title="编辑">
              <a-icon type="edit" />
            </a>
            <a @click.stop="treeDelete(row)" title="删除">
              <a-icon type="delete" />
            </a>
          </div>
          <div class="treepanel-content">
            <a-tree :replaceFields="{children:'mes_enum', title:'title', key:'key'}" v-if="!treeLoading" show-line :tree-data="treeData" :default-expand-all="true" :block-node="true"
              @select="onTreeSelect" :default-selected-keys="selectedKeys">
              <a-icon slot="switcherIcon" type="down" />
            </a-tree>
          </div>
        </div>
      </div>
      <div class="right" style="padding:10px">
        <div class="toolbarbtns">
          <a-button type="primary" @click="pageAdd">新增</a-button>
          <a-button type="primary" @click="ok">保存</a-button>
        </div>
        <vxe-table border show-overflow keep-source ref="xTable" :height="tableHeight" :data="detailsData"
          :export-config="{}" :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false }">
          <vxe-column width="80">
            <template #default="{ row }">
              <div class="oplinks">
                <a @click.stop="pageAdd(row)" title="新增">
                  <a-icon type="plus-circle" />
                </a>
                <a @click.stop="pageDelete(row)" title="删除">
                  <a-icon type="delete" />
                </a>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="code" width="220" title="编号" :edit-render="{ name: '$input', props: {} }">

          </vxe-column>
          <vxe-column field="name" width="220" title="名称" :edit-render="{ name: '$input', props: {} }">

          </vxe-column>
        </vxe-table>


      </div>
    </div>





  </div>
</template>

<script>


import BASE_URL from '@/services/mes/api.js';
let childrenFieldName = 'mes_enum';

export default {

  props: {
    pageMode: {
      type: String,
      default: "edit"
    },
    dataId: {
    }

  },

  data() {

    // 页面数据变量
    var pageData = {

      modelName: "",

      actions: {
        treedata: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/list`,
        delete: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/batchDelete`,
        listdata: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/list`,
        save: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/batchHandle`,
      },
      tipTimes: 0,
      detailsData: [
      ],
      sourceDetailsData :[

      ],
      treeData: [],
      treeLoading: true,
      deletedDetailsData: [

      ],
      selectedKeys: [],
      selectedKey: null,
      tableHeight: 500

    };


    return pageData;
  },
  created() {

    this.$nextTick(() => {

      this.tableHeight = this.$mk.getWindowSize().height - this.$mk.getOffsetTop(this.$refs.xTable.$el) - 40;
      this.treeInit();
    });



  },
  // 函数
  methods: {


    treeInit() {
      this.treeLoading = true;
      this.$mk.post({
        url: this.actions.treedata,
        loading: "加载中...",
        data: {
          "page": 1,
          "limit": 10000,
          "end_time": 0,
          "start_time": 0,
          "order_bys": [
          ],
          "search_rules": [
          ]
        }
      }).then(r => {


        let treedata = {
          title: "全部",
          key: "root"
        };
        treedata[childrenFieldName] =  r.data.MesEnum;


        function formatTreedata(d) {
          if (d.id) {
            d.key = d.id.toString();
          } else {
            d.key = "root";
          }
          if (d.name) {
            d.title = d.name;
          }
          if (d[childrenFieldName] && d[childrenFieldName].length) {
            d[childrenFieldName].forEach(item => formatTreedata(item))
          }
        }
        treedata[childrenFieldName].forEach(item => formatTreedata(item))

        this.treeData = [treedata];
        this.treeLoading = false;
      });

    },
    treeAdd() {
      this.$mk.dialog.open({
        page: () => import("./treeEdit"),
        title: "新增-枚举分类",
        dataId: 0,
        callback: ({ success }) => {
          success && this.treeInit();
        }
      })
    },
    treeEdit() {
      if (!this.selectedKey || this.selectedKey == "root") {
        this.$mk.error("请先选择枚举分类");
        return;
      }
      let node = this.findTreeNode(this.selectedKey);
 

      this.$mk.dialog.open({
        page: () => import("./treeEdit"),
        title: "编辑-枚举分类",
        dataId: node.id,
        callback: ({ success }) => {
          success && this.treeInit();
        }
      })
    },
    treeDelete() {
      if (!this.selectedKey || this.selectedKey == "root") {
        this.$mk.error("请先选择枚举分类");
        return;
      }
      let node = this.findTreeNode(this.selectedKey);
      let ids = [
        node.id
      ]; // 定义id数组

      if (!ids.length) {  // 如果没有选中行
        this.$mk.error("请选择行"); // 提示
        return;
      }

      this.$mk.confirm('您确定要删除吗？').then(type => { // 确认删除
        if (type == 'confirm') { // 如果确认删除
          this.$mk.post({
            url: this.actions.delete, // 请求删除数据地址
            loading: "删除中...", // 加载提示
            data: {
              ids: ids // 传递id数组
            },
            useBigInt: true
          }).then(() => { // 成功
            this.$mk.success("删除成功"); // 提示成功
            this.treeInit(); // 重新加载数据
          }).catch((a) => { // 失败
            this.$mk.error(a.data.msg); // 提示错误信息
          });
        }
      });
    },
    getDataId() {

      let dataId = this.dataId;
      if (this.$route.params.id) {
        dataId = this.$route.params.id;
      }

      return dataId;
    },

    onTreeSelect(selectedKeys) {
      if (selectedKeys && selectedKeys[0]) {
        this.selectedKey = selectedKeys[0];
        this.loadData(selectedKeys[0]);
      }
    },
    findTreeNode(key) {
      var find = (items) => {
        for (let i = 0; i < items.length; i++) {
          if (items[i].key == key) {
            return items[i];
          }
          if (items[i][childrenFieldName] && items[i][childrenFieldName].length) {
            var xx = find(items[i][childrenFieldName]);
            if (xx) {
              return xx;
            }
          }
        }
      };
      return find(this.treeData);
    },
    getAllChildrenIds(items) {
      let ids = [];
      let eachItems = (arr) => {
        arr.forEach(item => {

          if (item[childrenFieldName] && item[childrenFieldName].length) {
            eachItems(item[childrenFieldName]);
          } else if (item.model == "v_AA_PartnerClass") {
            ids.push(item.id)
          }

        })
      };
      eachItems(items);
      return ids;
    },
    reloadData() {
      if (this.selectedKey) {
        this.loadData(this.selectedKey);
      }

    },
    loadData(key) {

      let postLoad = (id) => {
        this.$mk.post({
          url: this.actions.listdata,
          loading: "加载中...",
          data: {
            "page": 1,
            "limit": 10000,
            "start_time": 0,
            "end_time": 0,
            "search_rules": [
              {
                column: "enum_id", // 字段名
                mode: "=", // 搜索模式
                value: id.toString()
              }
            ],
            "order_bys": [
            ]
          },
          useBigInt: true
        }).then(a => {
          console.log(a.data.MesEnumValue)
          this.sourceDetailsData = a.data.MesEnumValue || []; 
          let ds = [];
          this.sourceDetailsData.forEach(item=>{
            ds.push({
              id : item.id.toString(),
              code : item.code,
              name : item.name
            })
          });
          this.deletedDetailsData = [];
          this.detailsData = ds;
        });

      }
      if (key && key != "root") {
        var node = this.findTreeNode(key);

        postLoad(node.id);
      }




    },

    findSourceInfo(idStr){
      for(var i =0;i<this.sourceDetailsData.length;i++){
        let o = this.sourceDetailsData[i];
        if(o.id.toString() == idStr){
          return o;
        }
      }
    },
    ok() {

      let save = () => {

        

        if (!this.selectedKey || this.selectedKey == "root") {
          this.$mk.error("请先选择枚举分类");
          return;
        }

        
        this.$refs.xTable.clearEdit();
        
        let node = this.findTreeNode(this.selectedKey);

        let ds = JSON.parse(JSON.stringify(this.detailsData));

        var postdata = {
          insertList: [],
          updateList: [],
          deleteList: this.deletedDetailsData
        };

       ds.forEach(item => {
          delete item._X_ROW_KEY;

          item.enum_id = node.id;
          if (item.id && item.id != "0") {
            let source  = this.findSourceInfo(item.id);
            item.id = source.id;
            postdata.updateList.push(item);
          } else { 
            postdata.insertList.push(item);
          } 
        })
        this.$mk.post({
          url: this.actions.save,
          loading: "保存中...",
          data: postdata,
          useBigInt:true
        }).then(a => {
          if (a.code == "200") {
            this.$mk.success("保存成功");
            this.reloadData();
          } else {
            this.$mk.error(a.message);
          }


        }).catch((a) => {
          this.$mk.error(a.data.msg);
        });
      };

      save();


    },

    back() {
    },

    cancel() {
      this.back();
    },
    pageAdd(row) {

      const $table = this.$refs.xTable
      const record = {
      }
      if (row) {

        this.detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.detailsData.push(record)
      }



    },

    pageDelete(row) {
      const $table = this.$refs.xTable;
      if (row.id) {
        this.deletedDetailsData.push(row.id)
      }
      this.detailsData.splice($table.getRowSeq(row) - 1, 1);

    },

  },
  // 监听属性
  watch: {

  }
};

</script>
<style>
.page-body {
  background: white;
  padding: 8px;
}
 
.toolbarbtns .ant-btn {
  margin-right: 10px;
}

.toolbarbtns {
  margin-bottom: 5px;
}
</style>
