<template>
  <a-card>
    <a-row>
      <a-col span="12">
        <a-row :gutter="[8, 8]" >
          <a-col> <a-input allowClear v-model:value="queryParamsState.label" placeholder="请输入通知名称"/>  </a-col>
          <a-col>
            <a-select
              allowClear
              style="width: 170px"
              v-model:value="queryParamsState.source"
              placeholder="请选择数据来源"
            >
              <a-select-option
                v-for="item in sourceList"
                :key="item.key"
                :value="item.key"
              >
                {{item.label}}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col>
            <a-button type="primary" @click="getNoticePage">搜索</a-button>
          </a-col>
        </a-row>

      </a-col>
      <a-col span="12" >
        <a-row justify="end" >
          <a-button type="primary" @click="openModal('add')" >新增</a-button>
        </a-row>
      </a-col>
    </a-row>
    <a-table
      style="margin-top: 20px;"
      :columns="columns"
      :data-source="state.dataSource"
      :loading="state.loading"
      :pagination="queryParamsState"
      @change="changePage"
    >
      <template #bodyCell="{column, record}">
        <template v-if="column.key === 'id'" >
          <a @click="openModal('update', record.id)" >{{record.id}}</a>
        </template>
        <template v-if="column.key === 'source'" >
          {{record.source == '0'?'消息通知':'告警'}}
        </template>
            <template v-if="column.key === 'status'" >
              <a-switch
                @click="changeStatus(record)"
                v-model:checked="record.status"
                checked-children="运行中"
                un-checked-children="已关闭"
              />
            </template>
            <template v-if="column.key === 'action'" >
              <a-space>
                <a @click="openModal('update', record.id)" >编辑</a>
                <a-popconfirm
                    title="确实要删除吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="delNotice(record.id)"
                  >
                  <a>删除</a>
                  </a-popconfirm>
              </a-space>
            </template>
      </template>
    </a-table>
  </a-card>

  <modal-pro
    :label="modalTitle"
    :open="state.visible"
    destroyOnClose
    @cancel="state.visible = false"
    @ok="ok"
  >
    <a-form :label-col="{span: 4}" :wrapper-col="{span: 14}">
      <a-form-item label="通知名称" v-bind="validateInfos.label">
        <a-input allowClear v-model:value="modalRef.label"  />
      </a-form-item>
      <a-form-item label="数据来源" >
        <a-radio-group v-model:value="modalRef.source">
          <a-radio :value="0">消息通知</a-radio>
          <a-radio :value="1">告警</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="状态" >
        <a-radio-group v-model:value="modalRef.status">
          <a-radio :value="true">启用</a-radio>
          <a-radio :value="false">停用</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="通知方式" >
        <a-select v-model:value="modalRef.notification.methodType" >
          <a-select-option
            :value="item"
            v-for="item in SysController.methodTypeList"
            :key="item"
          >
            {{item}}
          </a-select-option>
        </a-select>
      </a-form-item>
      <span v-if="modalRef.notification && modalRef.notification.methodType == 'EMAIL'" >
        <a-form-item label="发送者" >
          <a-input allowClear v-model:value="modalRef.notification.to"  />
        </a-form-item>
        <a-form-item label="抄送者" >
          <a-row :gutter="[8, 8]" >
            <a-col :span="24" v-for="(item, index) in modalRef.notification.cc" :key="index" >
              <a-space>
                <a-input allowClear style="width: 275px;" v-model:value="modalRef.notification.cc[index]"  />
                <a-button @click="modalRef.notification.cc.splice(index, 1)" danger >删除</a-button>
              </a-space>
            </a-col>
            <a-col>
              <a-button @click="modalRef.notification.cc.push('')" >添加</a-button>
            </a-col>
          </a-row>
        </a-form-item>
      </span>
      <span v-if="modalRef.notification && modalRef.notification.methodType != 'EMAIL'" >
        <a-form-item label="地址" >
          <a-input allowClear v-model:value="modalRef.notification.hookUrl"  />
        </a-form-item>
        <a-form-item label="请求方法" >
          <a-select allowClear v-model:value="modalRef.notification.hookMethod" >
            <a-select-option
              :value="item"
              v-for="item in ['POST', 'GET']"
              :key="item"
            >
              {{item}}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="请求头" >
          <a-row>
            <a-col
              :span="24"
              v-for="(item, index) in modalRef.notification.customHeaders"
              :key="index"
            >
              <a-space>
                <a-input-group size="large">
                  <a-row :gutter="8">
                    <a-col :span="12">
                      <a-input allowClear v-model:value="item.key" />
                    </a-col>
                    <a-col :span="12">
                      <a-input allowClear v-model:value="item.value" />
                    </a-col>
                  </a-row>
                </a-input-group>
                <a-button  @click="modalRef.notification.customHeaders.splice(index, 1)" danger >删除</a-button>
              </a-space>
            </a-col>
            <a-col :span="24">
              <a-button type="primary" @click="addCustomHeaders" >新增</a-button>
            </a-col>
          </a-row>
        </a-form-item>
      </span>
    </a-form>
  </modal-pro>
