<template>
  <el-dialog
    v-model="state.isShowDialog"
    draggable
    :close-on-click-modal="false"
    width="700px"
    top="5vh"
    destroy-on-close
  >
    <template #header>
      <div>
        <el-icon class="el-custom-dialog-icon">
          <Edit />
        </el-icon>
        <span>发布</span>
      </div>
    </template>
    <div class="app-container" style="min-height: 150px" v-loading="state.loading">
      <el-form ref="elFormRef" :model="state.form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型">
              <EnumSelect
                v-model="state.form.messageType"
                enum="MessageTypeEnum"
                style="width: 210px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布到">
              <el-select v-model="state.publishTo">
                <el-option :key="0" label="所有人" :value="0" />
                <el-option :key="1" label="自定义" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-row v-if="state.publishTo == 1">
          <el-col :span="24">
            <el-button type="primary" @click="() => userSelectDialogRef.openDialog()">
              添加
            </el-button>
            <el-table
              ref="tableRef"
              row-key="id"
              :data="state.tableData"
              border
              style="margin-top: 5px"
            >
              <el-table-column type="index" width="50">
                <template #default="scope">
                  {{ scope.$index + 1 + (state.pageParams.Page - 1) * state.pageParams.PageSize }}
                </template>
              </el-table-column>
              <el-table-column prop="userName" label="账号"></el-table-column>
              <el-table-column prop="realName" label="姓名"></el-table-column>
              <el-table-column prop="orgName" label="机构部门" />
              <el-table-column label="操作" align="left" width="80" show-overflow-tooltip>
                <template #default="scope">
                  <el-button
                    link
                    icon="Delete"
                    type="danger"
                    @click="handleDelete(scope.row.id)"
                    v-auth="'receivemessage:page'"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              style="margin-top: 10px"
              v-model:currentPage="state.pageParams.Page"
              v-model:page-size="state.pageParams.PageSize"
              :total="state.pageParams.Total"
              background
              layout="total, sizes,prev, pager, next"
              @size-change="handleQuery"
              @current-change="handleQuery"
              :page-sizes="[10, 20, 50, 100]"
            />
          </el-col>
        </el-row>
      </el-form>
      <UserSelectDialog ref="userSelectDialogRef" @selected="mergeSelected"></UserSelectDialog>
    </div>
    <template #footer>
      <div class="el-custom-dialog-footer">
        <el-button type="primary" @click="submit" :disabled="state.loading">确定</el-button>
        <el-button @click="() => (state.isShowDialog = false)" :disabled="state.loading">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { publishMessage } from '@/api/system/messageApi'
import EnumSelect from '@/views/system/components/enumSelect.vue'
import UserSelectDialog from '@/views/system/components/userSelectDialog.vue'

const emits = defineEmits(['onClose'])
const state = reactive({
  isShowDialog: false,
  form: {},
  loading: false,
  publishTo: 0,
  pageParams: {
    Page: 1,
    PageSize: 10,
    Total: 0
  },
  tableData: [],
  tableDataBak: []
})
const elFormRef = ref()
const userSelectDialogRef = ref()

const rules = {}
function openDialog(id) {
  resetForm()
  state.form.id = id
  state.isShowDialog = true
}

function resetForm() {
  state.form = {
    id: null,
    messageType: 0,
    userIds: []
  }
  state.publishTo = 0
  state.tableDataBak = []
  state.tableData = []
  state.pageParams.Total=0
  elFormRef.value?.resetFields()
}

function submit() {
  elFormRef.value.validate((valid) => {
    if (valid) {
      state.loading = true
      let postData = Object.assign({}, state.form)
      postData.userIds=state.tableDataBak.map((item) => item.id)
      publishMessage(postData)
        .then(() => {
          emits('onClose')
          ElMessage({
            message: '更新成功',
            type: 'success'
          })
          state.isShowDialog = false
        })
        .finally(() => (state.loading = false))
    }
  })
}

function mergeSelected(data) {
  //把数据合并进入 state.tableData 根据列userName 去重
  data.forEach((item) => {
    let isExist = state.tableDataBak.find((i) => i.userName === item.userName)
    if (!isExist) {
      state.tableDataBak.push(item)
    }
  })
  state.pageParams.Total= state.tableDataBak.length
  handleQuery()
}

function handleQuery() {
  state.loading = true
  //根据state.tableData 和 state.pageParams 进行分页显示
  state.tableData = state.tableDataBak.slice(
    (state.pageParams.Page - 1) * state.pageParams.PageSize,
    state.pageParams.Page * state.pageParams.PageSize
  )
  state.loading = false
}

function handleDelete(id) {
  state.tableData = state.tableData.filter((item) => item.id !== id)
}

defineExpose({
  openDialog
})
</script>
