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

        <el-form-item label="所属地区"
                      prop="name">
          <el-cascader ref="sourceArea"
                       v-model="sourceAllCode"
                       class="item_width_2"
                       :props="areaProps"
                       @change="handleAreaChange"
                       clearable></el-cascader>

        </el-form-item>

        <el-form-item label="风险等级"
                      prop="dangerLevel">
          <el-select class="item_width_2"
                     v-model.trim="formData.dangerLevel"
                     placeholder="请选择"
                     clearable>
            <el-option v-for="item in dangerLevelList"
                       :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>

      </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 class="diy-button--export"
                   size="small"
                   @click="handleExportModule">下载模板</el-button>
        <el-upload :headers="$getElUploadHeaders()"
                   ref="upload"
                   :multiple='false'
                   :show-file-list='false'
                   :before-upload="beforeUpload"
                   action=""
                   accept=".xls,.xlsx"
                   :limit="1"
                   :on-exceed="handleExceed"
                   :http-request="uploadHttpRequest">
          <el-button size="small"
                     style="margin-left: 10px"
                     class="diy-button--delete"
                     :loading="importLoading">{{importBtnTitle}}</el-button>
        </el-upload>

        <el-button style="margin-left:10px"
                   class="diy-button--reset"
                   size="small"
                   :loading="exportBtn"
                   @click="handleExport">{{ exportBtnTitle }}</el-button>

      </div>

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

        <el-table-column prop="allName"
                         header-align="center"
                         align="center"
                         label="风险地区"
                         min-width="150"
                         fixed="left">
        </el-table-column>
        <el-table-column prop="dangerLevelShow"
                         header-align="center"
                         align="center"
                         label="风险等级"
                         min-width="100">
        </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-button type="text"
                       class="div-table-button--delete--noline "
                       size="small"
                       @click="handleDelete(scope.row)">删除</el-button>

          </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="formShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="formTitle"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <risk-form v-if="formShow"
                 ref="ref_form"
                 @dialogCancle="addFormCancle"
                 @dialogOk="addFormOk"></risk-form>
    </el-dialog>
    <!-- 详情弹出框 -->
    <el-dialog :visible.sync="detailShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'详情'"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <risk-detail v-if="detailShow"
                   @dialogCancle="addFormCancle"
                   ref="ref_detail"></risk-detail>
    </el-dialog>

  </div>
</template>

<script>

import riskForm from './riskForm'
import riskDetail from './riskDetail'


import { requestPost } from "@/js/dai/request";
import { mapGetters } from 'vuex'

