<template>
  <div class="app-container">

    <el-tabs v-model="activeName" @tab-click="handleTabChange">
      <el-tab-pane label="正常" :name="State.NORMAL"></el-tab-pane>
      <el-tab-pane label="停用" :name="State.STOP"></el-tab-pane>
    </el-tabs>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input size="small" v-model="queryParams.title" placeholder="请输入标题" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="接收人" prop="groupId">
        <el-select v-model="queryParams.groupId" size="small" clearable @keyup.enter.native="handleQuery"
          placeholder="请选择接收人">
          <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </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:push:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-search" size="mini" :disabled="single" @click="viewDetailButton"
          v-hasPermi="['system:push:export']">详情
        </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:push: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:push:remove']">删除
        </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:push:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table ref="table" v-loading="loading" :data="pushList" @selection-change="handleSelectionChange"
      @row-click="rowClick">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="center" v-if="columns[0].visible" prop="title" show-overflow-tooltip />
      <el-table-column label="类型" align="center" prop="messageType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_notice_type" :value="scope.row.messageType"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" v-if="columns[1].visible" prop="createTime" width="200"
        show-overflow-tooltip />
      <el-table-column label="创建人" align="center" v-if="columns[2].visible" prop="createBy" width="200"
        show-overflow-tooltip />
      <el-table-column label="接收人" align="center" v-if="columns[3].visible" prop="groupName" width="200"
        show-overflow-tooltip>
        <!-- <template slot-scope="scope">
          <span>{{ resolveRole(scope.row.receivePacket) }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="状态" align="center" v-if="columns[4].visible" prop="state" width="200">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" active-value="0" inactive-value="1"
            @change="handleChangeState(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" v-if="columns[5].visible" width="200"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-user" @click="getReceiveList(scope.row)"
            v-hasPermi="['system:push:edit']">接收人列表
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:push:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:push:remove']">删除
          </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="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input size="small" v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接收人" prop="groupId">
              <el-select size="small" v-model="form.groupId" placeholder="请选择角色" style="width: 100%;">
                <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="类型" prop="messageType">
              <el-select v-model="form.messageType" style="width: 100%;">
                <el-option v-for="dict in dict.type.sys_notice_type" :key="dict.value" :value="dict.value"
                  :label="dict.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="内容" prop="content">
              <editor v-model="form.content" :min-height="192" />
            </el-form-item>
          </el-col>
        </el-row>
      </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="viewDetail" width="960px" append-to-body>
      <el-card type="always">
        <div style="text-align: center">
          <h1 style="display: inline-block">{{ form.title }}</h1>
        </div>
        <span class="info-container" :disabled="true" v-html="form.content"></span>
        <br /><br />
        <div style="float: right;">
          <el-descriptions column="3">
            <!--          <el-descriptions-item label="标题">{{ form.title }}</el-descriptions-item>-->
            <el-descriptions-item label="接收人">{{ resolveRole(form.receivePacket) }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ form.createTime }}</el-descriptions-item>
            <el-descriptions-item label="创建人">{{ form.createBy }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <br>

      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="viewDetail = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 导出对话框 -->
    <ExportTable :open-export.sync="exportOptions.open" :title="exportOptions.title" @export="exportFile"></ExportTable>
  </div>
</template>

<script>
import {
  getList,
  getInfoOne,
  addInfo,
  editInfo,
  deleteInfo,
  changeState
} from "@/api/smartSchool/informationPush/school";
import { State } from "@/enums/infoPush";
// import { getUser } from "@/api/system/user";
import { ExportType } from "@/enums/common";
import {
  getUserList,//获取分组集合

} from "@/api/smartSchool/informationPush/personnelGrouping";
export default {
  name: "SchoolMessage",
  dicts: ['status', 'inform_push_state', 'receive_packet', 'sys_notice_type'],
  data() {
    return {
      selection: [],
      pageState: '0',
      // 状态
      State,
      viewDetail: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学校消息推送表格数据
      pushList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        groupId: null,
        state: State.NORMAL,
        // content: null,
        // messageType: null,
      },
      // 导出选项
      exportOptions: {
        title: '选择导出类别',
        open: false
      },
      //分组
      idList: [],
      // 表单参数
      form: {},
      // 列信息
      columns: [
        { key: 0, label: `标题`, visible: true },
        { key: 1, label: `创建时间`, visible: true },
        { key: 2, label: `创建人`, visible: true },
        { key: 3, label: `接收人`, visible: true },
        { key: 4, label: `状态`, visible: true },
        { key: 5, label: `操作`, visible: true },
      ],
      // 表单校验
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" }
        ],
        receivePacket: [
          { required: true, message: "接收人不能为空", trigger: "blur" }
        ],
        messageType: [
          { required: true, message: "类型不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
      },
      // 当前状态
      activeName: State.NORMAL,
      // 角色列表
      roleList: []
    };
  },
  computed: {
    resolveRole() {
      return value => {
        const result = this.roleList.find(item => item.roleId === value);
        return result ? result.roleName : '';
      }
    }
  },
  created() {
    this.getList();
    // this.getRoleList();
    this.groupList();
  },
  methods: {


    //接收人分组
    groupList() {
      getUserList().then(response => {
        this.roleList = response.rows;
        console.log('this.roleList', this.roleList);
        this.total = response.total;
        this.loading = false;
      });

    },

    /** 查询学校消息推送列表 */
    getList() {
      this.loading = true;
      getList(this.queryParams).then(response => {
        this.pushList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        receivePacket: null,
        messageType: '1',
        state: State.STOP,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.throttle(() => {
        this.queryParams.pageNum = 1;
        this.getList();
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = 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 = "添加学校消息推送";
    },

    getReceiveList(row) {
      this.$router.push({
        path: '/schoolManage/infoPush/receiveList',
        query: {
          id: row.id,
          // title: row.title,
          // type: row.messageType,
        }
      })
    },


    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      this.open = true;
      this.title = "修改学校消息推送";
      getInfoOne(id).then(response => {
        this.form = response.data;
        console.log('this.form', this.form);
      });
    },
    /** 提交按钮 */
    submitForm() {
      const groupId = this.form.groupId
      this.form.groupName = groupId == '' ? '' : this.roleList.find(item => item.id == groupId).name
      console.log(this.form.borrowBy);
      this.throttle(() => {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.$modal.loading('正在上传数据，请稍等...');
            if (this.form.id != null) {
              editInfo(this.form).then(response => {
                this.$modal.closeLoading();
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch(error => {
                this.$modal.closeLoading();
              })
            } else {
              addInfo(this.form).then(response => {
                this.$modal.closeLoading();
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch(error => {
                this.$modal.closeLoading();
              })
            }
          }
        });
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.throttle(() => {
        const ids = row.id || this.ids;
        if (ids) {
          this.$modal.confirm(`是否确认删除选中的${Object.hasOwnProperty.call(ids, 'length') ? ids.length : 1}条数据？`).then(function () {
            return deleteInfo(ids);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {
          });
        }

      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.exportOptions.open = true;
      // this.$confirm(`是否确认导出${ !!this.ids.length ? this.ids.length + '条' : '所有' }数据？`, '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   if (this.ids.length) {
      //     console.log("this.ids", this.ids)
      //     this.download('/schoolMessagePush/export/' + this.ids, {
      //       ...this.queryParams
      //     }, `学校信息推送.xlsx`)
      //   } else {
      //     this.download('/schoolMessagePush/export/', {
      //       ...this.queryParams
      //     }, `学校信息推送.xlsx`)
      //   }
      //   this.$message({
      //     type: 'success',
      //     message: '导出成功!'
      //   });
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消'
      //   });
      // });
    },
    viewDetailButton() {
      this.viewDetail = true;
      this.reset();
      const id = this.ids[0];
      getInfoOne(id).then(response => {
        this.form = response.data;
      });
    },

    /** 停用/推送消息 */
    handleChangeState(row) {
      let text = row.state === "0" ? "推送" : "停用";
      this.$modal.confirm('确认要' + text + '当前通知(公告)？').then(function () {
        return changeState(row.id, row.state);
        return Promise.reject();
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      }).catch(function () {
        row.state = row.state === "0" ? "1" : "0";
      });
    },

    // 切换状态
    handleTabChange({ name }) {
      if (name == State.NORMAL) {
        this.pageState = 0
      } else {
        this.pageState = 1
      }
      this.queryParams.state = name;
      this.handleQuery();
    },

    // 获取角色信息
    // getRoleList() {
    //   getUser().then(response => {
    //     this.roleList = response.roles;
    //   }).catch(error => {
    //   })
    // },
    /** 导出 */
    exportFile(callback) {
      const ids = this.ids;
      const options = [
        { type: ExportType.TOTAL, path: '/schoolMessagePush/exportAll', params: { state: this.pageState } },
        { type: ExportType.SELECT, path: '/schoolMessagePush/export/' + ids, params: {} },
        {
          type: ExportType.QUERY, path: '/schoolMessagePush/exportAll', params: {
            state: this.pageState,
            ...this.queryParams
          }
        },
      ]
      callback(options, `学校信息推送${new Date().getTime()}.xlsx`);
    },
    rowClick(row) {
      if (this.selection.includes(row)) {
        this.$refs.table.toggleRowSelection(row, false)
      } else {
        this.$refs.table.toggleRowSelection(row, true)
      }
    }

  }
};
</script>

<style lang="scss" scoped>
.info-container {
  max-height: 500px;
  overflow-y: auto;
}
</style>