</template>

<script lang="ts" setup >
import { reactive, onMounted, computed } from 'vue'
import { SysController } from '@/controller'
import { Form } from 'ant-design-vue'

const useForm = Form.useForm

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '通知名称',
    dataIndex: 'label',
    key: 'label'
  },
  {
    title: '通知数据来源',
    dataIndex: 'source',
    key: 'source'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action'
  }
]

const sourceList = [{ key: 0, label: '通知' }, { key: 1, label: '告警' }]

const queryParamsState = reactive({
  page: 1,
  pageSize: 10,
  label: '',
  source: null
})

const state = reactive({
  dataSource: [],
  loading: false,
  visible: false,
  opraState: 'add'
})

const modalRef = reactive({
  id: '',
  label: '',
  source: 0,
  status: true,
  notification: {
    methodType: 'EMAIL',
    to: '',
    cc: [''],
    hookUrl: '',
    hookMethod: '',
    customHeaders: [{ key: '', value: '' }]
  }
})

// const customHeadersList = computed(() =>
//   Object.keys(modalRef.notification.customHeaders).map(key => {
//     return {
//       key,
//       value: modalRef.notification.customHeaders[key]
//     }
//   }))

const modalTitle = computed(() => state.opraState === 'add' ? '新增通知' : '编辑通知')

const { resetFields, validate, validateInfos } = useForm(modalRef, reactive({
  label: [{ required: true, message: '请填写通知名称' }]
}))

const ok = () => {
  validate().then(async () => {
    if (modalRef.notification.methodType === 'WEBHOOK') {
      const obj = {}
      modalRef.notification.customHeaders.forEach(item => {
        obj[item.key] = item.value
      })
      modalRef.notification.customHeaders = obj
    }
    state.opraState === 'add' ? await SysController.addNoticeMethod(modalRef) : await SysController.updateNoticeMethod(modalRef)
    state.visible = false
    getNoticePage()
  })
}

const addCustomHeaders = () => {
  console.log(modalRef.notification.customHeaders)

  modalRef.notification.customHeaders.push({ key: '', value: '' })
}

const openModal = (opraState: 'add' | 'update', id = '') => {
  resetFields()
  state.opraState = opraState
  state.visible = true
  modalRef.id = id
  if (opraState === 'update') {
    getNoticeById()
  }
}

const changePage = ({ current }) => {
  queryParamsState.page = current
  getNoticePage()
}

const delNotice = async (id: string) => {
  await SysController.delNotice(id)
  getNoticePage()
}

const changeStatus = async (record) => SysController.updateNoticeStaus({ id: record.id, status: record.status })

const getNoticeById = async () => {
  const { data } = await SysController.noticeById(modalRef.id)
  data.notification.customHeaders = Object.keys(data.notification.customHeaders).map(key => {
    return {
      key,
      value: data.notification.customHeaders[key]
    }
  })
  resetFields(data)
}

const getNoticePage = async () => {
  state.loading = true
  const { data } = await SysController.noticeMethodPage(queryParamsState)
  state.loading = false
  state.dataSource = data
}

onMounted(() => {
  getNoticePage()
})

</script>

<style lang="less" scoped >
</style>
