<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="通知标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入通知标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通知类型" prop="notificationType">
        <el-select v-model="queryParams.notificationType" placeholder="请选择通知类型" clearable>
          <el-option label="系统通知" value="system" />
        </el-select>
      </el-form-item>
      <el-form-item label="计划发送时间" prop="sendTime">
        <el-date-picker clearable
          v-model="queryParams.sendTime"
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择计划发送时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:notifications:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:notifications:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:notifications:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-user"
          size="mini"
          :disabled="single"
          @click="handleBindUsers"
        >绑定用户</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:notifications:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="notificationsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="通知标题" align="center" prop="title" />
      <el-table-column label="通知内容" align="center" prop="content" :show-overflow-tooltip="true" />
      <el-table-column label="通知类型" align="center" prop="notificationType">
        <template slot-scope="scope">
          <el-tag type="primary">系统通知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计划发送时间" align="center" prop="sendTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.sendTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:notifications:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:notifications:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleBindUsers(scope.row)"
          >绑定用户</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handlePublish(scope.row)"
          >发布通知</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通知对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入通知内容"/>
        </el-form-item>
        <el-form-item label="通知类型" prop="notificationType">
          <el-select v-model="form.notificationType" placeholder="请选择通知类型">
            <el-option label="系统通知" value="system" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划发送时间" prop="sendTime">
          <el-date-picker clearable
            v-model="form.sendTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择计划发送时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog title="选择用户" :visible.sync="userSelectOpen" width="800px" append-to-body>
      <el-form :model="userQueryParams" ref="userQueryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="用户昵称" prop="nickname">
          <el-input
            v-model="userQueryParams.nickname"
            placeholder="请输入用户昵称"
            clearable
            @keyup.enter.native="handleUserQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="userQueryParams.phone"
            placeholder="请输入手机号码"
            clearable
            @keyup.enter.native="handleUserQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-check"
            size="mini"
            @click="confirmBindUsers"
          >确认绑定</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-user"
            size="mini"
            @click="bindAllUsers"
          >绑定全部用户</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="userLoading" :data="userList" @selection-change="handleUserSelectionChange" ref="userTable">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="用户昵称" align="center" prop="nickname" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" prop="phone" />
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">
            <span v-if="scope.row.sex === 1">男</span>
            <span v-else-if="scope.row.sex === 2">女</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="danger">黑名单</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="VIP" align="center" prop="vip">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.vip === 1" type="warning">VIP</el-tag>
            <span v-else>普通用户</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="userTotal>0"
        :total="userTotal"
        :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize"
        @pagination="getUserList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listNotifications, getNotifications, delNotifications, addNotifications, updateNotifications, bindUsers, getBindUsers, publishNotification } from "@/api/notify/notifications"
import { listShopUser } from "@/api/member/shopuser"

