<template>
  <div class="page-body router-edit-page">

    <vxe-form :data="formOptions.data" ref="xForm" :title-width="formOptions.titleWidth"
      :title-align="formOptions.titleAlign" :rules="formOptions.rules" :items="formOptions.items" titleColon>
      <template #parent_router="{}">
        <vxe-pulldown ref="pulldownParent" transfer>
          <template #default>
            <vxe-input v-model="parentName" suffix-icon="vxe-icon-search" placeholder="选择上级路由"
              @keyup="pulldownKeyupEvent" @focus="pulldownFocusEvent" @suffix-click="pulldownSuffixClick"></vxe-input>
          </template>
          <template #dropdown>
            <div class="my-dropdown">
              <vxe-grid ref="gridParent" v-bind="gridRouterParentOptions" @cell-click="pulldownCellClickEvent">
              </vxe-grid>
            </div>
          </template>
        </vxe-pulldown>
      </template>



    </vxe-form>


    <div class="footerbar-bottom">
      <a-button type="primary" @click="ok">确定</a-button>
      <a-button @click="cancel">取消</a-button>
    </div>

  </div>
</template>
 
<script>
import BASE_URL from '@/services/base/api.js';

export default {

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

  },

  data() {

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

      actions: {
        create: `${BASE_URL.BASE_URL}/BaseService/v1/router/create`,
        update: `${BASE_URL.BASE_URL}/BaseService/v1/router/update`,
        get: `${BASE_URL.BASE_URL}/BaseService/v1/router/detail`,
        list: `${BASE_URL.BASE_URL}/BaseService/v1/router/list`
      },

      service_id: 0,
      parentName: '',

      formOptions: {
        data: {
          "service_id": 1,
          "router": "",
          "parent_id": 0,
          "name": "",
          "path": "",
          "icon": "",
          "component": "",
          "sort": 1,
          "permission": "",
          "link": "",
          "redirect": "",
          "role": "",
          "route_type": 0,
          "invisible": 0,
          "status": 1
        },

        titleWidth: 100,
        titleAlign: 'right',

        rules: {
          router: [
            { required: true, message: '请输入路由Name' }
          ],
          name: [
            { required: true, message: '请输入路由名称' }
          ],
          path: [
            { required: true, message: '请输入路径' }
          ],
        },

        items: [
          { field: 'router', title: '路由Name', span: 24, itemRender: { name: '$input', props: { placeholder: '请输入路由名' } } },
          { title: '父级路由', span: 24, slots: { default: 'parent_router' } },
          { field: 'name', title: '名称', span: 24, itemRender: { name: '$input', props: { placeholder: '请输入路由标题' } } },
          { field: 'path', title: '路径', span: 24, itemRender: { name: '$input', props: { placeholder: '请输入路径' } } },
          { field: 'sort', dataRule: { type: "integer" }, title: '排序', span: 24, itemRender: { name: '$input', props: { type: "integer", placeholder: '请输入路径' } } }
        ]
      },


      gridRouterParentOptions: {
        height: 400,
        id: 'datagrid_router_parent_1',

        proxyConfig: {
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为 
          props: {
            result: 'routers', // 配置响应结果列表字段
            total: 'total' // 配置响应结果总页数字段
          },
          // 接收Promise
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: (options) => {
              const { page, sorts } = options;
              var params = {};
              params.page = page.currentPage;
              params.limit = page.pageSize;
              params.order_bys = [];
              params.search_rules = [];
              if (sorts) {
                sorts.forEach((v) => {
                  params.order_bys.push({
                    column: v.property,
                    order: v.order
                  })
                });
              }
              return this.loadParentGrid({ params });
            }
          }
        },
        sortConfig: {
        },
        treeConfig: {
          transform: true,
          expandAll: true,
          rowField: 'id',
          parentField: 'parent_id'
        },
        checkboxConfig: {
          reserve: true,
          highlight: true
        },
        columns: [
          { field: 'router', treeNode: true, sortable: true, title: '路由名' },
          { field: 'name', sortable: true, title: '路由标题', showHeaderOverflow: true },
          { field: 'path', sortable: true, title: '路径', showHeaderOverflow: true },
          { field: 'parent_router.name', sortable: true, title: '上级路由', showHeaderOverflow: true }
        ]
      }

    };
    pageData.gridRouterParentOptions = Object.assign({}, this.$mk.config.defaults.gridOptions, pageData.gridRouterParentOptions);
    pageData.formOptions = Object.assign({}, this.$mk.config.defaults.formOptions, pageData.formOptions);

    return pageData;
  },
  created() {

    this.service_id = this.pageOptions.service_id;

    if (this.dataId) {
      this.$mk.post({
        url: this.actions.get,
        loading: "加载中...",
        data: {
          id: this.dataId
        }
      }).then(a => {
        this.formOptions.data = a.data.router;
        if (this.formOptions.data.parent_router) {
          this.parentName = this.formOptions.data.parent_router.name;
        }

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


    }

  },
  // 函数
  methods: {


    loadData() {
    },

    loadParentGrid({ params }) {


      params.start_time = 0;
      params.end_time = 0;
      params.service_id = this.service_id;

      return this.$mk.getPagedData({ url: this.actions.list, data: params });
    },

    ok() {

      let save = () => {
        let action = this.pageMode == "add" ? this.actions.create : this.actions.update;
        let postdata = this.pageMode == "add" ? Object.assign({ id: this.dataId }, this.formOptions.data) : Object.assign({}, this.formOptions.data);

        postdata.service_id = this.service_id;
        if (this.pageMode != "add") {
          //postdata =  { BaseService:postdata}
        }

        this.$mk.formatFormData({ data: postdata, rules: this.formOptions.items }); 
        this.$mk.post({
          url: action,
          loading: "保存中...",
          data: postdata,
        }).then(() => {
          this.$mk.success("保存成功");
          this.$emit("callback", { success: true });
        }).catch((a) => {
          this.$mk.error(a.data.msg);
        });
      };

      this.$refs.xForm.validate((a) => {

        if (a) {
          let count = 0;
          for (let name in a) {
            a[name];
            count++;
          }
          this.$mk.error(`存在${count}项错误，请检查`);
        } else {
          save();
        }
      });


    },

    cancel() {
      this.$emit("callback", {});
    },


    pulldownFocusEvent() {
      this.$refs.pulldownParent.showPanel()
    },
    pulldownKeyupEvent() {

    },
    pulldownSuffixClick() {
      this.$refs.pulldownParent.togglePanel()
    },
    pulldownCellClickEvent({ row }) {
      this.formOptions.data.parent_id = row.id;
      this.parentName = row.name;
      this.$refs.pulldownParent.hidePanel()
    },
  },
  // 监听属性
  watch: {

  }
};

</script>
<style scoped lang="less">
.router-edit-page .vxe-pulldown {
  width: 100%;
}
</style>
