<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="站点类型">
          <el-select v-model="searchInfo.siteType" clearable placeholder="请选择">
            <el-option
              v-for="dict in dict.type.site_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchInfo.status" clearable placeholder="请选择">
            <el-option label="已处理" value="Processed" />
            <el-option label="未处理" value="Untreated" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
          <el-button class="excel-btn" size="small" type="primary" icon="el-icon-download" @click="handleExcelExport()">
            导出
          </el-button>
          <el-popover v-model:visible="deleteVisible" placement="top" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="deleteVisible = false">取消</el-button>
              <el-button size="mini" type="primary" @click="onDelete">确定</el-button>
            </div>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="multipleTable"
      border
      stripe
      style="width: 100%"
      tooltip-effect="dark"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="日期" width="180">
        <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
      </el-table-column>
      <el-table-column label="发布人" prop="oper" />
      <el-table-column label="站点" prop="siteName" />
      <el-table-column label="站点类型" prop="siteType">
        <template #default="scope">
          <dict-tag :options="dict.type.site_type" :value="scope.row.siteType" />
        </template>
      </el-table-column>
      <el-table-column label="已登录查阅次数" prop="count" />
      <el-table-column label="扣评分" prop="integral">
        <template #default="scope">{{ scope.row.integral/100 }}</template>
      </el-table-column>
      <el-table-column label="处理状态" prop="status">
        <template #default="scope">
          <el-tag v-show="scope.row.status == 'Untreated'" type="warning">未处理</el-tag>
          <el-tag v-show="scope.row.status == 'Processed'" type="warning" effect="dark">已处理待审核</el-tag>
          <el-tag v-show="scope.row.status == 'Success'" type="success" effect="dark">审核通过</el-tag>
          <el-tag v-show="scope.row.status == 'Error'" type="error" effect="dark">已审核未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="责任部门" prop="department">
        <template #default="scope">
          <span v-if="scope.row.department!=''">
            <span v-for="(item,i) in scope.row.department.split('|')" :key="i">{{ unitMap[item]+"、" }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            class="table-button"
            @click="updateProblemInfo(scope.row,false)"
          >查看详情
          </el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRow(scope.row)">删除</el-button>
          <el-button type="small" icon="el-icon-download" size="mini" @click="handlePdf(scope.row)">导出为pdf</el-button>
          <el-button type="small" icon="el-icon-s-comment" size="mini" @click="openUser(scope.row)">发送公众号通知</el-button>
          <el-button type="small" icon="el-icon-user" size="mini" @click="showReadInfo(scope.row)">已查阅详情</el-button>
          <el-button v-if="scope.row.status=='Processed'" type="warning" size="mini" @click="updateProblemInfo(scope.row,true)">待审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <el-dialog v-model="noticeList" title="选择通知人" width="500px" append-to-body>
      <el-form v-model="noticeUser" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择通知人" :rules="{required: true, message: '请选择通知人'}">
              <el-select
                v-model="noticeUser.userList"
                filterable
                clearable
                multiple
                size="small"
                style="width: 240px"
              >
                <el-option
                  v-for="id in Object.keys(userIds)"
                  :key="id"
                  :label="userIds[id]"
                  :value="id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendUser">确 定</el-button>
        <el-button @click="closeSend">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-model="dialogVisibleRead"
      title="已阅详情"
      width="30%"
    >
      <div style="text-align: center;padding-bottom: 20px">
        <span>{{ readMsg }}</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeRead">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog id="problemInfo" ref="problemInfo" v-model="dialogFormVisible" :before-close="closeDialog" :title="isAudit?'审核':'问题详情'">
      <el-form :model="formData" label-position="right" label-width="80px">
        <el-card class="box-card">
          <el-descriptions title="基本信息" border :column="2">
            <el-descriptions-item label="发布人">{{ formData.oper }}</el-descriptions-item>
            <el-descriptions-item label="站点名称">{{ formData.siteName }}</el-descriptions-item>
            <el-descriptions-item label="站点位置">{{ formData.position }}</el-descriptions-item>
            <el-descriptions-item label="站点类型"><dict-tag :options="dict.type.site_type" :value="formData.siteType " /></el-descriptions-item>
            <el-descriptions-item label="处理状态">
              <el-tag v-show="formData.status == 'Untreated'" type="warning">未处理</el-tag>
              <el-tag v-show="formData.status == 'Processed'" type="warning" effect="dark">已处理待审核</el-tag>
              <el-tag v-show="formData.status == 'Success'" type="success" effect="dark">审核通过</el-tag>
              <el-tag v-show="formData.status == 'Error'" type="error" effect="dark">已审核未通过</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="责任部门">
              <template #default="scope">
                <span v-for="(item,i) in formData.department.split('|')" :key="i">{{ unitMap[item] }}</span>
              </template>
            </el-descriptions-item>
            <el-descriptions-item label="处理时限" prop="HandAt">
              <template #default="scope">{{ formatDate(formData.HandAt) }}</template>
            </el-descriptions-item>
            <el-descriptions-item label="扣评分">{{ formData.integral/100 }}</el-descriptions-item>
            <el-descriptions-item span="2" label="问题备注">{{ formData.remark }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card v-show="replyList.length>0" class="box-card">
          <div class="el-descriptions__header el-descriptions__title">问题批示</div>
          <el-table border stripe :data="replyList" style="width: 100%">
            <el-table-column label="头像" prop="headerImg">
              <template #default="scope">
                <div :style="{'textAlign':'center'}">
                  <CustomPic :pic-src="scope.row.headerImg" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="昵称" prop="nickName" />
            <el-table-column label="批示内容" prop="replyMsg" />
            <el-table-column label="批示时间" prop="CreatedAt">
              <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
            </el-table-column>
            <el-table-column>
              <template #default="scope">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteReplyRow(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card class="box-card">
          <el-descriptions title="问题列表" :column="1" direction="vertical">
            <el-descriptions-item v-for="item in formData.matter.split('|')">
              {{ matterList[item] != undefined ? matterList[item] : '' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card class="box-card">
          <el-descriptions title="问题图片/视频" direction="vertical">
            <el-descriptions-item label="问题图片(点击图片查看更多)">
              <el-image
                style="width: 260px; height: 240px"
                :src="(formData.imgList.length>0?formData.imgList[0]:'')"
                :preview-src-list="formData.imgList"
              />
            </el-descriptions-item>
            <el-descriptions-item label="问题视频">
              <span v-show="formData.video.length<1">无视频</span>
              <video
                v-show="formData.video.length>0"
                style="object-fit:fill"
                controls
                width="400"
                height="240"
                :src="formData.video"
              >
                您的浏览器不支持Video标签。
              </video>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card v-show="formData.status=='Processed'" class="box-card">
          <el-descriptions title="处理结果" :column="1" border direction="vertical">
            <el-descriptions-item label="处理人">{{ formData.handler }}</el-descriptions-item>
            <el-descriptions-item label="处理内容">{{ formData.handText }}</el-descriptions-item>
            <el-descriptions-item label="处理图片(点击图片查看更多)" content-class-name="audit">
              <el-image
                style="width: 260px; height: 240px"
                :src="(formData.handImgList.length>0?formData.handImgList[0]:'')"
                :preview-src-list="formData.handImgList"
              />
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card v-show="formData.remark1||isAudit" class="box-card">
          <el-descriptions title="审核" border column="1">
            <el-descriptions-item v-if="isAudit">
              <el-button type="success" @click="auditUpdate(true)">审核通过</el-button>
              <el-button type="danger" :disabled="!(formData.remark1!=null&&formData.remark1.length>0)" @click="auditUpdate(false)">审核不通过</el-button>
            </el-descriptions-item>
            <el-descriptions-item label="审核不通过原因"><el-input
              v-model="formData.remark1"
              :readonly="!isAudit"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 5}"
              placeholder="请输入审核不通过理由"
            /></el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  createProblemInfo,
  deleteProblemInfo,
  deleteProblemInfoByIds,
  updateProblemInfo,
  findProblemInfo,
  getProblemInfoList,
  exportExcel, sendUserProblemInfo, getReadCountList, updateProblemInfoAudit
} from '@/api/problemInfo' //  此处请自行替换地址
import {
  deleteProblemReply,
  getProblemReplyList
} from '@/api/problemReply' //  此处请自行替换地址
import CustomPic from '@/components/customPic/index.vue'
import infoList from '@/mixins/infoList'
import { getDict } from '@/utils/dictionary'
import { getUserPList } from '@/api/user'
import { getUnitList } from '@/api/unit'

export default {
  name: 'ProblemInfo',
  components: { CustomPic },
  mixins: [infoList],
  dicts: ['site_type'],
  data() {
    return {
      listApi: getProblemInfoList,
      dialogFormVisible: false,
      type: '',
      siteType: [],
      noticeList: false,
      userIds: {},
      dialogVisibleRead: false,
      readMsg: '',
      noticeUser: {
        userList: []
      },
      isAudit: false,
      sendId: 0,
      deleteVisible: false,
      multipleSelection: [],
      matterList: [],
      replyList: [],
      unitMap: {},
      formData: {
        oper: 0,
        handler: 0,
        imgs: '',
        imgList: [],
        handImgList: [],
        HandAt: '',
        video: '',
        siteId: 0,
        position: '',
        matter: '',
        siteType: '',
        remark1: '',
        remark: '',
        status: '',
        handImgs: '',
        handText: '',
        department: '',
      }
    }
  },
  async created() {
    this.siteType = await getDict('site_type')
    await this.getTableData()
    await this.getUnitList()
  },
  methods: {
    handleExcelExport() {
      exportExcel(this.formData)
    },
    // 条件搜索前端看此方法
    onSubmit() {
      this.page = 1
      this.pageSize = 10
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getUnitList() {
      const params = {
        page: 1,
        pageSize: 99999999,
      }
      getUnitList(params).then(res => {
        if (res.code == 0) {
          res.data.list.forEach((unit, index) => {
            this.unitMap[unit.ID.toString()] = unit.unitName
          })
        }
      })
    },
    deleteRow(row) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteProblemInfo(row)
      })
    },
    deleteReplyRow(row) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProblemReply({ ID: row.ID }).then(res => {
          this.closeDialog()
          this.updateProblemInfo({ ID: row.problemId })
        })
      })
    },
    async handlePdf(row) {
      const href = window.location.origin
      const params = `/#/proInfo?Id=${row.ID}`
      window.open(href + params, '_blank', 'width=1200,height=1000,location=no,toolbar=no,status=no,scrollbars=yes,titlebar=no,')
    },
    async openUser(row) {
      this.sendId = row.ID
      this.noticeList = true
      getUserPList({ page: 1, pageSize: 9999 }).then(res => {
        for (const user in res.data.list) {
          this.userIds[res.data.list[user].ID] = res.data.list[user].userName
        }
      })
    },
    sendUser() {
      sendUserProblemInfo({ ID: this.noticeUser.userList, ProblemID: this.sendId }).then(res => {
        console.log(res)
        this.closeSend()
      })
    },
    closeSend() {
      this.noticeList = false
      this.userIds = {}
      this.noticeUser.userList = []
      this.sendId = 0
    },
    showReadInfo(row) {
      getReadCountList({ page: 1, pageSize: 9999, problemId: row.ID }).then(res => {
        this.dialogVisibleRead = true
        this.readMsg = ''
        for (const read in res.data.list) {
          this.readMsg = this.readMsg.concat(res.data.list[read].userName + ':' + res.data.list[read].count + '次、')
        }
      })
    },
    closeRead() {
      this.dialogVisibleRead = false
      this.readMsg = ''
    },
    async onDelete() {
      const ids = []
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      this.multipleSelection &&
      this.multipleSelection.map(item => {
        ids.push(item.ID)
      })
      const res = await deleteProblemInfoByIds({ ids })
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        if (this.tableData.length === ids.length && this.page > 1) {
          this.page--
        }
        this.deleteVisible = false
        this.getTableData()
      }
    },
    auditUpdate(isAudit) {
      updateProblemInfoAudit({ ID: this.formData.ID, status: (isAudit ? 'Success' : 'Error'), remark1: this.formData.remark1 }).then(res => {
        console.log(res)
        this.isAudit = false
        this.closeDialog()
        this.getTableData()
      })
    },
    async updateProblemInfo(row, isAudit) {
      const res = await findProblemInfo({ ID: row.ID })
      this.type = 'update'
      this.isAudit = isAudit
      if (res.code === 0) {
        await getProblemReplyList({ page: 1, pageSize: 9999, problemId: row.ID }).then(res => {
          this.replyList = res.data.list
        })
        this.formData = res.data.reproblemInfo
        if (this.formData.imgs.length > 0) {
          this.formData.imgList = this.formData.imgs.split('|')
        } else {
          this.formData.imgList = []
        }
        if (this.formData.handImgs.length > 0) {
          this.formData.handImgList = this.formData.handImgs.split('|')
        } else {
          this.formData.handImgList = []
        }
        const temp = res.data.reproblemInfo.matterList
        for (const index in temp) {
          this.matterList[temp[index].ID] = temp[index].problem
        }
        this.dialogFormVisible = true
      }
    },
    closeDialog() {
      const video = document.getElementById('video')
      if (video != undefined) {
        video.pause()
      }
      this.dialogFormVisible = false
      this.formData = {
        oper: 0,
        handler: 0,
        imgs: '',
        video: '',
        siteId: 0,
        imgList: [],
        position: '',
        matter: '',
        remark: '',
        handImgList: [],
        siteType: '',
        status: '',
        handImgs: '',
        handText: '',
        department: '',
      }
    },
    async deleteProblemInfo(row) {
      const res = await deleteProblemInfo({ ID: row.ID })
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.getTableData()
      }
    },
    async enterDialog() {
      let res
      switch (this.type) {
        case 'create':
          res = await createProblemInfo(this.formData)
          break
        case 'update':
          res = await updateProblemInfo(this.formData)
          break
        default:
          res = await createProblemInfo(this.formData)
          break
      }
      if (res.code === 0) {
        this.$message({
          type: 'success',
          message: '创建/更改成功'
        })
        this.closeDialog()
        this.getTableData()
      }
    },
    openDialog() {
      this.type = 'create'
      this.dialogFormVisible = true
    }
  },
}
</script>

<style>
.box-card {
  margin-bottom: 10px;
}
</style>
