<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :tableEvents="tableEvents"
    :optionsEvensGroup="optionsEvensGroup"
    :operation="operation()"
    :tableAttributes="tableAttributes"
    :columnParsing="columnParsing"
  >
   <!-- 新增 -->
   <el-dialog
      title="新增"
      :visible.sync="mainFormDialog"
      :show-close="false"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form ref="mainForm" :model="mainForm" :rules="mainFormRules" label-position="right" label-width="90px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="通知类型" prop="type">
              <el-input v-model="mainForm.type" placeholder="请输入通知类型"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="文件编号" prop="code">
              <el-input v-model="mainForm.code" placeholder="请输入文件编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="文件标题" prop="title">
              <el-input v-model="mainForm.title" placeholder="请输入文件标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="来源" prop="source">
              <el-input v-model="mainForm.source" placeholder="请输入来源"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="发布日期" prop="date">
              <el-date-picker
                v-model="mainForm.date"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
                placeholder="选择发布日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="发布内容" prop="content">
              <el-input
                type="textarea"
                v-model="mainForm.content"
                placeholder="请输入发布内容"
                :autosize="{ minRows: 4, maxRows: 8 }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="接收人" prop="department">
              <el-tree
                :data="departmentList"
                show-checkbox
                node-key="adminWebsitId"
                ref="tree"
                highlight-current
                :props="props"
              >
              </el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="上传附件" prop="fileUrl">
          <ImageUpload :fileList="fileList" :multiple="true" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeMainForm">取 消</el-button>
        <el-button type="primary" @click="submitMainForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 已阅记录 -->
    <el-dialog
      title="已阅记录"
      :visible.sync="recordDialog"
      :show-close="false"
      width="70%"
      :close-on-click-modal="false"
    >
      <div class="table" style="margin: 10px 0 20px">
        <el-table
          v-loading="detailTable_listLoading"
          :data="detailTable_dataList"
          element-loading-text="Loading"
          tooltip-effect="dark"
          style="width: 100%"
          max-height="270"
        >
          <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
          <el-table-column
            align="center"
            prop="title"
            label="标题"
            min-width="140"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column align="center" prop="websitNumber" label="网点名称" min-width="140" show-overflow-tooltip>
            <template slot-scope="scope"> {{ scope.row.websitName }}({{ scope.row.websitNumber }}) </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="remark"
            label="备注"
            min-width="140"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column align="center" prop="createTime" label="下载时间" min-width="160"></el-table-column>
        </el-table>
      </div>
      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @current-change="detailTableCurrentChange"
            :current-page="detailTable_currentPage"
            :page-size="detailTable_pageSize"
            background
            layout="prev, pager, next"
            :total="detailTable_listTotal"
          >
          </el-pagination>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="recordDialog = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog title="浏览" :visible.sync="detailDialog" width="60%" :close-on-click-modal="false">
      <div class="detail-container">
        <div class="title">{{ detailData.title }}</div>
        <div class="text">
          发布人：{{ detailData.issueNickName }}<el-divider direction="vertical"></el-divider>发布时间：{{
            detailData.issueTime
          }}
        </div>
        <el-divider></el-divider>
        <div class="content">{{ detailData.content }}</div>
        <el-divider v-if="detailData.files && detailData.files.length > 0"></el-divider>
        <div class="file" v-if="detailData.files && detailData.files.length > 0">
          <div>附件：</div>
          <div class="file-list">
            <div v-for="(item, index) in detailData.files" :key="index" class="item">
              <el-image
                v-if="checkFileType(item.url) == 'image'"
                class="img"
                :src="imageURL + item.url"
                :preview-src-list="[imageURL + item.url]"
              ></el-image>
              <div v-else class="box2" @click="openLink(item.url)">
                <img src="@/assets/common/word.png" v-if="checkFileType(item.url) == 'word'" />
                <img src="@/assets/common/excel.png" v-if="checkFileType(item.url) == 'excel'" />
                <img src="@/assets/common/ppt.png" v-if="checkFileType(item.url) == 'ppt'" />
                <img src="@/assets/common/pdf.png" v-if="checkFileType(item.url) == 'pdf'" />
                <div class="name ellipsis-3">{{ item.name }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmCheck(detailData.id)" v-if="!detailData.readFlag">确认接收</el-button>
        <el-button @click="detailDialog = false" v-if="detailData.readFlag">关 闭</el-button>
      </div>
    </el-dialog>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import add_callback_mixin from '@/components/template/add_callback_mixin.js'
import Popu from '@/components/template/popu.vue'
import {
  getListV2,
  getDownloadList,
  deleteData,
  addData,
  getDepartmentList,
  getDetail,
  confirmCheck
} from '@/api/notice'
import { getFileUrl } from '@/api/common'
import ImageUpload from '@/components/Common/image-upload.vue'
export default {
  components: { TemplatePage, Popu, ImageUpload },
  mixins: [import_mixin, add_callback_mixin],
  data() {
    return {
      visible: false,
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.openMainForm()
              })
              // isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量删除',
              click: async () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                let ids = this.recordSelected.map(v => {
                  return v.id
                })
                let params = ids
                await deleteData({ id: params.join(',') })
                this.$refs.pageRef.refreshList()
                this.$message.success('批量删除成功')
              }
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      }, // 关闭新增弹窗

      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],
      imageURL: this.$imageUrl,
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      screenForm: {
        // 筛选表单数据
        type: '',
        code: '',
        title: '',
        date: []
      },
      mainForm: {
        type: '',
        code: '',
        title: '',
        source: '',
        department: '',
        date: '',
        content: ''
      },
      mainFormRules: {
        type: [{ required: true, message: '请输入通知类型', trigger: 'blur' }],
        title: [{ required: true, message: '请输入文件标题', trigger: 'blur' }],
        date: [{ required: true, message: '请选择发布日期', trigger: 'change' }],
        content: [{ required: true, message: '请输入发布内容', trigger: 'blur' }]
      },
      mainFormDialog: false,
      fileList: [],
      isCollapse: true,
      departmentList: [],
      props: {
        multiple: true,
        value: 'adminWebsitId',
        label: 'name',
        children: 'children'
      },

      detailDialog: false, // 详情 - 弹窗
      detailData: {},

      multipleSelection: [],

      recordDialog: false, // 已阅记录 - 弹窗
      detailTable_dataList: null, // 已阅记录 - 列表数据
      detailTable_listLoading: true, // 已阅记录 - 列表加载loading
      detailTable_currentPage: 1, // 已阅记录 - 当前页码
      detailTable_pageSize: 10, // 已阅记录 - 每页数量
      detailTable_listTotal: 0 // 已阅记录 - 列表总数
    }
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      this.recordSelected = []
      return getListV2(...p)
    },
    // 列表导出函数
    exportList: () => {},
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      console.log(data);
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {this.checkBtnRole('edit') ? (
              <el-button
                size="mini"
                type="text"
                onClick={() => {
                  this.openDetail(row.id)
                }}
              >
                浏览
              </el-button>
            ) : null}
            <el-popconfirm

              title="确定删除吗？"
              onConfirm={() => this.deleteData(row.noticeId)}
            >
              <el-button slot="reference" type="text" size="mini">
                删除
              </el-button>
            </el-popconfirm>
          </div>
        )
      }
    },
    handleClose() {
      this.addOff(() => {
        this.visible = false
      })()
    },
    // 查询按钮权限
    checkBtnRole(value) {
      return true
      let btnRole = this.$route.meta.roles
      if (!btnRole) {
        return true
      }
      let index = btnRole.indexOf(value)
      return index >= 0 ? true : false
    },

    // 获取部门列表
    getTree() {
      getDepartmentList().then(res => {
        this.departmentList = res.data
      })
    },

    // 批量删除
    batchDelete() {
      if (this.multipleSelection.length < 1) {
        return this.$errorMsg('请选择信息')
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let ids = []
          this.multipleSelection.forEach(item => {
            ids.push(item.noticeId)
          })
          deleteData({ noticeIds: ids.join(',') }).then(res => {
            this.$successMsg('删除成功')
            this.$refs.pageRef.refreshList()
          })
        })
        .catch(() => {})
    },

    // 操作 - 删除
    deleteData(id) {
      deleteData({ noticeIds: id }).then(res => {
        this.$successMsg('删除成功')
        this.$refs.pageRef.refreshList()
      })
    },

    // 详情 - 打开弹窗
    openDetail(id) {
      getDetail({ id, isTopRead:true }).then(res => {
        this.detailData = res.data
        this.detailDialog = true
      })
    },

    // 检查文件类型
    checkFileType(url) {
      if (!url) return ''
      const fileSuffix = url.substring(url.lastIndexOf('.') + 1)

      if (['jpg', 'jpeg', 'png'].includes(fileSuffix)) {
        return 'image'
      } else if (['doc', 'docx', 'dot', 'wps', 'wpt'].includes(fileSuffix)) {
        return 'word'
      } else if (['xls', 'xlsx', 'xlt', 'et', 'ett'].includes(fileSuffix)) {
        return 'excel'
      } else if (['ppt', 'pptx', 'dps', 'dpt', 'pot', 'pps'].includes(fileSuffix)) {
        return 'ppt'
      } else if (['pdf'].includes(fileSuffix)) {
        return 'pdf'
      } else {
        return ''
      }
    },

    // 打开链接
    openLink(url) {
      getFileUrl({ key: url }).then(res => {
        window.open(res.data)
      })
    },

    // 确认查收
    confirmCheck(id) {
      confirmCheck({ noticeIds: id }).then(res => {
        this.$successMsg('查收成功')
        this.detailDialog = false
        this.$refs.pageRef.refreshList()
      })
    },

    // 已阅记录 - 获取列表
    getDownloadList() {
      getDownloadList({
        pageNo: this.detailTable_currentPage,
        pageSize: this.detailTable_pageSize,
        id: this.recordId
      }).then(res => {
        this.detailTable_dataList = res.data.records
        this.detailTable_listTotal = res.data.total
        this.detailTable_listLoading = false
      })
    },

    // 已阅记录 - 打开弹窗
    openRecord(id) {
      this.recordId = id
      this.recordDialog = true
      this.detailTable_currentPage = 1
      this.getDownloadList()
    },

    // 已阅记录 - 更改列表当前页
    detailTableCurrentChange(val) {
      this.detailTable_currentPage = val
      this.getDownloadList()
    },

    // 打开 表单
    openMainForm() {
      this.getTree()
      this.mainFormDialog = true
    },

    // 关闭 表单
    closeMainForm() {
      this.addOff(() => {
        this.mainFormDialog = false
      })()
      this.fileList = []
      this.$refs.mainForm.resetFields()
    },

    // 提交 表单
    async submitMainForm() {
      this.$refs.mainForm.validate(valid => {
        if (valid) {
          let params = {
            type: this.mainForm.type,
            code: this.mainForm.code,
            title: this.mainForm.title,
            source: this.mainForm.source,
            issueTime: this.mainForm.date,
            content: this.mainForm.content,
            adminWebsitIds: this.$refs.tree.getCheckedKeys(),
            files: this.fileList
          }
          addData(params).then(res => {
            this.closeMainForm()
            this.$refs.pageRef.refreshList()

            this.mainFormDialog = false
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  .title {
    font-size: 16px;
    color: #333333;
    font-weight: 600;
  }
  .text {
    font-size: 14px;
    color: #999999;
    margin-top: 10px;
  }
  .content {
    font-size: 14px;
    color: #666666;
    line-height: 20px;
  }
  .file {
    .file-list {
      display: flex;
      .item {
        margin-top: 10px;
        margin-right: 10px;
      }
    }
    .img {
      width: 80px;
      height: 80px;
      display: block;
      border: 1px solid #e4e7ed;
    }
    .box2 {
      flex: 1;
      display: flex;
      padding: 10px;
      align-items: center;
      border: 1px solid #e4e7ed;
      width: 240px;
      height: 80px;
      cursor: pointer;
      img {
        width: 40px;
        height: 40px;
        display: block;
      }
      .name {
        flex: 1;
        color: #222;
        font-weight: 600;
        margin-left: 10px;
      }
    }
  }
}
.el-divider--horizontal {
  margin: 16px 0;
}
</style>
