<template>
  <div class="app-container">
    <el-form label-width="50px">
      <el-row>
        <el-col :span="4">
          <el-form-item label="风险点（单元）" label-width="120px">
            <el-input v-model="KEYWORDS" placeholder="搜索"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="部门">
            <SelectTree ref="deptTree_Select" :clearable="false" :options="treeData" :props="defaultProps" v-model="DEPARTMENT_ID" placeholder="请选择部门" style="width: 100%;" />
          </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="12">
          <el-form-item style="text-align: right">
            <el-button v-waves class="filter-item" type="info" icon="el-icon-bottom-right" size="mini" plain @click="dialogFormDaoru = true">
              导入
            </el-button>
            <el-button v-waves class="filter-item" type="info" icon="el-icon-right" size="mini" plain @click="getDaochu">
              导出全部数据
            </el-button>
            <el-button v-waves class="filter-item" type="info" icon="el-icon-right" size="mini" plain @click="getonly(RISKUNIT_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="DEPT_NAME" label="所属部门" />
      <el-table-column prop="RISKUNITNAME" label="风险点（单元）" />
      <el-table-column label="操作" align="center" width="400">
        <template slot-scope="{row}">
          <el-button class="tiffany-btn" icon="el-icon-picture" size="mini" @click="goQrcode(row)">二维码</el-button>
          <el-button 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.RISKUNIT_ID)">编辑</el-button>
          <el-button v-show="del" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.RISKUNIT_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>{{ pd.RISKUNITNAME }}</td>
            <td class="tbg">管控部门</td>
            <td>{{ pd.DEPT_NAME }}</td>
          </tr>
          <tr>
            <td class="tbg">所属公司</td>
            <td>{{ pd.CORP_NAME }}</td>
            <td class="tbg">管控负责人</td>
            <td>{{ pd.HEADMANNAME }}</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 :visible.sync="dialogFormEdit" :title="dialogType==='edit'?'修改':'新增'" width="600px">
      <el-form ref="form" :rules="rules" :model="form" label-width="130px" style="width: 500px;">
        <el-form-item label="部门" prop="DEPARTMENT_ID">
          <SelectTree ref="deptTree" :clearable="false" :options="treeData" :props="defaultProps" v-model="form.DEPARTMENT_ID" placeholder="请选择部门" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="风险点（单元）" prop="RISKUNITNAME">
          <el-input id="RISKUNITNAME" ref="RISKUNITNAME" v-model="form.RISKUNITNAME" maxlength="255" placeholder="这里输入风险点（单元）名称..." title="风险点（单元）名称" />
        </el-form-item>
      </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="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>
    <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,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      KEYWORDS: this.$route.query.KEYWORDS || '',
      DEPARTMENT_ID: '',
      varList: [],
      pd: {
        RISKUNITNAME: '',
        DEPT_NAME: '',
        HEADMAN: '',
        CORP_NAME: ''
      },
      qrcodeStr: '',
      form: {
        RISKUNIT_ID: '',
        RISKUNITNAME: '', // 风险点（单元）
        DEPARTMENT_ID: ''// 管控部门
      },
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      treeData: [],
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogFormShow: false,
      dialogType: 'add',
      rules: {
        RISKUNITNAME: [{ required: true, message: '风险点（单元）不能为空', trigger: 'blur' }],
        DEPARTMENT_ID: [{ required: true, message: '管控部门不能为空', trigger: 'blur' }]
      },
      dialogFormDaoru: false,
      daoruFrom: {
        FFILE: '',
        FFILEName: ''
      }
    }
  },
  created() {
    this.getList()
    this.getTreeList()
  },
  methods: {
    getRowKey(row) {
      return row.RISKUNIT_ID
    },
    getTreeList() {
      requestFN(
        '/department/listTree',
        {}
      ).then((data) => {
        this.treeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
      })
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.$refs.deptTree_Select.clearHandle()
      this.DEPARTMENT_ID = ''
      this.getQuery()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/riskunit/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          DEPARTMENT_ID: this.DEPARTMENT_ID
        }
      ).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'
      this.dialogFormEdit = true
      this.resetForm()
      this.$refs.deptTree.clearHandle()
      this.getDict()
    },
    // 修改
    handleEdit(ID) {
      this.getDict()
      this.dialogType = 'edit'
      requestFN(
        '/riskunit/goEdit',
        {
          RISKUNIT_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj

        const node = {}
        node.id = this.form.DEPARTMENT_ID
        this.dialogFormEdit = true
        this.$refs.deptTree.clearHandle()
        this.$nextTick(() => { // 此处使用这个可以等节点渲染后再获取节点
          this.$refs.deptTree.handleNodeClick(node)
        })
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          requestFN(
            '/riskunit/' + 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/fxfb/index.html?FID=' + row.RISKUNIT_ID
      console.info(this.pd)
    },
    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(
        '/riskunit/readExcel',
        formData
      ).then((data) => {
        this.dialogFormDaoru = false
        if (data.msg) {
          this.$message({
            message: data.msg,
            type: data.type
          })
        }
        this.getList()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 导出全部数据
    getDaochu() {
      const _selectData = this.$refs.multipleTable.selection
      const ids = _selectData.map((item, index) => {
        return item.CORPINFO_ID
      }).join(',')
      this.$confirm('确定要导出到excel吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.open(this.config.httpurl + '/riskunit/excel?ids=' + ids)
      }).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.RISKUNIT_ID
      }).join(',')
      console.log(ids)
      this.$confirm('确定要导出到excel吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.open(this.config.httpurl + '/riskunit/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 + 'riskunit/excelModel'
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    },
    handleDelete(id) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/riskunit/delete',
          {
            RISKUNIT_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.RISKUNIT_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/riskunit/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 = 'riskunit:add,riskunit:del,riskunit:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.riskunitfhadminadd		// 新增权限
        this.del = data.riskunitfhadmindel		// 删除权限
        this.edit = data.riskunitfhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取数据字典数据
    getDict() {
    },
    resetForm() {
      this.form = {
        RISKUNITNAME: '', // 风险点（单元）
        CORPINFO_ID: '', // 企业ID
        DEPARTMENT_ID: ''// 管控部门
      }
    },
    goDetail(row) {
      this.$parent.activeName = 'Info'
      this.$parent.RISKUNIT_ID = row.RISKUNIT_ID
      this.$parent.RISKUNITNAME = row.RISKUNITNAME
      this.$parent.DEPT_NAME = row.DEPT_NAME
    }
  }
}

</script>
<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
</style>
