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

    <!-- 工具条 -->
    <mk-toolbar v-if="pageMode != 'select'" @toolbarClick="toolbarClick"></mk-toolbar>

    <div class="mk-toolbar" v-if="pageMode == 'select'">
      <a-button type="primary" @click="pageSelect">选择</a-button>
    </div>

    <!-- 搜索区 -->
    <vxe-form :data="searchFormData" :items="searchFormItems" titleColon @submit="onSearch">
      <template #date="{}">
        <a-form-item label="创建时间" :style="{ display: 'inline-block', width: 120 }">
        </a-form-item>
        <a-form-item :style="{ display: 'inline-block', width: 'calc(100% - 120px )' }">
          <a-range-picker @change="onDateChange" />
        </a-form-item>
      </template>
    </vxe-form>

    <vxe-toolbar ref="xToolbar" custom>
      <template #buttons>
        <a-button type="primary" icon="delete" @click="pageDelete()">批量删除</a-button>
      </template>
    </vxe-toolbar>
    <!-- 表格区 -->
    <div class="gridPanel">
      <vxe-grid ref='xGrid' v-bind="gridOptions">
          <template #status="{ row }">
            <a-switch :checked="row.status ? true : false" @change="onSwitch(row, 'status')" />
          </template>
          <template #op="{ row }">
            <div class="oplinks">
            <a @click.stop="pageEdit(row)" title="编辑"><a-icon type="edit" /></a>
            <a @click.stop="pageDelete(row)" title="删除"><a-icon type="delete" /></a> 
          </div>
          </template> 
    </vxe-grid>
    </div>
   

  </div>
</template>

