<template> 
  <page-layout :desc="desc" >
  <div class="page-body">



    <vxe-form :data="formOptions.data" ref="xForm" :title-width="formOptions.titleWidth"
          :title-align="formOptions.titleAlign" :rules="formOptions.rules" :items="formOptions.items" titleColon>
   
        </vxe-form>


    <a-tabs default-active-key="1" class="formtabs">
      <a-tab-pane key="1" tab="路由管理" v-if="isEdit">

        <div class="mk-toolbar">
          <a-button type="primary" @click="pageAdd">增加路由</a-button>
        </div>
        <div class="gridPanel">
          <vxe-grid ref='gridRouter' v-bind="gridRouterOptions">
          <template #op="{ row }">
            <vxe-button status="primary" icon="vxe-icon-edit" @click="pageEdit(row)">编辑</vxe-button>
            <vxe-button icon="vxe-icon-delete" @click="pageDel(row)">删除</vxe-button>
          </template>
        </vxe-grid>
        </div>
      

      </a-tab-pane>
      <a-tab-pane key="2" tab="权限管理" force-render v-if="isEdit">

        <div class="mk-toolbar">
          <a-button type="primary" @click="pageAdd2">增加权限</a-button>
        </div>
        <div class="gridPanel">
          <vxe-grid ref='gridPermission' v-bind="gridPermissionOptions">
          <template #op="{ row }">
            <vxe-button status="primary" icon="vxe-icon-edit" @click="pageEdit2(row)">编辑</vxe-button>
            <vxe-button icon="vxe-icon-delete" @click="pageDel2(row)">删除</vxe-button>
          </template>
        </vxe-grid>

          </div>


      </a-tab-pane>

    </a-tabs>



     

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

  </div> 
</page-layout>
</template>

<script>
import BASE_URL from '@/services/base/api.js';
import PageLayout from '@/layouts/PageLayout'


