<template>
  <div class="div_main">
    <div class="div_search">
      <el-form :inline="true"
               :model="formData"
               ref="ref_searchform"
               :label-width="'90px'">
        <div>

          <el-form-item label="姓名"
                        prop="name">
            <el-input v-model="formData.name"
                      size="small"
                      class="list_item_width_1"
                      clearable
                      placeholder="请输入姓名">
            </el-input>

          </el-form-item>
          <el-form-item label="手机号"
                        prop="mobile">
            <el-input v-model="formData.mobile"
                      size="small"
                      class="list_item_width_1"
                      clearable
                      placeholder="请输入手机号">
            </el-input>

          </el-form-item>

          <el-form-item label="身份证"
                        prop="mobile">
            <el-input v-model="formData.idCard"
                      size="small"
                      class="list_item_width_1"
                      clearable
                      placeholder="请输入身份证">
            </el-input>

          </el-form-item>

          <el-form-item label="接种针次"
                        prop="vaccinationCount">
            <el-select class="list_item_width_1"
                       v-model.trim="formData.vaccinationCount"
                       placeholder="请选择"
                       clearable>
              <el-option v-for="item in veroNumList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>

          </el-form-item>

          <el-button style="margin-left:30px"
                     size="small"
                     class="diy-button--search"
                     @click="handleSearch">查询</el-button>
          <el-button style="margin-left:10px"
                     size="small"
                     class="diy-button--reset"
                     @click="resetSearch">重置</el-button>
        </div>
      </el-form>
    </div>
    <div class="div_table">
      <div class="div_btn">
        <el-button class="diy-button--add"
                   size="small"
                   @click="handleAdd">新增</el-button>

        <el-button style="float:left"
                   class="diy-button--export"
                   size="small"
                   @click="handleExportModule">下载模板</el-button>
        <el-upload ref="upload"
                   :multiple='false'
                   :show-file-list='false'
                   :before-upload="beforeUpload"
                   action=""
                   accept=".xlsx"
                   :limit="1"
                   :on-exceed="handleExceed"
                   :http-request="uploadFile">
          <el-button style="margin-left:10px"
                     size="small"
                     class="diy-button--delete">导入</el-button>
        </el-upload>

        <el-button style="float:left;margin-left:10px"
                   class="diy-button--reset"
                   size="small"
                   @click="handleExport">导出</el-button>

        <el-button v-if="false"
                   style="margin-left:15px"
                   class="diy-button--more"
                   size="small"
                   @click="handleSendNotice">发送通知</el-button>
        <el-button style="margin-left:15px"
                   class="diy-button--more"
                   size="small"
                   @click="handleDelete">取消关注</el-button>
      </div>

      <el-table ref="ref_table"
                class="table"
                :data="tableData"
                border
                :height="tableHeight"
                v-loading="tableLoading"
                :header-cell-style="{background:'#2195FE',color:'#FFFFFF'}"
                @select="handleSelectTable"
                @select-all="handleSelAll"
                style="width: 100%">
        <el-table-column type="selection"
                         width="55"></el-table-column>
        <el-table-column label="序号"
                         header-align="center"
                         align="center"
                         type="index"
                         width="50"></el-table-column>

        <el-table-column prop="name"
                         header-align="center"
                         align="center"
                         label="姓名"
                         width="90">
        </el-table-column>
        <el-table-column prop="mobile"
                         header-align="center"
                         align="center"
                         label="手机号"
                         width="110">
        </el-table-column>
        <el-table-column prop="idCard"
                         header-align="center"
                         align="center"
                         label="身份证"
                         min-width="170">
        </el-table-column>
        <el-table-column prop="vaccinationCount"
                         header-align="center"
                         align="center"
                         label="接种针次"
                         width="100">
        </el-table-column>
        <el-table-column prop="remark"
                         header-align="center"
                         align="center"
                         show-overflow-tooltip
                         label="备注"
                         min-width="230">
        </el-table-column>
        <el-table-column prop="lastInformTime"
                         header-align="center"
                         align="center"
                         show-overflow-tooltip
                         label="最后一次通知时间"
                         min-width="120">
        </el-table-column>

        <el-table-column label="操作"
                         fixed="right"
                         width="140"
                         header-align="center"
                         align="center"
                         class="operate">
          <template slot-scope="scope">

            <el-button type="text"
                       class="div-table-button--detail"
                       size="small"
                       @click="handleDetail(scope.row)">查看</el-button>
            <el-button type="text"
                       class="div-table-button--edit"
                       size="small"
                       @click="handleEdit(scope.row)">修改</el-button>

            <el-popover popper-class="btn-popper"
                        placement="bottom"
                        style="margin-left:10px"
                        width="20"
                        trigger="click">
              <div class="more-btn">
                <el-button type="text"
                           class="div-table-button--detail--noline"
                           size="small"
                           @click="handleNoticeList(scope.row)">通知记录</el-button>
              </div>

              <div class="more-btn">
                <el-button type="text"
                           class="div-table-button--detail--noline"
                           size="small"
                           @click="handleVisiteList(scope.row) ">随访记录</el-button>
              </div>

              <el-button type="text"
                         size="small"
                         class="div-table-button--more"
                         slot="reference">更多<i class="el-icon-caret-bottom"></i></el-button>
            </el-popover>

          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="pageNo"
                       :page-sizes="[20, 50, 100, 200]"
                       :page-size="pageSize"
                       layout="sizes, prev, pager, next, total"
                       :total="total">
        </el-pagination>
      </div>

    </div>

    <!-- 新增弹出框 -->
    <el-dialog :visible.sync="addFormShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :destroy-on-close="true"
               title="新增"
               width="1050px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <vero-focus-add ref="ref_form_add"
                      @dialogCancle="diaClose"
                      @dialogOk="addFormOk"></vero-focus-add>
    </el-dialog>
    <!-- 修改弹出框 -->
    <el-dialog :visible.sync="editFormShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               title="修改"
               width="1050px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <vero-focus-edit ref="ref_form_edit"
                       @dialogCancle="diaClose"
                       @dialogOk="addFormOk"></vero-focus-edit>
    </el-dialog>
    <!-- 发送通知弹出框 -->
    <el-dialog :visible.sync="sendNoticeFormShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               title="发送通知"
               width="1050px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <vf-send-notice ref="ref_sendnotice"
                      @dialogCancle="diaClose"></vf-send-notice>
    </el-dialog>
    <!-- 通知记录弹出框 -->
    <el-dialog :visible.sync="noticeListFormShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               title="通知记录"
               width="1050px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <vf-notice-list ref="ref_noticelist"
                      @dialogCancle="diaClose"></vf-notice-list>
    </el-dialog>
    <!-- 随访记录弹出框 -->
    <el-dialog :visible.sync="visiteListFormShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               title="随访记录"
               width="1050px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <vf-visite-list ref="ref_visitelist"
                      @dialogCancle="diaClose"></vf-visite-list>
    </el-dialog>

  </div>