export default {
  name: "Notifications",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      notificationsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示用户选择弹出层
      userSelectOpen: false,
      // 当前选中的通知ID
      currentNotificationId: null,
      // 用户列表数据
      userList: [],
      // 用户列表加载状态
      userLoading: false,
      // 用户列表选中数据
      userIds: [],
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        nickname: null,
        phone: null
      },
      // 用户总条数
      userTotal: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        notificationType: null,
        creator: null,
        sendTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "通知标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "通知内容不能为空", trigger: "blur" }
        ],
        notificationType: [
          { required: true, message: "通知类型不能为空", trigger: "change" }
        ],
        sendTime: [
          { required: true, message: "计划发送时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      listNotifications(this.queryParams).then(response => {
        this.notificationsList = response.rows
        this.total = parseInt(response.total) || 0
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        notificationType: "system",
        creator: null,
        sendTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加通知"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getNotifications(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改通知"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateNotifications(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addNotifications(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除通知编号为"' + ids + '"的数据项？').then(function() {
        return delNotifications(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/notifications/export', {
        ...this.queryParams
      }, `notifications_${new Date().getTime()}.xlsx`)
    },
    /** 绑定用户按钮操作 */
    handleBindUsers(row) {
      this.reset();
      const id = row.id || this.ids;
      if (!id) {
        this.$message.warning("请选择一条通知记录");
        return;
      }
      this.currentNotificationId = id;
      this.userSelectOpen = true;
      this.userIds = [];
      this.getUserList();
      // 注意：不需要在这里调用getBindUserList，因为在getUserList完成后会自动调用
    },

    /** 获取已绑定的用户列表 */
    getBindUserList(id) {
      getBindUsers(id).then(response => {
        if (response.data && response.data.length > 0) {
          console.log("已绑定用户列表:", response.data);
          
          // 将用户ID转换为字符串类型，确保类型一致
          const bindUserIds = response.data.map(user => String(user.userId));
          this.userIds = bindUserIds;
          
          console.log("转换后的用户ID列表:", bindUserIds);

          // 延迟执行，确保表格已经完全渲染
          setTimeout(() => {
            // 先清除所有选中状态
            if (this.$refs.userTable) {
              this.$refs.userTable.clearSelection();
              
              // 为已绑定的用户设置选中状态
              this.userList.forEach(row => {
                // 确保类型一致，都转换为字符串进行比较
                const rowUserId = String(row.userId);
                console.log("比较用户ID:", rowUserId, "是否在列表中:", bindUserIds.includes(rowUserId));
                
                if (bindUserIds.includes(rowUserId)) {
                  console.log("选中用户:", row);
                  this.$refs.userTable.toggleRowSelection(row, true);
                }
              });
            } else {
              console.error("userTable引用不存在");
            }
          }, 200); // 延迟200毫秒执行
        } else {
          console.log("没有已绑定的用户");
          // 清除所有选中状态
          if (this.$refs.userTable) {
            this.$refs.userTable.clearSelection();
          }
        }
      });
    },
    /** 获取用户列表 */
    getUserList() {
      this.userLoading = true;
      listShopUser(this.userQueryParams).then(response => {
        this.userList = response.rows;
        this.userTotal = parseInt(response.total) || 0;
        this.userLoading = false;

        // 在用户列表加载完成后，设置已选中的用户
        if (this.currentNotificationId) {
          this.getBindUserList(this.currentNotificationId);
        }
      });
    },
    /** 用户搜索按钮操作 */
    handleUserQuery() {
      this.userQueryParams.pageNum = 1;
      this.getUserList();
    },
    /** 用户重置按钮操作 */
    resetUserQuery() {
      this.resetForm("userQueryForm");
      this.handleUserQuery();
    },
    /** 用户多选框选中数据 */
    handleUserSelectionChange(selection) {
      this.userIds = selection.map(item => item.userId);
    },
    /** 确认绑定用户 */
    confirmBindUsers() {
      if (this.userIds.length === 0) {
        this.$message.warning("请选择要绑定的用户");
        return;
      }

      const userList = [];
      this.userIds.forEach(userId => {
        userList.push({
          userId: userId
        });
      });

      // 调用绑定用户接口
      bindUsers(this.currentNotificationId, userList).then(response => {
        this.$modal.msgSuccess("绑定用户成功");
        this.userSelectOpen = false;
      });
    },
    /** 绑定全部用户 */
    bindAllUsers() {
      this.$confirm('确认要绑定全部用户吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 获取所有用户并绑定
        listShopUser({ pageNum: 1, pageSize: 9999 }).then(response => {
          const userList = [];
          response.rows.forEach(user => {
            userList.push({
              userId: user.userId
            });
          });

          if (userList.length === 0) {
            this.$message.warning('没有可绑定的用户');
            return;
          }

          // 调用绑定用户接口
          bindUsers(this.currentNotificationId, userList).then(response => {
            this.$modal.msgSuccess("绑定全部用户成功");
            this.userSelectOpen = false;
          });
        });
      }).catch(() => {});
    },

    /** 发布通知按钮操作 */
    handlePublish(row) {
      const id = row.id || this.ids;
      if (!id) {
        this.$message.warning("请选择一条通知记录");
        return;
      }

      this.$confirm('确认要发布该通知吗？发布后将向所有绑定的用户推送消息', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        publishNotification(id).then(response => {
          this.$modal.msgSuccess(response.msg || "发布成功");
          this.getList();
        });
      }).catch(() => {});
    }
  }
}
</script>
