<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" label-width="80px" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="标题" prop="dutyName">
        <el-input size="small" v-model="queryParams.dutyName" placeholder="请输入标题" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="节日" prop="holidayName">
        <el-input size="small" v-model="queryParams.holidayName" placeholder="请输入节日" clearable
                  @keyup.enter.native="handleQuery"/>
      </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="info" plain icon="el-icon-search" size="mini" :disabled="single" @click="viewDetailButton"-->
    <!--                   v-hasPermi="['system:push:export']">详情-->
    <!--        </el-button>-->

    <!--      </el-col>-->
    <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="listDuty"></right-toolbar>-->
    <!--    </el-row>-->

    <el-table v-loading="loading" :data="pushList" height="550px" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" type="index" align="center"/>
      <el-table-column label="标题" align="center" prop="dutyName" show-overflow-tooltip/>
      <el-table-column label="类型" prop="dutyType" align="center">
        <template v-slot="scope">
          {{ getDutyType(scope.row.dutyType) }}
        </template>
      </el-table-column>
      <el-table-column label="节日" prop="holidayName" align="center"/>
      <el-table-column label="说明" min-width="110" prop="remarks" align="center"/>
      <el-table-column label="操作" align="center" width="100"
                       class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="redirectDutyInfo(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="listDuty"/>
    <!--    <div style="width: 150px; margin: auto">-->
    <!--      <el-button type="primary" plain icon="el-icon-close" size="small" style="width: 150px" @click="handleClose">关闭-->
    <!--      </el-button>-->
    <!--    </div>-->

    <!-- 查看详细内容学校消息推送对话框 -->
    <el-dialog title="详细内容查看" :visible.sync="viewDetail" width="1500px" append-to-body>
      <el-card type="always">
        <el-row type="flex" justify="center" :gutter="10">
          <h1>{{ dutyList.dutyName }}</h1>
        </el-row>
        <el-row>
          <el-col>
            <h3>填报单位：东营市二中</h3>
          </el-col>
        </el-row>

        <el-table key="a" v-if="dutyList.dutyType==='1'" size="small" height="550px" border v-loading="loading2"
                  :data="dutyList.list"
                  :span-method="objectSpanMethod">
          <el-table-column label="节日" align="center">
            <template slot-scope="scope">
              {{ dutyList.holidayName }}
            </template>
          </el-table-column>
          <el-table-column label="日期" align="center" prop="dutyDeDate"/>
          <el-table-column label="星期" align="center" prop="dutyDeWeek"/>
          <el-table-column label="行政值班" align="center">
            <el-table-column label="值班人员" align="center" prop="adminPerson"/>
            <el-table-column label="值班电话" align="center" min-width="100px" prop="adminTel"/>
            <el-table-column label="手机" align="center" min-width="100px" prop="adminPhone"/>
          </el-table-column>
          <el-table-column label="办公室值班" align="center">
            <el-table-column label="人员" align="center" prop="officerPerson"/>
            <el-table-column label="值班电话" align="center" min-width="100px" prop="officerTel"/>
            <el-table-column label="手机" align="center" min-width="150px" prop="officerPhone"/>
          </el-table-column>
          <el-table-column label="门卫值班" align="center">
            <el-table-column label="人员" min-width="200px" align="center" prop="guardPerson"/>
            <el-table-column label="值班电话" align="center" min-width="150px" prop="guardTel"/>
            <el-table-column label="手机" align="center" min-width="150px" prop="guardPhone"/>
          </el-table-column>
          <el-table-column label="学生宿舍值班" align="center">
            <el-table-column label="人员" align="center" min-width="200px" prop="dormPerson"/>
            <el-table-column label="手机" align="center" min-width="150px" prop="dormPhone"/>
          </el-table-column>
        </el-table>

        <el-table key="b" v-else border size="small" height="500px" v-loading="loading2" :data="dutyList.list"
                  :span-method="objectSpanMethod">
          <el-table-column label="节日" align="center">
            <template slot-scope="scope">
              {{ dutyList.holidayName }}
            </template>
          </el-table-column>
          <el-table-column label="日期" align="center" prop="dateAndWeek" width="180"/>
          <el-table-column label="带班领导" align="center" prop="leader"/>
          <el-table-column label="职务" align="center" prop="postName"/>
          <el-table-column label="电话" align="center" min-width="150px" prop="dutyDeTel"/>
          <el-table-column label="手机" align="center" min-width="150px" prop="dutyDePhone"/>
          <el-table-column label="值班人员、手机" align="center" min-width="130px" prop="personAndPhone"/>
        </el-table>
        <div style="margin-top: 20px;margin-left: 50px">说明： {{ dutyList.remarks }}</div>
        <!--        </el-card>-->

        <!--        <el-descriptions title="内容"></el-descriptions>-->
        <!--        <span class="info-container" :disabled="true" v-html="form.content"></span>-->
      </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 {
  listDuty,
  getDuty,
  addDuty,
  updateDuty,
  delDuty,
  infoPublish,
  infoWithdraw
} from '@/api/smartSchool/schoolManage/dutyManage/index'
import {State} from '@/enums/infoPush'
import {getUser} from '@/api/system/user'
import {ExportType} from '@/enums/common'
import {getDutyDetail} from "../../../../api/smartSchool/schoolManage/dutyManage";

