<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" v-if="isEdit">
        <a-tab-pane key="1" tab="服务管理">

          <div class="mk-toolbar">
            <a-button type="primary" @click="pageAdd">增加服务</a-button>
            <a-button @click="pageDel">删除服务</a-button>
          </div>
          <div class="gridPanel">
            <vxe-grid ref='gridService' v-bind="gridServiceOptions">
              <template #status="{ row }">
                <a-switch :checked="row.status ? true : false" @change="onSwitch(row, 'status')" />
              </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'


let serviceListPage = () => import("../BaseService/list");

export default {

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

  },

  data() {

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

      actions: {
        create: `${BASE_URL.BASE_URL}/BaseConfig/v1/create`,
        update: `${BASE_URL.BASE_URL}/BaseConfig/v1/update`,
        get: `${BASE_URL.BASE_URL}/BaseConfig/v1/detail`,
        serviceList: `${BASE_URL.BASE_URL}/BaseConfig/v1/service/list`,
        serviceAdd: `${BASE_URL.BASE_URL}/BaseConfig/v1/service/add`,
        serviceDel: `${BASE_URL.BASE_URL}/BaseConfig/v1/service/detele`,
        serviceOpen: `${BASE_URL.BASE_URL}/BaseConfig/v1/service/open`,
        serviceClose: `${BASE_URL.BASE_URL}/BaseConfig/v1/service/close`
      },

      keyName: 'id',
      isEdit: false,
      formOptions: {
        data: {
          "title": "",
          "desc": "",
          "logo": "",
          "domain": "",
          "devdomain": "",
          "appid": "",
          "appsecret": "",
          "token": "",
          "status": 1,
          "accessexpire": 73,
          "en_title": "",
          "en_desc": "",
          "sub_title": "",
          "en_sub_title": "",
          "copy_right": "",
          "en_copy_right": ""
        },

        titleWidth: 100,
        titleAlign: 'right',

        rules: {
          title: [
            { required: true, message: '请输入标题' }
          ],
          desc: [
            { required: true, message: '请输入描述' }
          ],
        },

        items: [
          {
            title: '左侧',
            children: [
              { field: 'title', title: '项目名称', span: 16, itemRender: { name: '$input', props: { placeholder: '请输入项目名' } } },
              { field: 'desc', title: '项目描述', span: 16, itemRender: { name: '$textarea', props: { placeholder: '请输入描述' } } },
              { field: 'logo', title: 'Logo', span: 20, itemRender: { name: '$input', props: { placeholder: '请输入LOGO' } } },
              { field: 'domain', title: '网址域名', span: 10, itemRender: { name: '$input' } },
              { field: 'devdomain', title: '开发域名', span: 10, itemRender: { name: '$input' } },
              { field: 'appid', title: 'AppID', span: 20, itemRender: { name: '$textarea' } },
              { field: 'appsecret', title: 'AppSecret', span: 20, itemRender: { name: '$textarea' } },
              { field: 'token', title: '项目Token', span: 20, itemRender: { name: '$textarea' } }
            ]
          }
        ]
      },


      //服务管理 - 数据区
      gridServiceOptions: {
        height: '110%',
        id: 'datagrid_service_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 = [];
              if (sorts) {
                sorts.forEach((v) => {
                  params.order_bys.push({
                    column: v.property,
                    order: v.order
                  })
                });
              }
              return this.loadDetailData1({ params });
            }
          }
        },
        columns: [
          { type: 'checkbox', width: 50 },
          { type: 'seq', width: 50 },
          { field: 'name', sortable: true, title: '服务名' },
          { field: 'title', sortable: true, title: '标题', showHeaderOverflow: true },
          { field: 'port', sortable: true, title: '端口', showHeaderOverflow: true },
          { field: 'status', sortable: true, title: '是否启用', slots: { default: 'status' } }
        ]
      }

    };
    pageData.gridServiceOptions = Object.assign({}, this.$mk.config.defaults.gridOptions, pageData.gridServiceOptions);
    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.BaseConfig;
      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });

      this.isEdit = true;
    }

  },
  // 函数
  methods: {


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

    },
    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.beid = this.getDataId();

      return this.$mk.getPagedData({ url: this.actions.serviceList, data: params });
    },
    back() {
      if (!this.isEdit) {
        this.$closePage({
          closeRoute: "/BaseConfig/BaseConfigAdd"
        });
      } else {
        this.$closePage({
          closeRoute: "/BaseConfig/BaseConfigUpdate"
        });
      }
      this.$openPage('/BaseConfig/BaseConfigList')
    },
    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 = { BaseConfig: 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() {
      let rows = this.$refs.gridService.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.serviceDel,
            loading: "移除服务中...",
            data: {
              ids: ids
            }
          }).then(() => {
            this.$mk.success("移除服务成功");
            this.$refs.gridService.commitProxy('query')
          }).catch((a) => {
            this.$mk.error(a.data.msg);
          });
        }
      });

    },
    pageAdd() {
      this.$mk.dialog.open({
        page: serviceListPage,
        title: "选择要添加的服务",
        pageMode: "select",
        width: 1000,
        height: 870,
        dataId: 0,
        callback: ({ data }) => {

          this.$mk.post({
            url: this.actions.serviceAdd,
            loading: "添加中...",
            data: {
              "beid": this.getDataId(),
              "service_id": data.ids
            },
          }).then(() => {
            this.$mk.success("添加成功");

            this.$refs.gridService.commitProxy('query')
          }).catch((a) => {
            this.$mk.error(a.data.msg);
          });
        }
      });
    },
    cancel() {
      this.back();
    }
  },
  // 监听属性
  watch: {

  }
};

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

.formtabs .ant-tabs-tabpane {
  /* background: white; */
  padding: 12px;
}

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

.footerbar {
  padding-left: 10px;
}
</style>
