<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.id)">编辑</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" centered destroyOnClose @cancel='cancelModal()'>
            <a-form :form='form' style="height: 300px; overflow-y: scroll">
              <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-row>
                  <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="7">
                        <a-form-item>
                          <a-input
                            v-decorator="[
                              'key' + index,
                              {
                                validateTrigger: 'blur',
                                rules: [{ required: true, message: '请填写此项！' }]
                              }
                            ]"
                          />
                        </a-form-item>
                      </a-col>

                      <a-col :span="7" 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="4" offset="1">
                        <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>
                  </a-col>
                </a-row>
            </a-form>
          <template slot="footer">
            <a-button key="back" @click="cancelModal()">
              取消
            </a-button>
            <a-button type="primary" @click="handleRegisterOk()">
              完成
            </a-button>
          </template>
        </a-modal>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rowLoop: [{
        key: '',
        value: '',
        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: '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',
          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: [],
      editId: null
    }
  },
  mounted() {
    this.getList()
    this.getTriggerServiceOption()
    this.getActionServiceOption()
  },
  methods: {
    onEdit(id) {
      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++) {
          if(Object.keys(record)[i] == 'trigger') {
            this.form.getFieldDecorator('trigger', {'initialValue': Object.values(record)[i].id})
          }

          if(Object.keys(record)[i] == 'action') {
            this.form.getFieldDecorator('action', {'initialValue': Object.values(record)[i].id})
          }

          if(Object.keys(record)[i] == 'rules') {
            for (let j = 0; j < Object.values(record)[i].length; j++) {
              if(j !== 0) {
                this.addRow()
              }
              console.log(Object.values(record)[i][j].key)
              this.form.getFieldDecorator('key' + j, {'initialValue': Object.values(record)[i][j].key})
              this.form.getFieldDecorator('value' + j, {'initialValue': Object.values(record)[i][j].value})
            }
          }

          // if(Object.keys(record)[i] == 'rules') {
          //   this.form.getFieldDecorator('rules', {'initialValue': JSON.stringify(Object.values(record)[i])})
          // }
        }
      }
    },
    getTriggerServiceOption() {
      this.$ajax.post({
        url: this.$api.GET_TRIGGER_LIST,
        params: {
          'page': 1,
          'size': 10000
        }
      }).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,
        params: {
          'page': 1,
          'size': 10000
        }
      }).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])
          }
        }
      })
    },
    cancelModal() {
      console.log(123)
      this.rowLoop = [{
        key: '',
        value: '',
        randomNum: Math.random()
      }],
      this.form.resetFields()
      this.isShow = !this.isShow
    },
    initPagination() {
      this.pagination.pageNo = 1
      this.pagination.current = 1
    },
    confirmJson(rule, value, callback) {
      if (!value || value == undefined) {
        callback('不能为空!')
      } else if(typeof value == 'string') {
        try {
          let obj=JSON.parse(value)

          console.log(obj)
          if(typeof obj == 'object' && obj ){
            callback()
          } else {
            callback('不是有效的JSON格式')
          }
        } catch(e) {
          callback('不是有效的JSON格式')
        }
      }
    },
    onDelete(id) {

      const that = this
      this.$modal.confirm({
        title: '提示',
        content: '确定删除该条记录吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.$ajax.delete({
            url: that.$api.DELETE_RULE_RECORD.replace('{id}', id)
          }).then(res => {
            if(res.code == '200') {
              that.$message.success('删除成功!')
              that.initPagination()
              that.getList()
            }
          })
        },
      })
    },
    addRow() {
      this.rowLoop.push({
        key: '',
        value: '',
        randomNum: Math.random()
      })
    },
    deleteRow(randomNum) {
      this.rowLoop = this.rowLoop.filter(i => i.randomNum !== randomNum)
    },
    getList() {
      this.$ajax.post({
        url: this.$api.GET_RULES_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()
    },
    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) {

          const formContent = this.form.getFieldsValue()

          const trigger = this.triggerOptions.find(item => item.id == formContent.trigger)

          const action = this.actionOptions.find(item => item.id == formContent.action)

          let paramsJson = []

          for (let i = 0; i < this.rowLoop.length; i++) {
            paramsJson.push({
              key: formContent['key' + i],
              value: formContent['value' + i]
            })
          }

          if(!!this.editId) {
            this.$ajax.put({
              url: this.$api.PUT_RULE_RECORD.replace('{id}', this.editId),
              params: {
                rules: paramsJson,
                trigger,
                action
              }
            }).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_RULE_RECORD,
              params: {
                rules: paramsJson,
                trigger,
                action
              }
            }).then(res => {
              if(res.code == '200') {
                this.$message.success('新增成功!')
                this.isShow = !this.isShow
                this.form.resetFields()
                this.getList()
              }
            })
          }

          this.editId = null

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

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