let loading // 加载动画
export default {
  data () {
    return {

      exportBtn: false,
      exportBtnTitle: '导出',
      importBtnTitle: '导入',
      importLoading: false,
      loading: false,
      total: 0,
      pageSize: 20,
      pageNo: 0,
      tableLoading: false,

      sHeight: 0,

      dangerLevelList: [],
      sourceAllCode: [],
      areaProps: {
        checkStrictly: true,
        lazy: true,
        lazyLoad: this.lzayLoadArea
      },
      agencyId: '',


      formData: {
        name: '',//省-市-区	
        dangerLevel: '',//风险级别

      },

      tableData: [],

      //form相关
      formShow: false,
      detailShow: false,
      formTitle: '新增',


    }
  },
  components: {
    riskForm,
    riskDetail,

  },
  async created () {

  },
  async mounted () {
    //获取场所类型


    const { user } = this.$store.state
    console.log('user-----', user)
    this.agencyId = user.agencyId

    await this.getDangerLevel()
    await this.loadTable()
    this.sHeight = this.$refs.div_search.offsetHeight + 270
  },

  methods: {
    lzayLoadArea (node, resolve) {
      // this.getArea(node, resolve)
      setTimeout(() => {
        this.getArea(node, resolve)
      }, 200)
    },

    handleSearch () {
      this.loadTable()
    },

    async getArea (node, resolve) {

      const url = "/commonservice/areacode/nextarea"
      let params = {
        parentLevel: node.data ? node.data.level : '',
        parentAreaCode: node.data ? node.data.code : ''
      }

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

      if (code === 0) {
        const nodes = data.map(item => ({
          value: item.areaCode, //
          label: item.areaName,
          code: item.areaCode,
          level: item.level,
          leaf: node.level >= 2 // 3层级
        }))
        resolve(nodes)

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

    },

    async getDangerLevel () {

      const url = "/sys/dict/data/dictlist";

      let params = {
        dictType: "dangerAreaLevel",
      };

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

      if (code === 0) {
        this.dangerLevelList = data


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

    },
    async loadTable () {
      this.tableLoading = true

      const url = "/epmetuser/icDangerArea/list"
      // const url = "http://yapi.elinkservice.cn/mock/245/epmetuser/icDangerArea/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.tableData.forEach(item => {
          let selItem = this.dangerLevelList.filter((levelItem) =>
            item.dangerLevel === levelItem.value);

          if (selItem && selItem.length > 0)
            item.dangerLevelShow = selItem[0].label
        });

      } else {
        this.$message.error(msg)
      }
      this.tableLoading = false
    },
    handleAreaChange (val) {

      if (val.length > 0) {
        const labels = this.$refs.sourceArea.getCheckedNodes()[0].pathLabels

        this.formData.name = labels.join('-')

      } else {

        this.formData.allName = ''

      }
    },

    diaClose () {
      // this.$refs.ref_form.resetData()
      this.formShow = false

    },


    handleDetail (row) {
      // this.formTitle = '行程详情'
      this.detailShow = true
      this.$nextTick(() => {
        this.$refs.ref_detail.initForm(row)
      })
    },

    handleAdd () {
      this.formTitle = '新增'
      this.formShow = true
      this.$nextTick(() => {
        this.$refs.ref_form.initForm('add', '')
      })
    },

    handleEdit (row) {
      this.formTitle = '修改'
      this.formShow = true
      this.$nextTick(() => {
        this.$refs.ref_form.initForm('edit', row)
      })
    },

    addFormCancle () {
      this.detailShow = false
      this.formShow = false
    },
    addFormOk () {
      this.formShow = false

      this.loadTable()

    },

    async handleDelete (row) {

      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteRick(row)
        })
        .catch(err => {
          if (err == "cancel") {

          }

        });
    },

    async deleteRick (row) {
      const url = "/epmetuser/icDangerArea/delete"
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/org/placepatrolteam/del"

      let params = [row.id]

      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.sourceAllCode = []
      this.formData.name = ''
      this.formData.dangerLevel = ''
      this.pageSize = 20
      this.pageNo = 1
      // this.loadTable()
    },


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

    //导出表格
    async handleExport () {
      this.exportBtn = true
      this.exportBtnTitle = '正在导出...'
      let params = {
        ...this.formData
      }

      await this.$http({
        method: 'POST',
        url: '/epmetuser/icDangerArea/export',
        responseType: 'blob',
        data: params
      })
        .then(res => {

          console.log('resllll', res)
          let fileName = window.decodeURI(res.headers["content-disposition"].split(";")[1].split("=")[1])
          console.log('filename', fileName)
          let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
          var url = window.URL.createObjectURL(blob)
          var aLink = document.createElement('a')
          aLink.style.display = 'none'
          aLink.href = url
          aLink.setAttribute('download', fileName)
          document.body.appendChild(aLink)
          aLink.click()
          document.body.removeChild(aLink) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        })
        .catch((err) => {
          console.log('获取导出情失败', err)
          this.$message.error('获取导出失败')
        })
      this.exportBtnTitle = '导出'
      this.exportBtn = false

    },

    // 下载文件
    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);
      }

    },

    async handleExportModule () {

      const url = "/epmetuser/icDangerArea/downloadTemplate"
      let params = {}
      await this.$http({
        method: 'POST',
        url,
        responseType: 'blob',
        data: params
      })
        .then(res => {
          console.log('res----dddd', res)

          if (res.headers["content-disposition"]) {
            let fileName = window.decodeURI(res.headers["content-disposition"].split(";")[1].split("=")[1])
            console.log('filename', fileName)
            let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
            var url = window.URL.createObjectURL(blob)
            var aLink = document.createElement('a')
            aLink.style.display = 'none'
            aLink.href = url
            aLink.setAttribute('download', fileName)
            document.body.appendChild(aLink)
            aLink.click()
            document.body.removeChild(aLink) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          } else this.$message.error('下载失败')
        })
        .catch(err => {
          console.log('err', err)
          return this.$message.error('网络错误')
        })
    },

    // 上传文件之前的钩子
    beforeUpload (file) {
      this.files = file;

      const isText = file.type === 'application/vnd.ms-excel'
      const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

      if (!isText && !isTextComputer) {
        this.$message.error('请选择正确格式的文件')
        return false
      } else {
        this.fileName = file.name;
        return true
      }

    },
    // 上传文件个数超过定义的数量
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，请删除后继续上传`)
    },
    async uploadHttpRequest (file) {
      this.importLoading = true
      this.importBtnTitle = '正在上传中...'
      this.$message({
        showClose: true,
        message: '导入中，请到系统管理-导入记录中查看进度',
        duration: 0
      })
      const formData = new FormData() //FormData对象，添加参数只能通过append('key', value)的形式添加
      formData.append('file', file.file) //添加文件对象
      await this.$http
        .post('/epmetuser/icDangerArea/import', formData).then(res => {
          console.log('res-up', res)
          if (res.data.code == 0 && res.data.msg == 'success') {
            // this.$message.success('导入成功')
            this.loadTable()
          } else this.$message.error(res.data.msg)
        }).catch(err => {
          console.log('失败', err)
          file.onError() //上传失败的文件会从文件列表中删除
          // this.$message.error('导入失败')
        })
      this.importLoading = false
      this.importBtnTitle = '导入'
      this.$refs.upload.clearFiles()
    },

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

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

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

      var url = '/gov/org/house/houseimport'

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

      this.importRoomLoading = true
      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.$emit('refreshTree')
          this.loadTable()
          this.importRoomLoading = false
        },
        (rspMsg, data) => {
          this.importRoomLoading = false
        }, { headers: { 'Content-Type': 'multipart/form-data' } })


    }
  },
  computed: {
    tableHeight () {
      const h = this.clientHeight - this.sHeight + this.iframeHeigh
      const _h = this.clientHeight - this.sHeight
      return this.$store.state.inIframe ? h : _h

    },

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

      if (val.length === 0) {
        this.formData.name = ''
      }

    }
  },
  props: {

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

.item_width_2 {
  width: 300px;
}
</style>