<script>
import BASE_URL from '@/services/base/api.js';
export default {
  name: 'BaseServiceList',
  i18n: require('./i18n'),

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

    pageOptions: {
      type: Object 
    },
  },

  data() {

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

      keyName: 'id',
      actions: {
        getList: `${BASE_URL.BASE_URL}/BaseService/v1/list`,
        delete: `${BASE_URL.BASE_URL}/BaseService/v1/batchDelete`,
        serviceOpen: `${BASE_URL.BASE_URL}/BaseService/v1/open`,
        serviceClose: `${BASE_URL.BASE_URL}/BaseService/v1/close`,
        getConfigServiceList: `${BASE_URL.BASE_URL}/BaseConfig/v1/service/list`,
      },

      start_time: 0,
      end_time: 0,

      //搜索区
      searchFormData: {
        name: '',
        nick_name: '',
      },
      searchRules: [
        { key: "name", mode: "like" },
        { key: "title", mode: "like" }
      ],



      searchFormItems: [
        {
          title: '左侧',
          span: 20,
          children: [
            { field: 'name', title: '名称', span: 5, itemRender: { name: '$input', props: { placeholder: '请输入名称' } } },
            { field: 'title', title: '标题', span: 5, itemRender: { name: '$input', props: { placeholder: '请输入标题' } } },
            { span: 8, slots: { default: 'date' } },
            { align: 'left', span: 4, itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: '搜索', status: 'primary' } }, 
            { props: { type: 'reset', content: '重置' } }] } }
          ]
        }
      ],



      //数据区
      gridOptions: {
        height: '100%',
        id: 'datagrid_1',

        proxyConfig: {
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为 
          props: {
            result: 'list', // 配置响应结果列表字段
            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 = this.getSearchParms();
              if (sorts) {
                sorts.forEach((v) => {
                  params.order_bys.push({
                    column: v.property,
                    order: v.order
                  })
                });
              }
              return this.loadData({ params });
            }
          }
        },
        columns: [
          { type: 'checkbox', width: 50 },
          { type: 'seq', width: 50 },
          { field: 'name', sortable: true, title: '服务名称' ,width:180},
          { field: 'title', sortable: true, title: '服务中文名', showHeaderOverflow: true  ,width:220},
          { field: 'desc',sortable: true, title: '描述', showHeaderOverflow: true  ,width:400},
          { field: 'port', sortable: true, title: '端口', showHeaderOverflow: true ,width:100 },
          { field: 'version', sortable: true, title: '版本', showHeaderOverflow: true ,width:100 },
          { field: 'status', sortable: true, title: '是否启用', slots: { default: 'status' } ,width:100 },
          { title: '操作', slots: { default: 'op' },width:120 }
        ]
      }
    };

    // for(let i = 0;i<20;i++){
    //   pageData.gridOptions.columns.push({title:'列'+i,width: 100});
    // }

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

    return pageData;
  },
  computed: {
    desc() {
      return this.$t('pageDesc')
    }
  },
  created() {
    this.$nextTick(() => {
      // 将表格和工具栏进行关联 
      this.$refs.xGrid.connect(this.$refs.xToolbar)
    });
 
  },
  onLoad() {

  },
  // 函数
  methods: {

    onSwitch(row) {
      row.status = row.status ? 0 : 1;
      this.$mk.post({
        url: row.status ? this.actions.serviceOpen : this.actions.serviceClose,
        data: { service_id: row.id },
      }).then(() => {
        this.$mk.msg(row.status ? "开启服务完成" : "停止服务完成");
        this.$emit("callback", { success: true });
      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });

    },
    onDateChange(date) {
      if (date && date.length) {
        this.start_time = parseInt(date[0]._d.getTime() / 1000);
        this.end_time = parseInt(date[1]._d.getTime() / 1000);
      } else {
        this.start_time = 0;
        this.end_time = 0;
      }

    },
    getSearchParms() {
      var rules = [];
      let findMode = k => {
        for (let i in this.searchRules) {
          if (this.searchRules[i].key == k) return this.searchRules[i].mode;
        }
        return "equal";
      };

      for (let key in this.searchFormData) {
        let value = this.searchFormData[key];
        if (value) {
          let mode = findMode(key);
          if (mode == "like") {
            value = "%" + value + "%";
          }
          rules.push({
            column: key,
            mode: mode,
            value: value
          });
        }
      }
      return rules;
    },
    getSelectdRow() {
      let row = this.$refs.xGrid.getCurrentRecord();
      if (!row) {
        let rows = this.$refs.xGrid.getCheckboxRecords();
        if (rows && rows.length) { row = rows[0]; }
      }
      return row;
    },
    loadData({ params }) {

      params.start_time = this.start_time;
      params.end_time = this.end_time;
      if(this.pageOptions && this.pageOptions.config_id){
        params.beid = this.pageOptions.config_id;
        return this.$mk.getPagedData({ url: this.actions.getConfigServiceList, data: params });
      }

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

    //add / log / setting
    toolbarClick(e) {
      if (e.name == "add") {
        this.$openPage("/BaseService/BaseServiceAdd");
      } 
    },

    pageEdit(row) {
      this.$openPage("/BaseService/BaseServiceUpdate/" + row[this.keyName]);
    },

    pageSelect() {
      let rows = this.$refs.xGrid.getCheckboxRecords();
      let ids = [];
      rows.forEach((row) => {
        ids.push(row[this.keyName]);

      });

      if (!ids.length) {
        this.$mk.error("请选择行");
        return;
      }
      this.$emit("callback", { data: { ids: ids } });

    },
    // 删除
    pageDelete(row) {


      let rows = row ? [row] : this.$refs.xGrid.getCheckboxRecords();
      let ids = [];
      rows.forEach((row) => {
        ids.push(row[this.keyName]);

      });

      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
            }
          }).then(() => {
            this.$mk.success("删除成功");
            this.onSearch();
          }).catch((a) => {
            this.$mk.error(a.data.msg);
          });
        }
      });


    },
    onSearch() {
      this.$refs.xGrid.commitProxy('query')
    }
  },
  // 监听属性
  watch: {

  }
};

</script>
<style scoped lang="less">
.page-body {
  padding: 30px ;
  background: @base-bg-color;
}
.gridPanel{ 
  height: calc(100vh - 400px); 
}

</style> 
<style>
.oplinks svg { 
      width: 22px;
      height:22px;
      margin: 0 5px 0  0;
}
</style>