<template>
  <div class="app-container">
    <el-form label-width="60px">
      <el-row>
        <el-col :span="4">
          <el-form-item label="关键字">
            <el-input v-model="KEYWORDS" placeholder="搜索"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="10px">
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
              搜索
            </el-button>
            <el-button v-waves class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
              重置
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item style="text-align: right">
            <el-button v-waves size="mini" plain type="info" icon="el-icon-bottom-right" @click="dialogFormDaoru = true">
              导入
            </el-button>
            <el-button v-waves size="mini" plain type="info" icon="el-icon-right" @click="getDaochu">
              导出全部数据
            </el-button>
            <el-button v-waves class="filter-item" type="info" icon="el-icon-right" size="mini" plain @click="getonly(IDENTIFICATIONPARTS_ID)">
              导出
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table v-loading="listLoading" ref="multipleTable" :data="varList" :row-key="getRowKey" :header-cell-style="{ 'font-weight': 'bold','color': '#000'}" tooltip-effect="dark" border fit highlight-current-row>
      <el-table-column :reserve-selection="true" type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="RISKUNITNAME" label="风险点（单元）" />
      <el-table-column prop="PARTSNAME" label="辨识部位名称" />
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="{row}">
          <el-button class="tiffany-btn" icon="el-icon-picture" size="mini" @click="goQrcode(row)">二维码</el-button>
          <!--          <el-button v-show="edit" type="success" icon="el-icon-view" size="mini" @click="goDetail(row)">匹配资源存在风险</el-button>-->
          <el-button v-show="edit" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row.IDENTIFICATIONPARTS_ID)">编辑</el-button>
          <el-button v-show="del" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.IDENTIFICATIONPARTS_ID)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button v-show="del" type="danger" icon="el-icon-delete" plain @click="batchDel">删除</el-button>
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

    <el-dialog :visible.sync="dialogFormShow" title="查看二维码" width="680px" class="top-dialog">
      <div id="printTest" style="border: 1px solid #fff;">
        <div class="level-title" style="margin-top:20px">
          <h1>辨识部位信息</h1>
        </div>
        <table class="table-ui">
          <tr>
            <td class="tbg">辨识部位</td>
            <td colspan="3">{{ pd.PARTSNAME }}</td>
          </tr>
          <tr>
            <td class="tbg">风险点（单元）</td>
            <td>{{ pd.RISKUNITNAME }}</td>
            <td class="tbg">管控部门</td>
            <td>{{ pd.DEPT_NAME }}</td>
          </tr>
        </table>
        <div class="table-qrcode">
          <vue-qr :text="qrcodeStr" :margin="0" :size="300" color-dark="#000" color-light="#fff" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormShow = false">关 闭</el-button>
        <el-button v-print="'#printTest'" type="primary">打 印</el-button>
      </div>
    </el-dialog>

    <el-dialog :key="form.LATITUDE" :visible.sync="dialogFormEdit" :title="dialogType==='edit'?'修改':'新增'" width="800px">
      <el-form ref="form" :rules="rules" :model="form" label-width="140px" style="width: 750px;">
        <el-form-item label="风险点（单元）" prop="RISK_UNIT_ID">
          <el-select v-model="form.RISK_UNIT_ID" clearable placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in unitList" :key="item.RISKUNIT_ID" :label="item.DEPT_NAME +'-'+item.RISKUNITNAME" :value="item.RISKUNIT_ID" />
          </el-select>
        </el-form-item>
        <el-form-item label="辨识部位名称" prop="PARTSNAME">
          <el-input id="PARTSNAME" ref="PARTSNAME" v-model="form.PARTSNAME" maxlength="255" placeholder="这里输入辨识部位名称..." title="风险单元名称" />
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="经纬度：" prop="LONGITUDEANDLATITUDE">
              <el-input v-model="form.LONGITUDEANDLATITUDE" style="width:206px" placeholder="请选择" disabled/>
              <el-button style="margin-left: 10px" type="primary" @click="handleMap">点击定位</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-row>-->
        <!--          <el-col :span="11">-->
        <!--            <el-form-item label="经度" prop="LONGITUDE">-->
        <!--              <el-input v-model="form.LONGITUDE" maxlength="255" placeholder="经度..." disabled title="经度" @focus="chooseMap" />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="13">-->
        <!--            <div class="ud-flex">-->
        <!--              <div style="flex:1">-->
        <!--                <el-form-item label="纬度" prop="LATITUDE">-->
        <!--                  <el-input v-model="form.LATITUDE" maxlength="255" placeholder="纬度..." disabled title="纬度" @focus="chooseMap" />-->
        <!--                </el-form-item>-->
        <!--              </div>-->
        <!--              <div>-->
        <!--                <el-button style="margin-left:10px" @click="chooseMap">-->
        <!--                  <span class="svg-container">-->
        <!--                    <svg-icon icon-class="international" />-->
        <!--                  </span>-->
        <!--                </el-button>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="map.dialogMap" :title="'作业位置'" width="80%">
      <div>
        <iframe :src="map.iframeSrc" frameborder="0" allowtransparency="true" width="100%" height="600"/>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogFormDaoru" title="导入" width="800px">
      <template>
        <div class="app-container">
          <el-form ref="form" :model="daoruFrom" label-width="110px" class="in-uploader">
            <el-form-item label="上传附件" prop="FIELDS">
              <div class="uploader">
                <el-input v-model="daoruFrom.FFILEName" :disabled="true" />
                <el-upload :before-upload="beforeFileUpload" class="avatar-uploader" action="#">
                  <el-button type="primary" icon="el-icon-upload" style="margin-left:10px">上传附件</el-button>
                </el-upload>
                <el-button v-waves type="success" icon="el-icon-right" style="margin-left:10px;width:150px" @click="getExcelModel">
                  导出模板
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormDaoru = false">取 消</el-button>
        <el-button type="primary" @click="goUpload">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormMap" title="定位" width="1050px" class="dy-dialog">
      <div id="tdmap" style="height: 600px"/>
      <div slot="footer" class="dialog-footer">
        <span>经度：</span>
        <el-input v-model="LONGITUDE" style="width: 200px" placeholder="请输入内容" disabled/>
        <span>纬度：</span>
        <el-input v-model="LATITUDE" style="width: 200px" placeholder="请输入内容" disabled/>
        <el-button @click="dialogFormMap = false">取 消</el-button>
        <el-button type="primary" @click="setPosition">确 定</el-button>
      </div>
    </el-dialog>
    <div v-html="styleText" />
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import SelectTree from '@/components/SelectTree'
import waves from '@/directive/waves' // waves directive
import vueQr from 'vue-qr'
import { upload } from '@/utils/upload'
import { Message } from 'element-ui'
export default {
  components: { Pagination, SelectTree, vueQr },
  directives: { waves },
  data() {
    return {
      styleText: '<style type="text/css" media="print">\n' + '  @page { size: landscape; }\n' + '</style>',
      config: config,
      listLoading: true,
      dialogFormMap: false,
      LONGITUDE: '',
      marker: null,
      LATITUDE: '',
      tdmap: null,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      KEYWORDS: '',
      varList: [],
      pd: {},
      unitList: [],
      qrcodeStr: '',
      form: {
        IDENTIFICATIONPARTS_ID: '',
        RISKUNITNAME: '', // 风险单元名称
        LONGITUDEANDLATITUDE: '',
        LONGITUDE: '',
        LATITUDE: ''
      },
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogFormShow: false,
      dialogType: 'add',
      rules: {
        PARTSNAME: [{ required: true, message: '辨识部位名称不能为空', trigger: 'blur' }],
        RISK_UNIT_ID: [{ required: true, message: '风险单元不能为空', trigger: 'blur' }],
        LONGITUDEANDLATITUDE: [{ required: true, message: '辨识部位坐标经度不能为空', trigger: 'blur' }]
      },
      map: {
        dialogMap: false,
        iframeSrc: ''
      },
      dialogFormDaoru: false,
      daoruFrom: {
        FFILE: '',
        FFILEName: ''
      }
    }
  },
  created() {
    this.getList()
    this.getSelect()
  },
  mounted() {
    const that = this
    window.addEventListener('message', function(e) {
      console.log(e)
      that.form.LONGITUDE = e.data.LONGITUDE
      that.form.LATITUDE = e.data.LATITUDE
      that.map.dialogMap = false
    })
  },
  methods: {
    setPosition() {
      this.form.LONGITUDEANDLATITUDE = this.LATITUDE + '--' + this.LONGITUDE
      this.form.LATITUDE = this.LATITUDE
      this.form.LONGITUDE = this.LONGITUDE
      this.dialogFormMap = false
    },
    initTDT() {
      return new Promise((resolve, reject) => {
        if (window.T) {
          console.log('天地图初始化成功...')
          resolve(window.T)
          reject('error')
        } else {
          console.info(999999999)
        }
      }).then(T => {
        window.T = T
      })
    },
    /**
     * 初始化地图
     * @param {*} lng 经度
     * @param {*} lat 纬度
     * @param {*} zoom 缩放比例(1~18)
     */
    initMap(lng, lat, zoom) {
      this.initTDT().then((T) => {
        const imageURL = 'http://t0.tianditu.gov.cn/img_w/wmts?' + 'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' + '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=e8a16137fd226a62a23cc7ba5c9c78ce'
        // 创建自定义图层对象
        this.lay = new window.T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 })
        // 初始化地图对象
        this.tdmap = new window.T.Map('tdmap')
        this.initCenter(lng, lat, zoom)
      })
    },
    initCenter(lng, lat, zoom) {
      // 设置显示地图的中心点和级别
      if (!this.LONGITUDE && !this.LATITUDE) {
        this.tdmap.centerAndZoom(new window.T.LngLat(116.40969, 39.89945), zoom)
      } else {
        this.tdmap.centerAndZoom(new window.T.LngLat(lng, lat), zoom)
        this.marker && this.tdmap.removeOverLay(this.marker)
        this.LONGITUDE = lng
        this.LATITUDE = lat
        this.marker = new window.T.Marker(new window.T.LngLat(lng, lat))
        // 向地图上添加标注
        this.tdmap.addOverLay(this.marker)
      }
      // 创建卫星和路网的混合视图
      this.tdmap.setMapType(window.TMAP_HYBRID_MAP)
      // 允许鼠标滚轮缩放地图
      this.tdmap.enableScrollWheelZoom()
      // 允许鼠标移动地图
      this.tdmap.enableInertia()
      // 向地图上添加标注
      this.tdmap.addEventListener('click', this.MapClick)
    },
    MapClick(event) {
      this.marker && this.tdmap.removeOverLay(this.marker)
      this.LONGITUDE = event.lnglat.getLng()
      this.LATITUDE = event.lnglat.getLat()
      this.marker = new window.T.Marker(new window.T.LngLat(event.lnglat.getLng(), event.lnglat.getLat()))
      // 向地图上添加标注
      this.tdmap.addOverLay(this.marker)
    },
    handleMap() {
      this.dialogFormMap = true
      this.$nextTick(() => {
        if (!this.tdmap) this.initMap(this.LONGITUDE, this.LATITUDE, 16)
        else this.initCenter(this.LONGITUDE, this.LATITUDE, 16)
      })
    },
    getRowKey(row) {
      return row.IDENTIFICATIONPARTS_ID
    },
    getSelect() {
      requestFN(
        '/identificationparts/getSelect',
        {
        }
      ).then((data) => {
        this.unitList = data.unitList
      }).catch((e) => {
      })
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.getQuery()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/identificationparts/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 添加
    handleAdd() {
      this.dialogType = 'add'
      if (this.tdmap) {
        this.tdmap.removeOverLay(this.marker)
      }
      this.resetForm()
      this.dialogFormEdit = true
    },
    // 修改
    handleEdit(ID) {
      this.LATITUDE = null
      this.LONGITUDE = null
      if (this.tdmap) {
        this.tdmap.removeOverLay(this.marker)
      }
      this.dialogType = 'edit'
      requestFN(
        '/identificationparts/goEdit',
        {
          IDENTIFICATIONPARTS_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        if (data.pd.LATITUDE) {
          this.LATITUDE = data.pd.LATITUDE // copy obj
        }
        if (data.pd.LONGITUDE) {
          this.LONGITUDE = data.pd.LONGITUDE // copy obj
        }
        if (this.LATITUDE) {
          this.form.LONGITUDEANDLATITUDE = this.LATITUDE + '--' + this.LONGITUDE
        }
        this.dialogFormEdit = true
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          requestFN(
            '/identificationparts/' + this.dialogType,
            this.form
          ).then((data) => {
            this.listLoading = false
            this.dialogFormEdit = false
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    goQrcode(row) {
      this.dialogFormShow = true
      this.pd = Object.assign({}, row)
      this.qrcodeStr = this.config.weburlWaiwang + 'static/qrcode/views/bsbw/record_list.html?id=' + row.IDENTIFICATIONPARTS_ID + '&LEVELID=' + row.LEVELID
      // this.qrcodeStr = 'https://skqhdg.porthebei.com:9004/static/qrcode/views/bsbw/record_list.html?id=d726b717a5ad42eebdeb0381ab86da0f&LEVELID=levelD'
      console.log(this.qrcodeStr)
    },
    beforeFileUpload(file) {
      this.daoruFrom.FFILE = file
      this.daoruFrom.FFILEName = file.name
      this.$forceUpdate()
      return false
    },
    goUpload() {
      const formData = new FormData()
      Object.keys(this.daoruFrom).map(key => {
        formData.append(key, this.daoruFrom[key])
      })
      upload(
        '/identificationparts/readExcel',
        formData
      ).then((data) => {
        if (data.resultStr) {
          Message({
            message: data.resultStr,
            type: data.type,
            duration: 5 * 1000
          })
        }
        this.dialogFormDaoru = false
        this.getList()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    chooseMap() { // 弹出地图
      this.map.dialogMap = true
      this.map.iframeSrc = this.config.weburl + 'static/maplocation.html?t=' + Math.random()
    },
    getDaochu() {
      this.$confirm('确定要导出到excel吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.location.href = config.httpurl + '/identificationparts/excel'
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    },
    getonly() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要导出的数据...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.IDENTIFICATIONPARTS_ID
      }).join(',')
      this.$confirm('确定要导出到excel吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.open(this.config.httpurl + '/identificationparts/excelAll?ids=' + ids)
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    },
    getExcelModel() {
      this.$confirm('确定要下载excel模板吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.location.href = config.httpurl + '/identificationparts/excelModel'
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    },
    handleDelete(id) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/identificationparts/delete',
          {
            IDENTIFICATIONPARTS_ID: id
          }
        ).then((res) => {
          if (res.result === 'success') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '该条数据下有管控台账信息不能进行删除',
              type: 'error'
            })
          }
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },

    batchDel() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.IDENTIFICATIONPARTS_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/identificationparts/deleteAll',
          {
            DATA_IDS: ids
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 判断按钮权限，用于是否显示按钮
    hasButton() {
      var keys = 'identificationparts:add,identificationparts:del,identificationparts:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.identificationpartsfhadminadd		// 新增权限
        this.del = data.identificationpartsfhadmindel		// 删除权限
        this.edit = data.identificationpartsfhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    resetForm() {
      this.LONGITUDE = ''
      this.LATITUDE = ''
      this.maker = null
      this.form = {
        RISKUNITNAME: '', // 风险单元名称
        CORPINFO_ID: '', // 企业ID
        LONGITUDEANDLATITUDE: '',
        LONGITUDE: '',
        LATITUDE: ''
      }
    },
    goDetail(row) {
      this.$parent.activeName = 'Info'
      this.$parent.IDENTIFICATIONPARTS_ID = row.IDENTIFICATIONPARTS_ID
      this.$parent.PARTSNAME = row.PARTSNAME
    }
  }
}

</script>
<style>

</style>
<style lang="sass" scoped>

.table-qrcode
  text-align: center
  padding-top: 20px
  width: 100%
.filter-container
  position: relative
  .filter-flot
    position: absolute
    right: 0
    top: 0
.uploader
  width: 570px
  display: flex
  align-items: center
.el-form-item__content
  line-height: 1

.ud-flex
  display: flex
</style>
