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

    <a-row type="flex">
      <a-col :flex="$mk.config.ui.searchFlex">
        <!-- 搜索区 -->
        <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>
      </a-col>
      <a-col :flex="$mk.config.ui.toolbarFlex">
        <!-- 工具条 -->
        <mk-toolbar @toolbarClick="toolbarClick"></mk-toolbar>
      </a-col>
    </a-row>




    <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="pageEditSMS(row)" title="Sms配置"><a-icon type="setting" /></a>
            <a @click.stop="pageEdit(row)" title="编辑"><a-icon type="edit" /></a>
            <a @click.stop="pageDelete(row)" title="删除"><a-icon type="delete" /></a>
          </div>
        </template>

        <template #logo="{ row }">
          <img v-if="row.logo" :src="row.logo" style="width: 60px;" />
          <span v-else>无</span>
        </template>
      </vxe-grid>
    </div>


  </div>
</template>

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

const projectSettingsPage = () => import("./projectSettings");

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

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

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

      start_time: 0,
      end_time: 0,

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



      searchFormItems: [
        { field: 'title', title: '标题', span: 5, itemRender: { name: '$input', props: { placeholder: '请输入标题' } } },
        { field: 'desc', title: '描述', span: 5, itemRender: { name: '$input', props: { placeholder: '请输入描述' } } },
        { span: 8, 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: 'auto' },
          { type: 'seq', width: 50 },
          { field: 'title', sortable: true, title: '标题' },
          { slots: { default: 'logo' }, width: 120, sortable: true, title: '项目Logo', showHeaderOverflow: true },
          { field: 'domain', sortable: true, title: '网址域名', showHeaderOverflow: true },
          { field: 'token', sortable: true, title: 'token', showHeaderOverflow: true },
          // { field: 'desc', sortable: true, title: '描述', showHeaderOverflow: true },
          { title: '操作', slots: { default: 'op' }, width: 150 }
        ]
      }
    };

    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;
      }

    },
    openProjectSettings() {
      let row = this.getSelectdRow();
      if (!row) {
        this.$mk.msg("请选择行");
        return;
      }
      this.$mk.dialog.open({
        page: projectSettingsPage,
        title: "项目配置",
        pageOptions: {
          beid: row.id
        },
        width: 800,
        height: 600,
        dataId: 0,
        callback: ({ success }) => {
          if (success) {
            this.$refs.gridRouter.commitProxy('query')
          }
        }
      });
    },
    // 获取搜索条件
    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.$openPage("/BaseConfig/BaseConfigAdd");
      }
      if (e.name == "setting") {
        this.openProjectSettings();
      }
    },

    // 编辑
    pageEdit(row) {

      if (!row) {
        this.$mk.msg("请选择行");
        return;
      }

      this.$openPage("/BaseConfig/BaseConfigUpdate/" + row[this.keyName]);

    },
    pageEditSMS(row) {
      if (!row) { // 如果没有选中行
        this.$mk.msg("请选择行"); // 提示
        return; // 返回
      }

      this.$mk.dialog.open({
        page: () => import("./setting"),
        title: "参数配置",
        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 scoped lang="less">
.page-body {
  padding: 30px;
  background: @base-bg-color;
}

.gridPanel {
  height: calc((100vh*2) - 400px);
}

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