</template>

<script>

import veroFocusAdd from './veroFocusAdd'
import veroFocusEdit from './veroFocusEdit'
import vfNoticeList from './vfNoticeList'
import vfSendNotice from './vfSendNotice'
import vfVisiteList from './vfVisiteList'

import { requestPost } from "@/js/dai/request";
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务

let loading // 加载动画
export default {
  data () {
    return {
      loading: false,
      total: 0,
      pageSize: 20,
      pageNo: 1,
      tableLoading: false,

      selection: [],

      agencyId: '',

      formData: {
        attentionType: 1,//关注类型，核酸检测：2，疫苗接种：1		
        name: '',
        mobile: '',
        idCard: '',
        vaccinationCount: '',
      },
      veroNumList: [],

      tableData: [],
      selectionAll: [],

      //form相关
      addFormShow: false,
      editFormShow: false,
      sendNoticeFormShow: false,
      noticeListFormShow: false,
      visiteListFormShow: false,


    }
  },
  components: {
    veroFocusAdd, veroFocusEdit, vfNoticeList, vfSendNotice, vfVisiteList
  },
  async created () {

  },
  activated () {
    this.$refs['ref_table'].doLayout()
  },
  async mounted () {
    for (let i = 0; i < 11; i++) {
      let obj = {
        value: i + '',
        label: i + '次'
      }
      this.veroNumList.push(obj)
    }

    await this.loadTable()
  },

  methods: {
    handleSearch () {
      this.selectionAll = []
      this.loadTable()
    },

    async loadTable () {
      this.tableLoading = true

      const url = "/epmetuser/icEpidemicSpecialAttention/list"
      // const url = "http://yapi.elinkservice.cn/mock/245/epmetuser/icEpidemicSpecialAttention/list"
      let params = {
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        ...this.formData
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.total = data.total
        this.tableData = data.list

        this.analysisTableSelection()

        // this.tableData.forEach(item => {
        //   if (item.time) {
        //     let timeArray = item.time.split(' ')
        //     item.time = timeArray[0]
        //   }

        // });
      } else {
        this.$message.error(msg)
      }
      this.tableLoading = false
    },

    handleSelectTable (selection, row) {

      row.isSel = !row.isSel

      if (row.isSel) {
        this.selectionAll.push(row)
      } else {
        for (let i = 0; i < this.selectionAll.length; i++) {
          let item = this.selectionAll[i]
          if (item.idCard === row.idCard) {
            this.selectionAll.splice(i, 1)
            break
          }

        }
      }

    },

    handleSelAll (selection) {
      let selFlag = selection.length > 0//全选选中 还是 全选不选中
      for (let i = 0; i < this.tableData.length; i++) {
        let tableItem = this.tableData[i]
        tableItem.isSel = selFlag
        let isHasItem = false
        for (let j = 0; j < this.selectionAll.length; j++) {
          let selectionItem = this.selectionAll[j]
          if (selectionItem.idCard === tableItem.idCard) {
            isHasItem = true
            if (!selFlag) {
              this.selectionAll.splice(j, 1)
              break
            }
          }

        }

        if (!isHasItem && selFlag) {
          this.selectionAll.push(tableItem)
        }
      }

    },


    //回显列表选中的行
    analysisTableSelection () {
      this.$nextTick(() => {
        this.tableData.forEach(tableItem => {


          for (let j = 0; j < this.selectionAll.length; j++) {
            let selectionItem = this.selectionAll[j]

            if (selectionItem.idCard === tableItem.idCard) {
              tableItem.isSel = true
              break

            }
          }
          if (tableItem.isSel) {
            this.$refs.ref_table.toggleRowSelection(tableItem);
          }
        });
      })


    },

    diaClose () {
      this.addFormShow = false
      this.editFormShow = false
      this.sendNoticeFormShow = false
      this.noticeListFormShow = false
      this.visiteListFormShow = false

    },

    handleAdd () {
      this.addFormShow = true
      this.$nextTick(() => {
        this.$refs.ref_form_add.initForm(null, this.agencyId)
      })
    },

    handleEdit (row) {
      this.editFormShow = true
      this.$nextTick(() => {
        this.$refs.ref_form_edit.initForm('edit', row)
      })
    },

    handleDetail (row) {
      this.editFormShow = true
      this.$nextTick(() => {
        this.$refs.ref_form_edit.initForm('detail', row)
      })
    },

    handleSendNotice () {
      if (this.selectionAll.length === 0) {
        this.$message.info('请选择要通知的人员')
        return false
      }
      this.sendNoticeFormShow = true
      this.$nextTick(() => {
        this.$refs.ref_sendnotice.initForm(this.selectionAll)
      })

    },

    handleNoticeList (row) {
      this.noticeListFormShow = true
      this.$nextTick(() => {
        this.$refs.ref_noticelist.initTable(row.idCard)
      })

    },
    handleVisiteList (row) {

      this.visiteListFormShow = true
      this.$nextTick(() => {
        this.$refs.ref_visitelist.initTable(row)

      })

    },


    addFormOk () {
      this.addFormShow = false
      this.editFormShow = false
      this.loadTable()

    },

    async handleDelete (row) {
      if (this.selectionAll.length === 0) {
        this.$message.info('请选择要取消关注的名单')
        return false
      }
      this.$confirm("确认取消关注选择的名单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteFocus(row)
        })
        .catch(err => {
          if (err == "cancel") {

          }

        });
    },

    async deleteFocus (row) {
      const url = "/epmetuser/icEpidemicSpecialAttention/cancel-attention"
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/org/placepatrolteam/del"
      let idCards = []

      this.selectionAll.forEach(element => {
        idCards.push(element.idCard)
      });
      let params = {
        attentionType: 1,
        idCards: idCards
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.$message({
          type: "success",
          message: "操作成功"
        });

        this.loadTable()
      } else {
        this.$message.error(msg)
      }
    },

    //重置搜索条件
    resetSearch () {
      this.formData = {
        attentionType: 1,//关注类型，核酸检测：2，疫苗接种：1		
        name: '',
        mobile: '',
        idCard: '',
        vaccinationCount: '',
      }

      this.pageNo = 1
      // this.loadTable()
    },


    handleSizeChange (val) {
      this.pageSize = val
      this.pageNo = 1
      this.loadTable()
    },
    handleCurrentChange (val) {
      this.pageNo = val
      this.loadTable()
    },

    //导出表格
    async handleExport () {
      let title = '疫苗接种关注名单'

      const url = "/epmetuser/icEpidemicSpecialAttention/vaccination-export"

      app.ajax.exportFilePost(
        url,
        this.formData,
        (data, rspMsg) => {

          this.download(data, title + '.xlsx')
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg);
        }
      );

    },

    // 下载文件
    download (data, fileName) {
      if (!data) {
        return
      }

      var csvData = new Blob([data])

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(csvData, fileName);
      }
      // for Non-IE (chrome, firefox etc.)
      else {
        var a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        var url = window.URL.createObjectURL(csvData);
        a.href = url;
        a.download = fileName;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }

    },

    handleExportModule () {
      let title = '疫苗接种关注名单模板'

      const url = "/epmetuser/icEpidemicSpecialAttention/export-template"
      let params = {
        attentionType: '1'
      }

      app.ajax.exportFilePost(
        url,
        params,
        (data, rspMsg) => {

          this.download(data, title + '.xlsx')
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg);
        }
      );
    },


    // 上传文件之前的钩子
    beforeUpload (file) {

      const array = file.name.split('.')
      const extension = array[array.length - 1]
      // const isLt1M = (file.size / 1024 / 1024) < 5
      if (extension !== 'xlsx') {
        this.$message.error('只能上传xlsx文件！')
        return false
      } else {
        this.files = file;
        this.fileName = file.name;
        return true
      }

    },
    // 上传文件个数超过定义的数量
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，请删除后继续上传`)
    },

    async uploadFile () {
      if (this.fileName == "") {
        this.$message.warning('请选择要上传的文件！')
        return false
      }

      this.$message({
        showClose: true,
        message: '导入中，请到系统管理-导入记录中查看进度',
        duration: 0
      })

      //清空上传列表
      this.$refs['upload'].clearFiles()

      var url = '/epmetuser/icEpidemicSpecialAttention/vaccination-import'

      let fileFormData = new FormData();
      fileFormData.append('file', this.files);//filename是键，file是值，就是要传的文件，test.zip是要传的文件名
      fileFormData.append('attentionType', '1');//filename是键，file是值，就是要传的文件，test.zip是要传的文件名

      window.app.ajax.post2(url, fileFormData,
        (data, rspMsg) => {

          if (data.code === 0 && data.msg == 'success') {
            // this.$message.success('导入成功')
          } else {
            // this.$message({
            //   showClose: true,
            //   message: rspMsg,
            //   duration: 0,
            //   type: "error"
            // })
            // this.$message.error(rspMsg)
          }

          // this.loadTable()

        },
        (rspMsg, data) => {

        }, { headers: { 'Content-Type': 'multipart/form-data' } })


    },


    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    tableHeight () {
      return this.$store.state.inIframe ? this.clientHeight - 360 + this.iframeHeight : this.clientHeight - 360

    },

    ...mapGetters(['clientHeight', 'iframeHeight'])
  },
  watch: {

  },
  props: {

  }
}
</script>

<style lang="scss" scoped >
@import "@/assets/scss/modules/management/epidemic.scss";
</style>



