<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
      @cancel='cancelModal()'
      destroyOnClose
    >
      <a-steps :current="current" style="margin-bottom: 20px">
        <a-step v-for="item in steps" :key="item.title" :title="item.title" />
      </a-steps>
      <div class="steps-content" style="height: 300px; overflow-y: scroll">
        <!-- {{ steps[current].content }} -->
        <a-form :form="form">
          <div v-show="current == 0">
            <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>
          </div>
          <div v-show="current == 1">
            <a-row v-for="(item, index) in rowLoop" :key="index">
              <a-col :span="6" offset="1">
                <a-form-item>
                  <a-input
                    v-decorator="[
                      'key' + index,
                      {
                        validateTrigger: 'blur',
                        rules: [{ required: true, message: '请填写此项！' }]
                      }
                    ]"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6" offset="1">
                <a-form-item>
                  <a-select
                    v-decorator="[
                      'type' + index,
                      {
                        validateTrigger: 'blur',
                        rules: [{ required: true, message: '请填写此项！' }]
                      }
                    ]"
                  >
                    <a-select-option value="String">String</a-select-option>
                    <a-select-option value="Integer">Integer</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6" offset="1">
                <a-form-item>
                  <a-input
                    v-decorator="[
                      'name' + index,
                      {
                        validateTrigger: 'blur',
                        rules: [{ required: true, message: '请填写此项！' }]
                      }
                    ]"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="2" offset="1">
                <!-- {{item}} -->
                <a-button
                  v-if="index + 1 == rowLoop.length"
                  icon="minus"
                  @click="deleteRow(item.randomNum)"
                ></a-button>
                <a-button
                  v-if="index + 1 == rowLoop.length"
                  icon="plus"
                  @click="addRow()"
                ></a-button>
              </a-col>
            </a-row>
          </div>
          <div v-show="current == 2">
            <a-form-item
              label="回调地址"
              :label-col="{ span: 5 }"
              :wrapper-col="{ span: 12 }"
            >
              <a-input
                v-decorator="[
                  'callBackPath',
                  {
                    validateTrigger: 'blur',
                    rules: [{validator: pathValidate}]
                  },
                ]"
              />
            </a-form-item>
          </div>
        </a-form>
      </div>
      <template slot="footer">
        <a-button key="back" @click="isShow = !isShow">
          取消
        </a-button>
        <a-button v-if="current >= 1" type="primary" @click="handlePrevStep()">
          上一步
        </a-button>
        <a-button v-if="current < 2" type="primary" @click="handleNextStep()">
          下一步
        </a-button>
        <a-button
          v-if="current == 2"
          type="primary"
          @click="handleRegisterOk()"
        >
          完成
        </a-button>
      </template>
    </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: [{
        key: '',
        type: '',
        name: '',
        randomNum: Math.random()
      }],
      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()
        }
      }
    },
    cancelModal() {
      this.form.resetFields()
      this.current = 0
      this.isShow = !this.isShow
    },
    onEdit(id) {
      this.rowLoop = [{
        key: '',
        type: '',
        name: '',
        randomNum: Math.random()
      }]
      this.isShow = !this.isShow
      let record = this.list.find(item => item.id == id)

      console.log(record)

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

        console.log(Object.keys(record))

        for (let i = 0; i < Object.keys(record).length; i++) {
          if(Object.keys(record)[i] !== 'args') {
            this.form.getFieldDecorator(Object.keys(record)[i], {initialValue: Object.values(record)[i]})
          } else {
            for (let j = 0; j < Object.values(record)[i].length; j++) {
              console.log(Object.values(record)[i][j])
              if(j !== 0) {
                this.addRow()
              }
              this.form.getFieldDecorator('key' + j, {initialValue: Object.values(record)[i][j].key})
              this.form.getFieldDecorator('type' + j, {initialValue: Object.values(record)[i][j].type})
              this.form.getFieldDecorator('name' + j, {initialValue: Object.values(record)[i][j].name})
            }
          }
        }
      }
      
      // this.form.setFieldsValue(record)
    },
    initPagination() {
      this.pagination.pageNo = 1
      this.pagination.current = 1
    },
    onDelete(id) {
      let that = this
      this.$modal.confirm({
        title: '提示',
        content: '确定删除该条记录吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.$ajax.delete({
            url: that.$api.DELETE_TRIGGER_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_TRIGGER_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: '',
        type: '',
        key: '',
        randomNum: Math.random()
      }]
      this.current = 0
      this.form.resetFields()
      this.isShow = !this.isShow
    },
    handlePrevStep() {
      if(this.current >= 1) {
        this.current -= 1
      }
    },
    handleNextStep() {
      this.current += 1
    },
    handleRegisterOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          let formContent = this.form.getFieldsValue()

          let paramsJson = []
          let finalParse = {}
          // 遍历有多少行授权参数
          for (let i = 0; i < this.rowLoop.length; i++) {
            paramsJson.push({
              required: 'false',
              key: formContent['key' + i],
              type: formContent['type' + i],
              name: formContent['name' + i],
              example: null,
              group: null
            })
          }

          finalParse = {
            code: this.form.getFieldValue('code'),
            name: this.form.getFieldValue('name'),
            systemId: this.form.getFieldValue('systemId'),
            callBackPath: this.form.getFieldValue('callBackPath'),
            args: paramsJson
          }

          if(!!this.editId) {
            this.$ajax.put({
              url: this.$api.PUT_TRIGGER_RECORD.replace('{id}', this.editId),
              params: finalParse
            }).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_TRIGGER_RECORD,
              params: finalParse
            }).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: '',
        randomNum: Math.random()
      })
    },
    deleteRow(randomNum) {
      this.rowLoop = this.rowLoop.filter(i => i.randomNum !== randomNum)
    }
  }
}
</script>

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