<template>
  <div class="hc-system-announcement-box">
    <div class="card-body">
      <div class="card-main">
        <div class="header">
          <div class="title">
            <div style="width: 140px">
              <el-select v-model="searchForm.msgType" class="block" clearable filterable placeholder="请选择公告类型"
                size="small">
                <el-option label="更新公告" value="1"></el-option>
                <el-option label="普通公告" value="2"></el-option>
              </el-select>
            </div>
            <div style="width: 100px; margin-left: 12px; margin-right: 12px;">
              <el-select v-model="searchForm.pushStatus" class="block" clearable filterable placeholder="发布状态"
                size="small">
                <el-option label="待发布" value="1"></el-option>
                <el-option label="已发布" value="2"></el-option>
                <el-option label="已取消" value="3"></el-option>
              </el-select>
            </div>
            <el-button size="small" type="primary" @click="searchClick">搜索</el-button>
          </div>
          <div class="extra">
            <el-badge :value="releasedNum" style="margin-right: 18px;">
              <el-button size="small" @click="releasedShow">待发布</el-button>
            </el-badge>
            <el-button size="small" type="primary" @click="generalShow">发布普通公告</el-button>
            <el-button size="small" type="warning" @click="systemUpdateShow">发布系统公告</el-button>
            <el-button size="small" type="danger" @click="handleDelete">批量删除公告</el-button>
          </div>
        </div>
        <div class="content" v-loading="isLoading">
          <el-table ref="tableRef" :data="tableData" border style="width: 100%;" height="100%"
            @selection-change="tableSelection">
            <el-table-column type="selection" width="50" align="center" fixed="left"></el-table-column>
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column prop="msgType" label="公告类型" width="100" align="center">
              <template slot-scope="{row}">
                <span v-if="row.msgType === 1">更新公告</span>
                <span v-if="row.msgType === 2">普通公告</span>
              </template>
            </el-table-column>
            <el-table-column prop="pushSystem" label="推送系统" min-width="220"></el-table-column>
            <el-table-column prop="msgContent" label="公告内容" min-width="240"></el-table-column>
            <el-table-column prop="pushRemark" label="发布备注"></el-table-column>
            <el-table-column prop="pushDateTime" label="发布时间" width="160" align="center"></el-table-column>
            <el-table-column prop="pushDateTime" label="时间配置" width="340">
              <template slot-scope="{row}">
                <template v-if="row.msgType === 1">
                  <span>剩余</span>
                  <el-tag type="danger" size="mini">{{ row.msgWarnTime }}分钟</el-tag>
                  <span>进行提醒，</span>
                  <el-tag type="danger" size="mini">{{ row.msgCountDownTime }}分钟</el-tag>
                  <span>开始进入倒计时</span>
                </template>
                <template v-else>
                  <span>-</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="creatUserName" label="创建人" width="100"></el-table-column>
            <el-table-column prop="cancelDateTime" label="取消时间" width="160" align="center"></el-table-column>
            <el-table-column prop="pushStatus" label="发布状态" width="80" align="center">
              <template slot-scope="{row}">
                <el-tag type="danger" effect="dark" size="mini" v-if="row.pushStatus === 3">已取消</el-tag>
                <el-tag type="success" effect="dark" size="mini" v-if="row.pushStatus === 2">已发布</el-tag>
                <el-tag type="info" effect="dark" size="mini" v-if="row.pushStatus === 1">待发布</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="action" label="操作" width="180" align="center" fixed="right">
              <template slot-scope="{row}">
                <el-button size="mini" @click="handleEdit(row)" :disabled="row.pushStatus !== 3">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleCancel(row)"
                  :disabled="row.pushStatus !== 1">取消发布</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="action">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="searchForm.current" :page-sizes="[20, 30, 40, 50]" :page-size="searchForm.size"
            layout="total, prev, pager, next, sizes, jumper" :total="searchForm.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!--待发布-->
    <el-dialog class="hc-system-announcement-dialog black-card" title="待发布的公告" :visible.sync="isReleasedShow"
      append-to-body center destroy-on-close width="660px" @closed="releasedCancel">
      <el-divider content-position="left" class="hc-system-announcement-black-divider top"
        v-if="releasedData.updateMsg.length > 0">更新公告</el-divider>
      <div class="hc-system-announcement-black-card" v-for="(item, index) in releasedData.updateMsg" :key="index">
        <div class="icon-box">
          <div class="name">{{ index === 0 ? '前 端' : '后 端' }}</div>
          <div class="icon">
            <i class="iconfont iconicon_notice"></i>
          </div>
        </div>
        <div class="content">
          <div class="top-box">
            <div class="left">
              <span class="name">待发布：</span>
              <span class="num">{{ item.awaitMsgTotal }}</span>
            </div>
            <div class="right">
              <span class="name">创建人：</span>
              <span class="user">{{ item.creatUserName }}</span>
            </div>
          </div>
          <div class="time-box">
            <span class="name">发布时间：</span>
            <span class="time">{{ item.pushDateTime }}</span>
          </div>
        </div>
      </div>
      <el-divider content-position="left" class="hc-system-announcement-black-divider"
        v-if="releasedData.systemMsg.length > 0">普通公告</el-divider>
      <div class="hc-system-announcement-black-card" v-for="(item, index) in releasedData.systemMsg" :key="index">
        <div class="icon-box">
          <div class="name">公 告</div>
          <div class="icon">
            <i class="iconfont iconicon_notice"></i>
          </div>
        </div>
        <div class="content">
          <div class="top-box">
            <div class="left">
              <span class="name">待发布：</span>
              <span class="num">{{ item.awaitMsgTotal }}</span>
            </div>
            <div class="right">
              <span class="name">创建人：</span>
              <span class="user">{{ item.creatUserName }}</span>
            </div>
          </div>
          <div class="time-box">
            <span class="name">发布时间：</span>
            <span class="time">{{ item.pushDateTime }}</span>
          </div>
        </div>
      </div>
    </el-dialog>

    <!--发布普通公告-->
    <el-dialog class="hc-system-announcement-dialog w-700px" title="发布普通公告" :visible.sync="isGeneralShow" width="700px"
      append-to-body center destroy-on-close @closed="generalCancel">
      <el-form :model="generalFormModel" :rules="generalFormRules" ref="generalFormRef"
        class="hc-system-announcement-form" label-width="auto">
        <el-form-item label="公告内容：" prop="msgContent">
          <el-input type="textarea" v-model="generalFormModel.msgContent" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="发布备注：" prop="pushRemark">
          <el-input type="textarea" v-model="generalFormModel.pushRemark"></el-input>
        </el-form-item>
        <el-form-item label="发布配置：" prop="pushDateTime">
          <el-date-picker v-model="generalFormModel.pushDateTime" type="datetime" placeholder="选择日期时间"
            :picker-options="pickerOptions" format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="停留时间：" prop="msgShowTime">
          <el-select v-model="generalFormModel.msgShowTime" clearable filterable style="width: 190px;">
            <el-option v-for="i in 60" :label="`${i}分钟`" :value="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="涉及系统：" prop="pushSystem">
          <el-checkbox-group v-model="generalFormModel.pushSystem">
            <el-checkbox v-for="item in systemClinet" :label="item.clientId">{{ item.name ||
              item.clientId }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="generalCancel">取消</el-button>
        <el-button type="primary" :loading="releasedLoading" @click="generalFormSubmit">发布</el-button>
      </div>
    </el-dialog>

    <!--发布系统公告-->
    <el-dialog class="hc-system-announcement-dialog h-full w-700px" title="发布系统公告" :visible.sync="isSystemUpdateShow"
      width="700px" append-to-body center destroy-on-close @closed="systemUpdateCancel">
      <el-form :model="updateFormModel" :rules="updateFormRules" ref="updateFormRef" class="hc-system-announcement-form"
        label-width="auto">
        <el-form-item label="公告内容：" prop="msgContent">
          <el-input type="textarea" v-model="updateFormModel.msgContent" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="发布备注：" prop="pushRemark">
          <el-input type="textarea" v-model="updateFormModel.pushRemark"></el-input>
        </el-form-item>
        <el-form-item label="更新类型：" prop="updateServerType">
          <el-checkbox-group v-model="updateFormModel.updateServerType">
            <el-checkbox label="1">前端页面</el-checkbox>
            <el-checkbox label="2">后端接口</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="更新原因：" prop="updateCodeType">
          <el-radio-group v-model="updateFormModel.updateCodeType">
            <el-radio label="1">新功能需求</el-radio>
            <el-radio label="2">bug修复</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布配置：" prop="pushDateTime">
          <el-date-picker v-model="updateFormModel.pushDateTime" type="datetime" placeholder="选择日期时间"
            :picker-options="pickerOptions" format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="时间配置：" prop="msgWarnTime">
          <span>剩余</span>
          <span style="margin-left: 5px">
            <el-select v-model="updateFormModel.msgWarnTime" clearable filterable size="small" style="width: 90px;"
              placeholder="分钟">
              <el-option v-for="i in 60" :label="`${i}分钟`" :value="i"></el-option>
            </el-select>
          </span>
          <span style="margin-left: 5px">进行提醒，</span>
          <span style="margin-left: 5px">
            <el-select v-model="updateFormModel.msgCountDownTime" clearable filterable size="small" style="width: 90px;"
              placeholder="时间">
              <el-option v-for="i in 60" :label="`${i}分钟`" :value="i"></el-option>
            </el-select>
          </span>
          <span style="margin-left: 5px">开始进入倒计时</span>
        </el-form-item>
        <el-form-item label="涉及系统：" prop="pushSystem">
          <el-checkbox-group v-model="updateFormModel.pushSystem">
            <el-checkbox v-for="item in systemClinet" :label="item.clientId">{{ item.name ||
              item.clientId }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="systemUpdateCancel">取消</el-button>
        <el-button type="primary" :loading="releasedLoading" @click="updateFormSubmit">发布</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import '@/styles/announcement.scss'
import { getList, getAwaitMsg, getClinetAll, add, update, cancelPush, remove } from "@/api/system/announcement";
export default {
  data() {
    return {
      //搜索
      searchForm: { current: 1, size: 20, total: 0 },
      //公告列表
      isLoading: false,
      tableData: [],
      tableMultiple: [],
      //待发布
      releasedLoading: false, // 发布按钮loading状态
      isReleasedShow: false,
      releasedNum: 0,
      releasedData: {
        systemMsg: [],
        updateMsg: []
      },
      //普通公告
      isGeneralShow: false,
      generalFormModel: {
        pushSystem: [],
      },
      generalFormRules: {
        msgContent: [
          { required: true, message: '请填写公告内容', trigger: 'blur' }
        ],
        pushDateTime: [
          { required: true, message: '请选择发布配置', trigger: 'blur' }
        ],
        msgShowTime: [
          { required: true, message: '请选择停留时间', trigger: 'blur' }
        ],
        pushSystem: [
          { required: true, message: '请选择涉及系统', trigger: 'blur' }
        ]
      },
      //系统更新
      isSystemUpdateShow: false,
      updateFormModel: {
        updateServerType: [],
        pushSystem: [],
        msgContent: '【系统维护公告】为提升系统安全性及运行效率，系统将于今日（(需填写更新时间)）进行更新升级，请您提前保存好工作数据。维护期间系统将暂停访问，给您带来不便，敬请谅解！如有疑问，请联系系统工作人员处理。'
      },
      updateFormRules: {
        msgContent: [
          { required: true, message: '请填写公告内容', trigger: 'blur' }
        ],
        updateServerType: [
          { required: true, message: '请选择更新类型', trigger: 'blur' }
        ],
        updateCodeType: [
          { required: true, message: '请选择更新原因', trigger: 'blur' }
        ],
        pushDateTime: [{
          required: true, trigger: 'blur',
          validator: (rule, value, callback) => {
            const { msgCountDownTime } = this.updateFormModel
            if (!value) {
              callback(new Error('请选择剩余进行提醒时间'));
            } else if (!msgCountDownTime) {
              callback(new Error('请选择进入倒计时时间'));
            } else {
              callback();
            }
          }
        }],
        msgWarnTime: [
          { required: true, message: '请选择时间配置', trigger: 'blur' }
        ],
        pushSystem: [
          { required: true, message: '请选择涉及系统', trigger: 'blur' }
        ]
      },
      systemClinet: [],
      //日期时间
      pickerOptions: {
        shortcuts: [{
          text: '三分钟',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3 * 60 * 1000);
            picker.$emit('pick', date);
          }
        }, {
          text: '五分钟',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 5 * 60 * 1000);
            picker.$emit('pick', date);
          }
        }, {
          text: '十分钟',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 10 * 60 * 1000);
            picker.$emit('pick', date);
          }
        }, {
          text: '三十分钟',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 30 * 60 * 1000);
            picker.$emit('pick', date);
          }
        }]
      },
    }
  },
  created() {
    this.searchClick()
    this.getAwaitMsgApi()
  },
  methods: {
    //获取待发布公告
    async getAwaitMsgApi() {
      let _this = this
      getAwaitMsg().then(({ data }) => {
        const { msgTotal, systemMsg, updateMsg } = data.data || {}
        _this.releasedData = {
          systemMsg: systemMsg,
          updateMsg: updateMsg
        }
        _this.releasedNum = msgTotal
      })
    },
    handleSizeChange(val) {
      this.searchForm.size = val
    },
    handleCurrentChange(val) {
      this.searchForm.current = val
    },
    //搜索
    searchClick() {
      this.searchForm.current = 1
      this.getTableData()
    },
    //获取表格数据
    async getTableData() {
      this.isLoading = true
      const res = await getList(this.searchForm)
      const { code, data, msg } = res.data || {}
      const { records, total } = data || {}
      this.tableData = records
      this.searchForm.total = total
      if (code !== 200) {
        this.$message.error(msg);
      }
      this.isLoading = false
    },
    //表格多选
    tableSelection(val) {
      this.tableMultiple = val
    },
    //表格编辑
    handleEdit(row) {
      const form = JSON.parse(JSON.stringify(row));
      if (form.msgType === 1) {
        form.updateServerType = form.updateServerType.split(',')
        form.pushSystem = form.pushSystem.split(',')
        this.updateFormModel = form
        this.systemUpdateShow()
      } else {
        form.pushSystem = form.pushSystem.split(',')
        this.generalFormModel = form
        this.generalShow()
      }
    },
    //表格删除
    async handleDelete() {
      const arr = this.tableMultiple
      if (arr.length <= 0) {
        this.$message.warning('请先勾选数据');
        return
      }
      //判断是否满足条件
      const result = arr.every(({ pushStatus }) => {
        return pushStatus === 3
      })
      if (!result) {
        this.$message.error('请选择已取消的数据');
        return
      }
      const ids = arr.flat().map(item => item.id).join(',');
      remove(ids).then(({ data }) => {
        this.$message.success(data.msg || '操作成功');
        this.tableMultiple = []
        this.searchClick()
        this.getAwaitMsgApi()
      })
    },
    //取消发布
    handleCancel(row) {
      cancelPush(row.id).then(({ data }) => {
        this.$message.success(data.msg || '操作成功');
        this.searchClick()
        this.getAwaitMsgApi()
      })
    },
    //待发布打开
    releasedShow() {
      this.isReleasedShow = true
    },
    //待发布关闭
    releasedCancel() {
      this.isReleasedShow = false
    },
    //打开普通公告
    generalShow() {
      this.isGeneralShow = true
      this.getClinetAllApi()
    },
    //获取应用列表
    async getClinetAllApi() {
      const res = await getClinetAll()
      const { data } = res.data || []
      this.systemClinet = data
    },
    async generalFormSubmit() {
      const isForm = await this.getFormValidate('generalFormRef')
      if (!isForm) return
      let form = JSON.parse(JSON.stringify(this.generalFormModel))
      form.pushSystem = form.pushSystem.join(',')
      form.msgType = 2
      this.releasedLoading = true
      if (form.id) {
        const { data } = await update(form)
        if (data.code === 200) {
          this.$message.success(data.msg || '操作成功');
          this.generalCancel()
          this.searchClick()
          this.getAwaitMsgApi()
        }

      } else {
        const { data } = await add(form)
        if (data.code === 200) {
          this.$message.success(data.msg || '操作成功');
          this.generalCancel()
          this.searchClick()
          this.getAwaitMsgApi()
        }
      }
      this.releasedLoading = false
    },
    //普通公告关闭
    generalCancel() {
      this.isGeneralShow = false
      this.generalFormModel = {
        pushSystem: []
      }
    },
    //系统更新公告
    systemUpdateShow() {
      this.isSystemUpdateShow = true
      this.getClinetAllApi()
    },
    //系统更新公告提交
    async updateFormSubmit() {
      const isForm = await this.getFormValidate('updateFormRef')
      if (!isForm) return
      let form = JSON.parse(JSON.stringify(this.updateFormModel))
      form.pushSystem = form.pushSystem.join(',')
      form.updateServerType = form.updateServerType.join(',')
      form.msgType = 1
      this.releasedLoading = true
      if (form.id) {
        const { data } = await update(form)
        if (data.code === 200) {
          this.$message.success(data.msg || '操作成功');
          this.systemUpdateCancel()
          this.searchClick()
          this.getAwaitMsgApi()
        }
      } else {
        const { data } = await add(form)
        if (data.code === 200) {
          this.$message.success(data.msg || '操作成功');
          this.systemUpdateCancel()
          this.searchClick()
          this.getAwaitMsgApi()
        }
      }
      this.releasedLoading = false
    },
    //系统更新公告关闭
    systemUpdateCancel() {
      this.isSystemUpdateShow = false
      this.updateFormModel = {
        updateServerType: [],
        pushSystem: []
      }
    },
    //验证表单
    async getFormValidate(ref) {
      return new Promise(resolve => {
        if (!ref) {
          resolve(false)
          return
        }
        this.$refs[ref].validate((valid) => {
          resolve(!!valid)
        });
      })
    }
  },
}
</script>
