
<template>
  <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" class="publicPageTree">
    <div class="publicPageTree_add">
      <PublicPageHeader class="publicPageTree_add_title" page-title="服务列表">
        <el-button size="small" @click="append" type="primary">新增</el-button>
      </PublicPageHeader>
    </div>
    <div class="publicPageTree_search">
      <el-input size="small" placeholder="输入关键字进行过滤" clearable v-model="filterText"></el-input>
    </div>
    <div class="publicPageTree_tree">
      <el-scrollbar style="height: 100%" :horizontal="false">
        <el-tree class="filter-tree" :data="data" :props="defaultProps" node-key="serviceid" :default-expanded-keys="defaultKeys" :filter-node-method="filterNode" ref="tree" @node-click="treeNodeClick">
          <span class="custom-tree-node" slot-scope="{node,data}">
            <span class="custom-tree-node-label">{{node.label}}</span>
            <span class="custom-tree-node-btn">
              <el-button size="mini" type="text" @click.stop="() => edit(data)">编辑</el-button>
              <el-button size="mini" class="del" type="text" @click.stop="() => remove(node, data)">删除</el-button>
            </span>
          </span>
        </el-tree>
      </el-scrollbar>
    </div>
    <div class="publicPageTree_dialog">
      <PublicPageDialog :dialog-title="tableTitle" dialogSize="630px" :dialog-drawer="flag" @handleClose="submitClickClose('ruleForm')" @handleSubmit="submitClickHandler">
        <PublicPageForm ref="ruleForm" :label-width="labelWidth" :form-item="formItem" :form-data="tableForm" />
      </PublicPageDialog>
    </div>
  </div>
</template>

<script>
import PublicPageHeader from '@/components/PublicPageHeader'
import PublicPageDialog from '@/components/PublicPageDialog'
import PublicPageForm from '@/components/publicPageForm'
import { listToTree } from '@/utils/validate'
import { mapGetters } from 'vuex'
import { formatChange } from '@/utils/validate'
import { Query, newData, modifyData, moveData } from "@/api/webApi"

export default {
  name: 'PublicPageTree',
  components: { PublicPageDialog, PublicPageForm, PublicPageHeader },
  data () {
    return {
      loading: false,
      filterText: '',
      data: [],
      defaultProps: {
        children: 'children',
        label: 'servicename'
      },
      pageServiceId: '',
      tableKey: null,//表格主键
      defaultKeys: [],
      formItem: [], //弹框表单渲染数据
      flag: false, //弹框表单开关
      tableType: "add", //弹框表单弹框类型
      tableTitle: "新增", //弹框表单标题
      tableForm: {}, //弹框表单数据
      rmFlag: false, //删除弹框开关
      rmTitle: '', //删除弹框标题
      tableObj: {}, //删除数据
      tableOptions: {}, //表单数据下拉
      labelWidth: '120px', //表单文字距离
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
    ...mapGetters(['authArrs']),
  },
  mounted () {
    //获取页面配置
    const { auth_id } = this.$route.meta
    //获取页面权限类型组件  pagetype 1模块  2页面  3按钮 4表格 5树形  6弹窗
    const pageAuths = this.authArrs
    if (!pageAuths.length) return
    //获取当前页面权限类型
    const pageAuthArrs = pageAuths.filter(item => item['superiorid'] == auth_id)
    if (!pageAuthArrs.length) return
    //获取tree权限
    const pageAuthtrees = pageAuthArrs.filter(item => item.pagetype == 'tree')
    if (!pageAuthtrees.length) return
    //获取form权限
    const pageAuthfroms = pageAuthArrs.filter(item => item.pagetype == 'form')
    if (!pageAuthfroms.length) return

    const { pageconfigurationid } = pageAuthfroms[0]
    const { pagename, serviceid } = pageAuthtrees[0]
    const tableColumnArrs = pageAuths.filter(item => item['superiorid'] == pageconfigurationid && item['pagetype'] == 'column')
    this.formItem = tableColumnArrs.filter(item => item.isdisplay == 1)
    this.pageServiceId = serviceid
    this.getColumnData(tableColumnArrs)
    this.queryTreeData(serviceid, pagename)
  },
  methods: {
    filterNode (value, data) {
      if (!value) return true;
      return data.servicename.indexOf(value) !== -1;
    },

    treeNodeClick (data) {
      console.log(data)
    },

    append () {
      this.flag = true;
      this.tableType = "add";
      this.tableTitle = "新增-服务";
      this.tableForm = {};
      // this.formItem = tableColumnArrs.filter(item => item.isdisplay == 1)
    },

    edit (data) {
      this.flag = true;
      this.tableType = "edit";
      this.tableTitle = "编辑";
      this.tableForm = _.cloneDeep(data);
    },

    remove (node, data) {
      console.log(data)
    },

    restData () {
      this.flag = false;
      this.rmFlag = false;
      this.tableObj = {};
      this.tableForm = {};
      this.queryTreeData(this.pageServiceId)
    },

    //获取表头数据
    getColumnData (columnArrs = []) {
      const returnData = [...columnArrs]
      const columncode = returnData.find(
        (item) => item.isprimarykey == 1
      );
      if (columncode && Object.keys(columncode).length) {
        this.tableKey = columncode['pagecode']
      }
    },

    // 新增/编辑-取消
    submitClickClose (formName) {
      this.flag = false
      this.$refs[formName].restForm()
    },

    // 新增/编辑-确认
    submitClickHandler () {
      const flag = this.$refs["ruleForm"].submitClickHandler()
      if (flag) this.tableType == "add" ? this.generalDataReception(1, this.tableForm) : this.generalDataReception(2, this.tableForm, this.tableKey)
    },

    //表格-增/删/改
    async generalDataReception (event, data, key) {
      try {
        const params = {
          serviceid: this.pageServiceId,
          datacontent: formatChange(data, event, key),
          event: `${event}`,
        };
        const { code } =
          event == 1
            ? await newData(params)
            : event == 2
              ? await modifyData(params)
              : await moveData(params);
        if (code == 0) {
          this.$message.success("操作成功");
          this.restData()
        } else {
          this.$message.error("操作失败");
          this.restData();
        }
      } catch (error) {
        this.restData()
      }
    },

    async queryTreeData (serviceid, pagename = '') {
      this.loading = true;
      const datacontent = { filter: { 1: 1 } }
      try {
        const { code, returnData } = await Query({
          serviceid,
          datacontent,
          event: '0'
        });
        if (code == 0 && returnData?.length) {
          // const name = '全部'
          // const treeMenu = listToTree(returnData, 'superiorid', 'pageconfigurationid')
          // const treeMenuAll = [{ pagename: name, serviceid: name, superiorid: name, pageconfigurationid: -1, children: treeMenu }]
          // this.defaultKeys = [-1]
          // this.data = treeMenuAll
          this.data = returnData
        } else {
          this.$message.error(`获取${pagename}数据失败`);
        }
      } catch (error) {
        this.$message.error(`获取${pagename}数据失败`);
      }
      this.loading = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.publicPageTree {
  background-color: #fff;
  padding: 20px;
  height: 100%;
  width: 100%;
  &_add {
    margin-bottom: 20px;
    line-height: 32px;
    &_title {
      font-size: 16px;
      font-weight: 600;
    }
  }
  ::v-deep &_tree {
    margin-top: 20px;
    height: calc(100% - 114px);
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
    .is-horizontal {
      display: none;
    }
    .custom-tree-node {
      display: flex;
      width: 100%;
      justify-content: space-between;
      line-height: 28px;
      .del {
        color: #ff0000;
      }
    }
  }
}
</style>