<template>
  <div class="routerWapper">
    <div class="portalDetailTitle" v-if="$route.name == 'businessSystemList'">
      <span class="title">业务系统</span>
      <div class="layoutMargin layoutPadding">
        <a-row>
          <a-col span="24">
            <a-button icon="plus" type="primary" @click="onRegister">系统注册</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;" destroyOnClose :centered='true' @cancel='cancelModal'>
          <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-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="['url', {validateTrigger:'blur', rules: [{validator: urlValidate}]}]" />
                </a-form-item>
              </div>
              <div v-show="current == 1">
                <a-form-item label="授权类型" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                  <a-select placeholder="请选择授权类型" v-decorator="['authType', {validateTrigger:'blur', rules: [{required: true, message: '请填写此项！'}]}]">
                    <a-select-option value="oauth2">oauth2</a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item label="授权路径" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                  <a-input v-decorator="['authPath', {validateTrigger:'blur', rules: [{required: true, message: '请填写此项！'}, {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-row>
                  <!-- {{rowLoop}} -->
                  <a-col :span='5' style="text-align: right; color: black">授权参数：</a-col>
                  <a-col :span='19'>
                    <a-row v-for="(item, index) in rowLoop" :key="index">
                      <a-col :span='6'>
                        <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-input v-decorator="['value'+index, {validateTrigger:'blur', rules: [{required: true, message: '请填写此项！'}]}]" />
                        </a-form-item>
                      </a-col>

                      <a-col :span='1' :offset='1' v-if="index + 1 == rowLoop.length">
                        <a-button icon='minus' v-if="index !== 0" @click="deleteRow(item.randomNum)" /> 
                      </a-col>
                    </a-row>
                  </a-col>
                </a-row>

                <a-row style="text-align: center">
                  <a-button icon='plus' type="dashed" style="padding: 0px 100px" @click="addRow()">添加参数</a-button>
                </a-row>
              </div>
              <div v-show="current == 2">
                <a-form-item label="Token Key" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                  <a-input v-decorator="['authTokenKey', {validateTrigger:'blur', rules: [{required: true, message: '请填写此项！'}]}]" />
                </a-form-item>

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

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

                <a-form-item label="Token Expires Time Key" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                  <a-input v-decorator="['authTokenTimeKey', {validateTrigger:'blur', rules: [{required: true, message: '请填写此项！'}]}]" />
                </a-form-item>
              </div>
            </a-form>
          </div>
          <template slot="footer">
            <a-button key="back" @click="cancelModal()">
              取消
            </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>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rowLoop: [{
        name: '',
        key: '',
        randomNum: Math.random()
      }],
      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: 'code',
          align: 'center',
          key: 'code'
        },
        {
          title: '系统名称',
          dataIndex: 'name',
          align: 'center',
          key: 'name'
        },
        {
          title: '系统地址',
          dataIndex: 'url',
          align: 'center',
          key: 'url'
        },
        {
          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: [],
      businessOptionsList: [],
      editId: null
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    urlValidate(type, value, callback) {

      const regex = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|www\.)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/

      if (!value || value == undefined) {
        callback('请填写此项')
      } else {
        if (!regex.test(value)) {
          callback('请输入正确的地址！')
        } else{
          callback()
        }
      }

      // if(!value.startsWith('/')) {
      //   callback('请输入正确的路径！')
      // }
    },

    pathValidate(t, value, callback) {
      console.log(t, value, callback)

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

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

        for (let i = 0; i < Object.keys(record).length; i++) {
          if(Object.keys(record)[i] !== 'data') {
            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('value' + j, {initialValue: Object.values(record)[i][j].value})
            }
          }
        }
      }
      
      // this.form.setFieldsValue(record)
    },
    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_BUSINESS_RECORD.replace('{id}', id)
          }).then(res => {
            if(res.code == '200') {
              that.$message.success('删除成功!')
              that.initPagination()
              that.getList()
            }
          })
        },
      })
    },
    addRow() {
      this.rowLoop.push({
        name: '',
        key: '',
        randomNum: Math.random()
      })
    },
    deleteRow(randomNum) {
      // this.rowLoop.splice(index, 1)
      this.rowLoop = this.rowLoop.filter(i => i.randomNum !== randomNum)
    },
    getList() {
      this.$ajax.post({
        url: this.$api.GET_BUSINESS_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
    },
    onRegister() {
      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
    },
    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({
              key: formContent['key' + i],
              value: formContent['value' + i],
            })
          }

          finalParse = {
            code: this.form.getFieldValue('code'),
            name: this.form.getFieldValue('name'),
            url: this.form.getFieldValue('url'),
            method: this.form.getFieldValue('method'),
            data: paramsJson,
            authType: this.form.getFieldValue('authType'),
            authPath: this.form.getFieldValue('authPath'),
            authTokenKey: this.form.getFieldValue('authTokenKey'),
            authTokenHeaderName: this.form.getFieldValue('authTokenHeaderName'),
            authTokenPrefix: this.form.getFieldValue('authTokenPrefix'),
            authTokenTimeKey: this.form.getFieldValue('authTokenTimeKey')
          }

          if(!!this.editId) {
            this.$ajax.put({
              url: this.$api.PUT_BUSINESS_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_BUSINESS_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('请填写表单所有项目！')
        }
      })
    }
  }
}
</script>

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