<template>
  <div class="layoutMargin">
    <a-row>
      <a-col span="24">
        <a-button icon="plus" type="primary" @click="onCreate">新建</a-button>
      </a-col>
    </a-row>
    <div class="itemMargin">
      <a-alert type="info" show-icon>
        <p slot="description">已选择: {{ selectedRowKeys.length }}</p>
      </a-alert>
    </div>
    <a-table
      class="elevator-table portalTable"
      :dataSource="list"
      :columns="columns"
      size="small"
      :pagination="pagination"
      rowKey="id"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <span slot="operation" slot-scope="text, record">
        <span class="actionBtn" @click="onEdit(record.id)">编辑</span>
        <span class="actionBtn" @click="onDelete(record.id)">删除</span>
      </span>
      <span slot="no" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
    </a-table>
    <a-modal
      title="服务注册"
      v-model="isShow"
      width="900px"
      style="padding: 20px"
      centered
      destroyOnClose
      @cancel="cancelModal()"
    >
    <template slot="footer">
        <a-button key="back" @click="isShow = !isShow">
          取消
        </a-button>
        <a-button
          type="primary"
          @click="handleRegisterOk()"
        >
          提交
        </a-button>
      </template>
      <a-form :form="form">
        <a-form-item
          label="所属系统"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-select
            placeholder="请选择授权类型"
            v-decorator="[
              'systemId',
              {
                validateTrigger: 'blur',
                rules: [{ required: true, message: '请填写此项！' }],
              },
            ]"
          >
            <a-select-option
              v-for="item in businessOptionsList"
              :key="item.value"
              >{{ item.key }}</a-select-option
            >
          </a-select>
        </a-form-item>

        <a-form-item
              label="服务编码"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 12 }"
            >
              <a-input
                v-decorator="[
                  'code',
                  {
                    validateTrigger: 'blur',
                    rules: [{ required: true, message: '请填写此项！' }]
                  }
                ]"
              />
            </a-form-item>

            <a-form-item
              label="服务名称"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 12 }"
            >
              <a-input
                v-decorator="[
                  'name',
                  {
                    validateTrigger: 'blur',
                    rules: [{ required: true, message: '请填写此项！' }]
                  }
                ]"
              />
            </a-form-item>

            <a-form-item
              label="服务路径"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 12 }"
            >
              <a-input
                v-decorator="[
                  'path',
                  {
                    validateTrigger: 'blur',
                    rules: [{validator: pathValidate}]
                  }
                ]"
              />
            </a-form-item>

            <a-form-item label="授权方法" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                  <a-select placeholder="请选择授权方法" v-decorator="['method', {validateTrigger:'blur', rules: [{required: true, message: '请填写此项！'}]}]">
                    <a-select-option value="POST">POST</a-select-option>
                    <a-select-option value="GET">GET</a-select-option>
                  </a-select>
                </a-form-item>

            <a-form-item label="输入参数" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                  <a-textarea
                    v-decorator="[
                      'jsonArgs',
                      {
                        validateTrigger: 'blur',
                        rules: [
                          { required: true, message: '请填写此项！' },
                          {validator: confirmJson}
                        ]
                      }
                    ]"
                  />
                </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: this.$form.createForm(this),
      current: 0,
      steps: [
        {
          title: '基本信息',
        },
        {
          title: '输出参数',
        },
        {
          title: '回调设置',
        },
      ],
      isShow: false,
      selectedRowKeys: [],
      list: [],
      columns: [
        {
          title: '#',
          dataIndex: 'no',
          align: 'center',
          key: 'no',
          scopedSlots: {
            customRender: 'no',
          },
        },
        {
          title: '所属系统',
          dataIndex: 'systemId',
          align: 'center',
          key: 'systemId',
        },
        {
          title: '服务编码',
          dataIndex: 'code',
          align: 'center',
          key: 'code',
        },
        {
          title: '服务名称',
          dataIndex: 'name',
          align: 'center',
          key: 'name',
        },
        {
          title: '服务地址',
          dataIndex: 'callBackPath',
          align: 'center',
          key: 'callBackPath',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: '120px',
          scopedSlots: {
            customRender: 'operation',
          },
        },
      ],
      pagination: {
        //分页
        pageNo: 1,
        pageSize: 10,
        total: 10,
        current: 1,
        defaultCurrent: 1,
        showQuickJumper: true,
        onChange: this.pageChange,
      },
      formStoreList: [],
      rowLoop: [
        {
          first: '',
          second: '',
          third: '',
        },
      ],
      businessOptionsList: [],
      editId: null
    }
  },
  mounted() {
    this.getList()
    this.getBusinessOptions()
  },
  methods: {
    pathValidate(t, value, callback) {
      console.log(t, value, callback)

      if (!value || value == undefined) {
        callback('请填写此项')
      } else {
        if (!value.startsWith('/')) {
          callback('请输入正确的路径！')
        } else{
          callback()
        }
      }
    },
    onEdit(id) {
      this.rowLoop = [{
        name: '',
        key: '',
        randomNum: Math.random()
      }]
      this.isShow = !this.isShow
      let record = this.list.find(item => item.id == id)

      console.log(record)

      if(!!record) {
        this.editId = id

        for (let i = 0; i < Object.keys(record).length; i++) {
          this.form.getFieldDecorator(Object.keys(record)[i], {initialValue: Object.values(record)[i]})
        }
      }
    },
    confirmJson(rule, value, callback) {
      if (!value || value == undefined) {
        callback('不能为空!')
      } else if(typeof value == 'string') {
        try {
          let obj=JSON.parse(value)
          if(typeof obj == 'object' && obj ){
            callback()
          } else {
            callback('不是有效的JSON格式')
          }
        } catch(e) {
          callback('不是有效的JSON格式')
        }
      }
    },
    initPagination() {
      this.pagination.pageNo = 1
      this.pagination.current = 1
    },
    onDelete(id) {
      const that = this
      this.$modal.confirm({
        title: '提示',
        content: '确定删除该条记录吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.$ajax.delete({
            url: that.$api.DELETE_ACTION_RECORD.replace('{id}', id)
          }).then(res => {
            if(res.code == '200') {
              that.$message.success('删除成功!')
              that.initPagination()
              that.getList()
            }
          })
        },
      })
    },
    getBusinessOptions() {
      this.$ajax
        .post({
          url: this.$api.GET_BUSINESS_LIST, // page信息需要拼接在地址栏
          params: {
            page: this.pagination.pageNo,
            size: 10
          }
        })
        .then((res) => {
          if (res.code === '200') {
            let result = this.$com.confirm(res, 'data.content', [])
            for (let i = 0; i < result.length; i++) {
              this.businessOptionsList.push({
                key: result[i].name,
                value: result[i].id,
              })
            }
          }
        })
    },
    getList() {
      this.$ajax
        .post({
          url: this.$api.GET_ACTION_LIST,
          params: {
            page: this.pagination.pageNo,
            size: 10
          }
        })
        .then((res) => {
          this.list = this.$com.confirm(res, 'data.content', [])
          this.pagination.total = this.$com.confirm(res, 'data.totalElements', 0)
        })
    },
    pageChange(val) {
      this.pagination.pageNo = val
      this.pagination.current = val
      this.getList()
      // this.getCompanyList()
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    onCreate() {
      this.rowLoop = [{
        name: '',
        key: ''
      }]
      this.current = 0
      this.form.resetFields()
      this.isShow = !this.isShow
    },
    handlePrevStep() {
      if (this.current >= 1) {
        this.current -= 1
      }
    },
    handleNextStep() {
      this.current += 1
    },
    cancelModal() {
      this.form.resetFields()
      this.current = 0
      this.isShow = !this.isShow
    },
    handleRegisterOk() {

      this.form.validateFields((err, values) => {
        if (!err) {
          let formContent = this.form.getFieldsValue()

          if(!!this.editId) {
            this.$ajax.put({
              url: this.$api.PUT_ACTION_RECORD.replace('{id}', this.editId),
              params: formContent
            }).then(res => {
              if(res.code == '200') {
                this.$message.success('修改成功!')
                this.cancelModal()
                this.form.resetFields()
                this.getList()
              }
            })
          } else {
            this.$ajax.post({
              url: this.$api.POST_ADD_ACTION_RECORD,
              params: formContent
            }).then(res => {
              if(res.code == '200') {
                this.$message.success('新增成功!')
                this.cancelModal()
                this.form.resetFields()
                this.getList()
              }
            })
          }

          this.editId = null
        } else {
          this.$message.info('请填写表单所有项目！')
        }
      })
    },
    addRow() {
      this.rowLoop.push({
        key: '',
        type: '',
        name: '',
      })
    },
    deleteRow() {},
  },
}
</script>

<style scoped>
.itemMargin {
  margin-top: 14px;
  margin-bottom: 14px;
}
</style>