const routerEditPage = () => import("./routerEdit");
const permissionEditPage = () =>import("./permissionEdit");
export default {

  name: 'BaseServiceUpdate',
  i18n: require('./i18n'),
  components: {PageLayout},
  props: {
    pageMode: {
      type: String,
      default: "edit"
    },
    dataId: {
    }

  },

  data() {

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

      actions: {
        create: `${BASE_URL.BASE_URL}/BaseService/v1/create`,
        update: `${BASE_URL.BASE_URL}/BaseService/v1/update`,
        get: `${BASE_URL.BASE_URL}/BaseService/v1/detail`,
        routerList: `${BASE_URL.BASE_URL}/BaseService/v1/router/list`,
        routerDel: `${BASE_URL.BASE_URL}/BaseService/v1/router/batchDelete`,
        permissionList:`${BASE_URL.BASE_URL}/BasePermission/v1/base/permission/list`,
        permissionDel: `${BASE_URL.BASE_URL}/BasePermission/v1/base/permission/batchDelete`,
      },

      keyName: 'id',
      isEdit: false,
      formOptions: {
        data: {
          "name": "",
          "title": "",
          "desc": "",
          "port": 80,
          "version": "",
          "status": 1,
          "token": ""
        },


        titleWidth: 100,
        titleAlign: 'right',

        rules: {
          name: [
            { required: true, message: '请输入服务名' }
          ],
          title: [
            { required: true, message: '请输入标题' }
          ],
        },


        items: [
          {
            title: '左侧',
            children: [
              { field: 'name', title: '服务名', span: 16, itemRender: { name: '$input', props: { placeholder: '请输入服务名' } } },
              { field: 'title', title: '服务标题', span: 16, itemRender: { name: '$input', props: { placeholder: '请输入服务标题' } } },
              { field: 'desc', title: '描述', span: 16, itemRender: { name: '$textarea', props: { placeholder: '请输入描述' } } },
              { field: 'port', title: '端口', span: 10, itemRender: { name: '$input', props: { placeholder: '请输入端口' } } },
              { field: 'version', title: '版本号', span: 6, itemRender: { name: '$input', props: { placeholder: '请输入版本号' } } }
            ]
          }
        ]

      },


      //路由管理 - 数据区
      gridRouterOptions: {
        height: '110%', 
        id: 'datagrid_router_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.loadDetailData1({ params });
            }
          }
        },
        treeConfig: {
          transform: true,
          expandAll: true,
          rowField: 'id',
          parentField: 'parent_id'
        },
        checkboxConfig: {
          reserve: true,
          highlight: true
        },
        columns: [
          { field: 'router', treeNode: true, sortable: true, title: '路由Name' },
          { field: 'name', sortable: true, title: '名称', showHeaderOverflow: true },
          { field: 'path', sortable: true, title: '路径', showHeaderOverflow: true },
          { title: '操作', slots: { default: 'op' } ,width: 200}
        ]
      },

       //路由管理 - 数据区
       gridPermissionOptions: {
        height: '110%', 
        id: 'datagrid_permission_1',

        proxyConfig: {
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为 
          props: {
            result: 'BasePermission', // 配置响应结果列表字段
            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.loadDetailData2({ params });
            }
          }
        },
        treeConfig: {
          transform: true,
          expandAll: true,
          rowField: 'id',
          parentField: 'parent_id'
        },
        checkboxConfig: {
          reserve: true,
          highlight: true
        },
        columns: [
        { field: 'title', sortable: true, title: '权限名' },
          { field: 'permission_code', sortable: true, title: '编号', showHeaderOverflow: true }, 
          { field: 'desc', sortable: true, title: '描述', showHeaderOverflow: true },
          { title: '操作', slots: { default: 'op' } }
        ]
      }

    };

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

    return pageData;
  },
  computed: {
    desc() {
      return this.$t('editPageDesc')
    }
  },
  created() {
    let dataId = this.getDataId();

    if (dataId) {
      this.$mk.post({
        url: this.actions.get,
        loading: "加载中...",
        data: {
          id: parseInt(dataId)
        }
      }).then(a => {
        this.formOptions.data = a.data.BaseService;
      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });

      this.isEdit = true;
    }

  },
  // 函数
  methods: {


    getDataId() {

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

      return parseInt(dataId || 0);
    },
    loadDetailData1({ params }) {


      params.start_time = 0;
      params.end_time = 0;
      params.service_id = this.getDataId();

      return this.$mk.getPagedData({
        url: this.actions.routerList, data: params, callback: () => {

          setTimeout(() => {
            this.$refs.gridRouter.setAllTreeExpand(true);
          }, 100);

        }
      });
    },
    loadDetailData2({ params }) {


      params.start_time = 0;
      params.end_time = 0;
      params.service_id = this.getDataId();

      return this.$mk.getPagedData({
        url: this.actions.permissionList, data: params
      });
    },
    back() {
      if (!this.isEdit) {
        this.$closePage({
          closeRoute: "/BaseService/BaseServiceAdd"
        });
      } else {
        this.$closePage({
          closeRoute: "/BaseService/BaseServiceUpdate"
        });
      }
      this.$openPage('/BaseService/BaseServiceList')
    },
    ok() {

      let save = () => {
        let action = !this.isEdit ? this.actions.create : this.actions.update;
        let postdata = !this.isEdit ? Object.assign({ id: this.dataId }, this.formOptions.data) : Object.assign({}, this.formOptions.data);
        if (this.isEdit) {
          postdata = { BaseService: postdata }
        }
        this.$mk.post({
          url: action,
          loading: "保存中...",
          data: postdata,
        }).then(() => {
          this.$mk.success("保存成功");

          if (!this.isEdit) {
            this.back();
          }

        }).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();
        }
      });


    },
    pageDel(row) {
      let ids = [row.id];

      let send = ()=>{
        this.$mk.post({
            url: this.actions.routerDel,
            loading: "移除路由中...",
            data: {
              ids: ids
            }
          }).then(() => {
            this.$mk.success("移除路由成功");
            this.$refs.gridRouter.commitProxy('query')
          }).catch((a) => {
            this.$mk.error(a.data.msg);
          });
      };
      send();
      /*
      this.$mk.confirm('您确定要移除路由吗？').then(type => {
        if (type == 'confirm') {
         send();
        }
      });
      */

    },
    pageDel2(row) {
      let ids = [row.id];

      this.$mk.confirm('您确定要移除权限吗？').then(type => {
        if (type == 'confirm') {
          this.$mk.post({
            url: this.actions.permissionDel,
            loading: "移除权限中...",
            data: {
              ids: ids
            }
          }).then(() => {
            this.$mk.success("移除权限成功");
            this.$refs.gridPermission.commitProxy('query')
          }).catch((a) => {
            this.$mk.error(a.data.msg);
          });
        }
      });

    },
    pageAdd() {
      this.$mk.dialog.open({
        page: routerEditPage,
        title: "添加路由",
        pageMode: "add",
        pageOptions: {
          service_id: this.getDataId()
        },
        width: 800,
        height: 600,
        dataId: 0,
        callback: ({ success }) => {
          if (success) {
            this.$refs.gridRouter.commitProxy('query')
          }
        }
      });
    },
    pageAdd2() {
      this.$mk.dialog.open({
        page: permissionEditPage,
        title: "添加权限",
        pageMode: "add",
        pageOptions: {
          service_id: this.getDataId(),
          service :  this.formOptions.data.name
        },
        width: 800,
        height: 600,
        dataId: 0,
        callback: ({ success }) => {
          if (success) {
            this.$refs.gridPermission.commitProxy('query')
          }
        }
      });
    },
    getSelectdRow(grid) {
      let row = grid.getCurrentRecord();
      if (!row) {
        let rows = grid.getCheckboxRecords();
        if (rows && rows.length) { row = rows[0]; }
      }
      return row;
    },

    pageEdit(row) {
      this.$mk.dialog.open({
        page: routerEditPage,
        title: "编辑路由",
        pageMode: "edit",
        pageOptions: {
          service_id: this.getDataId()
        },
        width: 800,
        height: 600,
        dataId: row.id,
        callback: ({ success }) => {
          if (success) {
            this.$refs.gridRouter.commitProxy('query')
          }
        }
      });
    },
    pageEdit2(row) {
      this.$mk.dialog.open({
        page: permissionEditPage,
        title: "编辑权限",
        pageMode: "edit",
        pageOptions: {
          service_id: this.getDataId(),
          service :  this.formOptions.data.name
        },
        width: 800,
        height: 600,
        dataId: row.id,
        callback: ({ success }) => {
          if (success) {
            // 触发 commitProxy 的query方法 刷新表格
            this.$refs.gridPermission.commitProxy('query')
          }
        }
      });
    },
    
    cancel() {
      this.back();
    }
  },
  // 监听属性
  watch: {

  }
};

</script>
<style scoped lang="less">
.page-body{
  background: @base-bg-color;
  padding: 30px ;
}
.formtabs {

  padding: 10px 30px;
  .ant-tabs-tabpane {
  background: @base-bg-color;
  padding: 20px 30px;
}
}

.gridPanel{ 
  height: calc(150vh - 580px);   
}

</style>
