<template>
  <div class="routerWapper">
    <div class="portalDetailTitle" v-if="$route.name == 'iftttRulesList'">
      <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)">编辑</span>
            <span class="actionBtn" @click="onDelete(record.id)">删除</span>
          </span>
          <span  slot="no" slot-scope="text, record, index"> 
            {{index+1}}
          </span>

          <span  slot="trigger" slot-scope="text, record, index"> 
            {{record.trigger.name}}
          </span>

          <span  slot="action" slot-scope="text, record, index"> 
            {{record.action.name}}
          </span>

          <span  slot="rules" slot-scope="text, record, index"> 
            <a-tag v-for="(item, index) in record.rules" :key="index">{{`{` + record.rules[index].key + `: `+ record.rules[index].value + `}`}}</a-tag>
          </span>
        </a-table>
        <a-modal title="新建规则"  v-model="isShow" width='900px' style="padding: 20px">
            <a-form :form='form'>
              <a-form-item label="触发服务" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                  <a-select placeholder="请选择触发服务" v-decorator="['trigger', {validateTrigger:'blur', rules: [{required: true, message: '请选择此项！'}]}]">
                    <a-select-option v-for="(item) in triggerOptions" :key="item.id">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item label="执行服务" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                  <a-select placeholder="请选择执行服务" v-decorator="['action', {validateTrigger:'blur', rules: [{required: true, message: '请选择此项！'}]}]">
                    <a-select-option v-for="(item) in actionOptions" :key="item.id">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item label="规则字段定义" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                  <a-textarea
                    v-decorator="[
                      'rules',
                      {
                        validateTrigger: 'blur',
                        rules: [
                          { required: true, message: '请填写此项！' },
                          {validator: confirmJson}
                        ]
                      }
                    ]"
                  />
                </a-form-item>
            </a-form>
          <template slot="footer">
            <a-button key="back" @click="isShow = !isShow">
              取消
            </a-button>
            <a-button type="primary" @click="handleRegisterOk()">
              完成
            </a-button>
          </template>
        </a-modal>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rowLoop: [{
        name: '',
        key: ''
      }],
      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: 'trigger',
          align: 'center',
          key: 'trigger',
          width: '100px',
          scopedSlots: {
            customRender: 'trigger',
          },
        },
        {
          title: '执行服务',
          dataIndex: 'action',
          align: 'center',
          key: 'action',
          width: '100px',
          scopedSlots: {
            customRender: 'action',
          },
        },
        {
          title: '规则字段定义',
          dataIndex: 'rules',
          align: 'center',
          key: 'rules',
          scopedSlots: {
            customRender: 'rules',
          },
        },
        {
          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: [],
      triggerOptions: [],
      actionOptions: []
    }
  },
  mounted() {
    this.getList()
    this.getTriggerServiceOption()
    this.getActionServiceOption()
  },
  methods: {
    getTriggerServiceOption() {
      this.$ajax.post({
        url: this.$api.GET_TRIGGER_LIST,
      }).then(res => {
        if(res.code == '200') {
          let result = this.$com.confirm(res, 'data.content', [])
          for (let i = 0; i < result.length; i++) {
            this.triggerOptions.push(result[i])
          }
        }
      })
    },
    getActionServiceOption() {
      this.$ajax.post({
        url: this.$api.GET_ACTION_LIST,
      }).then(res => {
        if(res.code == '200') {
          let result = this.$com.confirm(res, 'data.content', [])
          for (let i = 0; i < result.length; i++) {
            this.actionOptions.push(result[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格式')
        }
      }
    },
    onDelete(id) {
      this.$ajax.delete({
        url: this.$api.DELETE_RULE_RECORD.replace('{id}', id)
      }).then(res => {
        if(res.code == '200') {
          this.$message.success('删除成功!')
          this.getList()
        }
      })
    },
    addRow() {
      this.rowLoop.push({
        name: '',
        key: ''
      })
    },
    deleteRow() {},
    getList() {
      this.$ajax.post({
        url: this.$api.GET_RULES_LIST
      }).then(res => {
        this.list = this.$com.confirm(res, 'data.content', [])
      })
    },
    pageChange(val) {
      this.pagination.pageNo = val
      this.pagination.current = val
      // this.getCompanyList()
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    onRegister() {
      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()

          this.$ajax.post({
            url: this.$api.POST_ADD_RULE_RECORD,
            params: formContent
          }).then(res => {
            if(res.code == '200') {
              this.$message.success('新增成功!')
              this.isShow = !this.isShow
              this.form.resetFields()
              this.getList()
            }
          })

        } else {
          this.$message.info('请填写表单所有项目！')
        }
      })
    }
  }
}
</script>

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