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

    <!-- 工具条 -->
    <mk-toolbar @toolbarClick="toolbarClick"></mk-toolbar>



    <!-- 搜索区 -->
    <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> awS QSE8WQE
    </vxe-grid>
    </div>
   

  </div>
</template>

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

let editPage = () => import("./edit");

export default {
  name: 'BaseAgentList', 
  i18n: require('./i18n'),
  props: {
    pageMode: {
      type: String,
      default: "edit"
    }
  },
  data() {

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

      keyName : 'id',
      actions: {
        getList: `${BASE_URL.BASE_URL}/BaseAgent/v1/list`,
        delete: `${BASE_URL.BASE_URL}/BaseAgent/v1/batchDelete`
      },

      start_time :0,
      end_time :0,

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



      searchFormItems: [
        {
          title: '左侧',
          span: 20,
          children: [
            { field: 'title', title: '代理商名称', span: 7, itemRender: { name: '$input', props: { placeholder: '请输入名称' } } },
            { field: 'short_name', title: '代理商简写', span: 7, itemRender: { name: '$input', props: { placeholder: '请输入昵称' } } },

            { span: 10, slots: { default: 'date' } }
          ]
        },
        { align: 'right', 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 },
          { title: '操作', slots: { default: 'op' },width:100 },
          { field: 'title', sortable: true, title: '代理商名称' },
          { field: 'short_name', sortable: true, title: '代理商简写', showHeaderOverflow: true },
          { field: 'company_type', sortable: true, title: '代理商类型', showHeaderOverflow: true },
          { field: 'desc', sortable: true, title: '描述', showHeaderOverflow: true } 
        ]
      }
    };

    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: {
    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;


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

    //add / log / setting
    toolbarClick(e) {
      if (e.name == "add") {
        this.$mk.dialog.open({
        page: editPage,
        title: "新增代理商信息",
        pageMode: "add",
        dataId: 0,
        callback: ({ success }) => {
          success && this.$refs.xGrid.commitProxy('query')
        }
      })
      } 
    }, 

    pageEdit(row) {
      if (!row) {
        this.$mk.msg("请选择行");
        return;
      }
      this.$mk.dialog.open({
        page: editPage,
        title: "编辑代理商信息",
        pageMode: "edit",
        dataId: row[this.keyName],
        callback: ({ success }) => {
          success && this.$refs.xGrid.commitProxy('query')
        }
      })
    },

    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>
.page-body {
  padding: 10px 10px;
  background: white;
}
.gridPanel{ 
  height: calc(100vh - 400px); 
}
</style> 