export default {
  name: 'index',
  dicts: ['status', 'inform_push_state', 'receive_packet', 'sys_notice_type', 'dutytype'],
  data() {
    return {
      // 导出选项
      exportOptions: {
        title: '选择导出类别',
        open: false
      },
      // 状态
      State,
      viewDetail: false,
      // 遮罩层
      loading: true,
      loading2: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      dutyList: {},

      showSearch: true,
      // 总条数
      total: 0,
      // 学校消息推送表格数据
      pushList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dutyName: null,
        dutyType: null,
        holidayName: null,
        messageType: null,
        state: State.STOP
      },
      // 表单参数
      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}
      // ],
      // 当前状态
      activeName: State.NORMAL,
      // 角色列表
      roleList: []
    }
  },
  computed: {
    resolveRole() {
      return value => {
        const result = this.roleList.find(item => item.roleId === value)
        return result ? result.roleName : ''
      }
    }
  },
  created() {
    this.listDuty()
    this.getRoleList()
  },
  methods: {
    /** 查询学校消息推送列表 */
    listDuty() {
      this.loading = true
      listDuty(this.queryParams).then(response => {
        this.pushList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 0) {
        if (rowIndex % this.dutyList.list.length === 0) {
          return {
            rowspan: this.dutyList.list.length,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    async redirectDutyInfo(rowData) {
      this.viewDetail = true
      this.reset()
      this.loading2 = true
      // console.log(rowData,column,e)
      this.viewDuty = true
      let fetchRes = (await getDutyDetail(rowData.id, rowData.dutyType)).data
      console.log(fetchRes)
      this.dutyList = {
        ...fetchRes,
        dutyType: rowData.dutyType,
        holidayName: rowData.holidayName
      }
      this.loading2 = false
    },
    getDutyType(dutyType) {
      if (this.dict.type.dutytype.length != 0) {
        for (let i = 0; i < this.dict.type.dutytype.length; i++) {
          let item = this.dict.type.dutytype[i]
          if (dutyType == item.value) return item.label
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dutyName: null,
        dutyType: null,
        holidayName: null,
        state: State.STOP,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.throttle(() => {
        this.queryParams.pageNum = 1
        this.listDuty()
      })
    },
    /** 重置按钮操作 */
    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 = '添加学校消息推送'
    },
    /** 查看通知(公告)详情 */
    handleDetails(row) {
      const type = this.dict.type.sys_notice_type.find(item => item.value === row.messageType)
      this.$router.push({
        path: '/school/info-details/' + row.id,
        query: {
          title: row.title,
          type: type ? type.label : '',
          role: row.receivePacket
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      this.open = true
      this.title = '修改学校消息推送'
      getDuty(id).then(response => {
        this.form = response.data
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.throttle(() => {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.$modal.loading('正在上传数据，请稍等...')
            if (this.form.id != null) {
              updateDuty(this.form)
                .then(response => {
                  this.$modal.closeLoading()
                  this.$modal.msgSuccess('修改成功')
                  this.open = false
                  this.listDuty()
                })
                .catch(error => {
                  this.$modal.closeLoading()
                })
            } else {
              addDuty(this.form)
                .then(response => {
                  this.$modal.closeLoading()
                  this.$modal.msgSuccess('新增成功')
                  this.open = false
                  this.listDuty()
                })
                .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 delDuty(ids)
            })
            .then(() => {
              this.listDuty()
              this.$modal.msgSuccess('删除成功')
            })
            .catch(() => {
            })
        }
      })
    },
    /** 导出 */
    exportFile(callback) {
      const ids = this.ids
      const options = [
        {type: ExportType.TOTAL, path: '/schoolMessagePush/exportAll', params: {}},
        {type: ExportType.SELECT, path: '/schoolMessagePush/export/' + ids, params: {}},
        {type: ExportType.QUERY, path: '/schoolMessagePush/exportAll', params: this.queryParams}
      ]
      callback(options, `学校信息推送${new Date().getTime()}.xlsx`)
    },
    /** 导出按钮操作 */
    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(() => {
      // });
    },
    viewDetailButton(row) {
      this.viewDetail = true
      this.reset()
      const id = row.id || this.ids[0]
      getDuty(id).then(response => {
        this.form = response.data
      })
    },

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

    // 切换状态
    handleTabChange({name}) {
      this.queryParams.state = name
      this.handleQuery()
    },

    // 获取角色信息
    getRoleList() {
      getUser()
        .then(response => {
          this.roleList = response.roles
        })
        .catch(error => {
        })
    },

    /** 关闭 */
    handleClose() {
      // this.$tab.closeOpenPage({
      //   path: '/index'
      // })

      // 关闭当前页签，回到首页
      this.$tab.closePage();
    }
  }
}
</script>

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