<template>
  <div class="page-view flex-row-sb">
    <app-sync-tree
      ref="appAsyncTree"
      :actions="treeActions"
      :default-data="{ customConfigField: 'custom config field' }"
      :default-expanded-keys="defaultExpandedKeys"
      :expand-all="expandAll"
      :fields="treeFields"
      :props="treeProps"
      :request-method="getTreeNodes"
      title="行政维度"
      @select="onTreeNodeClick"
    >
      <!-- 此form为组件内部form 在actions配置项的method函数当中 可以获取参数 -->
      <template #default="{ form: treeForm }">
        <app-filter-item :rules="[{ required: true, message: '自定义项一不能为空' }]" :span="24" label="自定义项一"
                         prop="customConfigField"
        >
          <el-input v-model="treeForm.customConfigField" placeholder="请输入自定义项一" />
        </app-filter-item>
      </template>
    </app-sync-tree>

    <div class="page-view flex-1 ml-11">
      <app-filter ref="app-filter" :model="filters" class="bg-white px-15 border-radius-5" label-width="90px"
                  @query="onQuery" @reset="onReset"
      >
        <app-filter-item :span="6" el-type="input" label="岗位名称">
          <el-input v-model="filters.jobName" clearable placeholder="请输入"
                    @keyup.enter.native="$refs['app-filter'].query"
          />
        </app-filter-item>
        <app-filter-item :span="6" label="职务名称">
          <!--          <el-input v-model="filters.name" clearable placeholder="请输入"-->
          <!--                    @keyup.enter.native="$refs['app-filter'].query"-->
          <!--          />-->
          <el-select v-model="filters.name" clearable placeholder="请选择单位类型"
                     @keyup.enter.native="$refs['app-filter'].query"
          >
            <el-option v-for="dict in options" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </app-filter-item>
      </app-filter>

      <div class="pa-11 bg-white h-100 flex-col mt-11 border-radius-5">
        <div class="mb-11">
          <el-button icon="el-icon-plus" size="mini" type="primary" @click="addCompany"> 新增</el-button>
          <el-button :disabled="!selectedRows.length > 0" icon="el-icon-delete" size="mini" type="danger"
                     @click="delCompany"
          >删除
          </el-button>
        </div>
        <app-table
          :column="columns"
          :pagination="pagination"
          :table-data="tableData"
          :table-loading="tableLoading"
          :total="total"
          checkbox
          @pagination-change="onPaginationChange"
          @selection-change="handleSelectionChange"
          @row-dblclick="showDetail"
        />
      </div>
      <add-dialog v-model="dialogVisible" :data="currentRow" :title="dialogTitle" @confirm="onConfirm" />
    </div>
  </div>
</template>

<script>
import tableMixin from '@/mixins/table.js';
import AddDialog from './AddDialog.vue'; // 列表mixins
export default {
  name: '',
  components: { AddDialog },
  mixins: [tableMixin],
  data() {
    const TREE_CONFIG = {
      treeProps: {
        value: 'id',
      },
      expandAll: false,
      defaultExpandedKeys: ['0'],
      // 此处fields内配置对象属性包括: label/prop/rules/type(枚举:switch/number/input(默认))/span/
      treeFields: [
        { label: '节点名称', prop: 'label', rules: [{ required: true, message: '节点名称不能为空' }] },
        {
          label: '排序',
          prop: 'sort',
          type: 'number',
          span: 24,
          labelWidth: '100px',
          rules: [{ required: true, message: '排序不能为空' }],
        },
      ],
      curNode: {}, // 当前选择节点
    };
    const TABLE_CONFIG = {
      tableData: [
        {
          jobName: '文书',
          jobCode: 'ws',
          name: '职员',
          tableName: 'a/b/c',
        },
      ],
      // 列表表头
      columns: [
        { label: '岗位名称', prop: 'jobName', align: 'center' },
        { label: '岗位编码', prop: 'jobCode', align: 'center' },
        { label: '职务名称', prop: 'name', align: 'center' },
        { label: '组织路径', prop: 'tableName', align: 'center' },
        {
          dataType: 'option',
          label: '操作',
          width: '150px',
          fixed: 'right',
          operation: [
            {
              name: '详情',
              // icon: 'el-icon-s-operation',
              // showHide: (row) => {},
              clickFun: (row) => {
                this.showDetail(row);
              },
            },
          ],
        },
      ],
    };
    const DIALOG_CONFIG = {
      dialogVisible: false,
      dialogTitle: '新增',
    };

    return {
      ...TREE_CONFIG,
      ...TABLE_CONFIG,
      ...DIALOG_CONFIG,
      options: [{ value: '选项1', label: '职员' }, { value: '选项1', label: '部长' }],
    };
  },
  created() {
    // 本地存储实例
    //   const storedData = localStorage.getItem('tableData');
    //   if (storedData) {
    //     this.tableData = JSON.parse(storedData);
    //   }
  },
  methods: {
    getTreeNodes() {
      return Promise.resolve({
        data: [
          {
            parentId: '0',
            id: '1',
            label: '云财斌集团',
            isDir: 1,
            children: [
              {
                parentId: '1',
                id: '12',
                label: '贵专大数据',
                isDir: 1,
              },
              {
                parentId: '2',
                id: '13',
                label: '财务部',
                isDir: 1,
              },
            ],
          },
        ],
      });
    },
    /**
     * @description: treeActions支持函数也支持数组，由于实际场景当中 可能会动态设置按钮，故以函数示例来展示
     * @param {*} data 当前点击节点数据
     * @return {*} 当前节点展示的操作项数组
     */
    treeActions(data) {
      // 根节点判断方式以业务为准，此处仅为示例
      return [
        { label: '添加', type: 'add', method: this.addNode },
        { label: '编辑', type: 'edit', method: this.editNode },
        { label: '删除', type: 'delete', method: this.delNode },
      ];
    },
    onTreeNodeClick(node) {
      if (node.id === this.curNode?.id) return;
      this.deptName = node.label;
      this.curNode = { ...node };
      this.form = this.$options.data().form;
    },
    addNode(params, node) {
      // 此处仅为示例 实际为回调
      const tree = this.$refs.appAsyncTree.getElTree();
      tree.append(params, node);
    },
    editNode(params) {
      console.log(params);
    },
    delNode(params) {
      console.log(params);
    },
    // 新增
    addCompany() {
      this.dialogTitle = '新增岗位';
      this.currentRow = null;
      this.dialogVisible = true;
    },
    // 编辑
    showDetail(row) {
      this.dialogTitle = `编辑 - ${row.companyName}`;
      this.currentRow = row;
      this.dialogVisible = true;
    },
    handleSelectionChange(val) {
      this.selectedRows = val; // 更新变量，当选则或取消行时触发
      console.log(val);
    },
    // 确定按钮
    onConfirm(data) {
      this.tableData.push(data);
      localStorage.setItem('tableData', JSON.stringify(this.tableData));
      this.dialogVisible = false;
    },
    delCompany() {
      // 删除实例 ，对selectedRows进行删除
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的行');
        return;
      }
      this.$confirm('此操作将永久删除选中的行，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 从 tableData 中移除选中的行
          this.tableData = this.tableData.filter((item) => !this.selectedRows.includes(item));
          // 清空 selectedRows
          this.selectedRows = [];
          // 存储更新后的 tableData 到本地存储
          localStorage.setItem('tableData', JSON.stringify(this.tableData));
          this.$message.success('删除成功');
          this.refresh();
        })
        .catch(() => {
        });
    },
  },
};
</script>

<style lang="scss" scoped></style>
