<template>
    <d2-container>
        <div v-if="isExpend" class="d2-fl d2-tree-view">
            <el-tree
                    ref="tree"
                    highlight-current
                    :data="treeData"
                    default-expand-all
                    :props="defaultProps"
                    @node-click="handleNodeClick"
            >
        <span class="icon-tree" slot-scope="{ node, data }">
          <div v-if="data.alias == 'top'">
          	<i class="fa fa-university"></i>
          	<span>&nbsp;{{node.label}}</span>
          </div>
          <div v-if="data.alias == 'JG001'">
          	<i class="fa fa-building"></i>
          	<span>&nbsp;{{node.label}}</span>
          </div>
             <div v-if="data.alias == 'JG002'">
          	<i class="fa fa-building"></i>
          	<span>&nbsp;{{node.label}}</span>
          </div>
            	<div v-if="data.alias == 'JG003'">
				 		 				<i class="fa fa-users"></i>
				 		 				<span>&nbsp;{{node.label}}</span>
				 		 			</div>
          	<!--<div v-if="data.alias == 'user'">-->
          	<!--<i class="fa fa-users"></i>-->
          	<!--<span>&nbsp;{{node.label}}</span>-->
          <!--</div>-->
        </span>
            </el-tree>
        </div>
        <div
                @click="isExpend = !isExpend"
                :class="[{'angle-view':isExpend},{'angle-view-none':!isExpend}]"
        >
            <i :class="['fa', {'fa-angle-left':isExpend},{'fa-angle-right':!isExpend}]"></i>
        </div>
        <div @click="isExpend = !isExpend" :class="[{'angle-view':isExpend},{'angle-view-none':!isExpend}]">
            <i :class="['fa', {'fa-angle-left':isExpend},{'fa-angle-right':!isExpend}]"></i>
        </div>
        <div :class="[{'d2-fl':isExpend},{'d2-table-view':isExpend},{'d2-table-view-full':!isExpend}]" style="overflow: hidden">
            <div class="d2-table-view-header">
                <el-form size="small" :inline="true" :model="filter" @keyup.enter.native="handleList" class="demo-form-inline" labelPosition="right">
                    <el-form-item label="通行权限">
                        <el-select v-model="filter.paId" clearable>
                        <el-option v-for=" (item,index) in lanuchs" :key="index" :label="item.paName"
                        :value="item.paId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否下发设备">
                        <el-select v-model="filter.lssued" style="width: 100%" clearable>
                            <el-option label="下发" value="1"></el-option>
                            <el-option label="未下发" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="人员编号">
                        <el-input v-model.trim="filter.userNo" placeholder="人员编号" clearable/>
                    </el-form-item>
                    <el-form-item label="姓名">
                        <el-input v-model.trim="filter.userNm" placeholder="姓名" clearable/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleList('1')">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="d2-table-view-content">
                <div class="d2-table-view-handle">
                    <label slot="headerButton" for="upload-input_1">
                        <span   class="import-button">批量导入人脸</span>
                    </label>
                </div>
                <d2-crud
                        title="人脸信息列表"
                        ref="d2Crud"
                        :options="tableOptions"
                        :loading="loading"
                        :columns="columns"
                        :data="data"
                        :rowHandle="rowHandle"
                        @set="handleSetFace"
                        @delete="handleRowRemove"
                        selection-row
                        @selection-change="handleSelectionChange"
                >
                </d2-crud>
            </div>
            <div class="d2-table-view-footer">
                <el-pagination
                        @current-change="handleCurrentChange"
                        @size-change="handleSizeChange"
                        :current-page.sync="currentPage"
                        :page-size="tableOptions.pageList[0]"
                        :page-sizes="tableOptions.pageList"
                        layout="total,sizes, prev, pager, next,jumper"
                        :total="pagination.total">
                </el-pagination>
            </div>
        </div>
        <el-dialog
                :title="diaLogName"
                :visible.sync="operVisible"
                @close="clearForm"
                width="40%"
                :close-on-click-modal="false"
        >
            <el-form ref="form" :model="form" label-width="80px" labelPosition="right" :rules="rules">
                <el-row :gutter="15">
                    <el-col :span="24">
                        <el-form-item label="人员编号" prop="userNo">
                            <el-input v-model.trim="form.userNo" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="人员姓名" prop="userNm">
                            <el-input v-model.trim="form.userNm" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="载入图片1" prop="face1">
                            <!--<label for="upload-input">-->
                            <!--<span class="buttonBox">选择</span>-->
                            <!--</label>-->
                            <input
                                    id="upload-input1"
                                    type="file"
                                    multiple
                                    ref="upload"
                                    name="img"
                                    @change="upload($event,'1')"
                                    style="width: 70px"
                            >
                            <span class="buttonBox" @click="removeClick(1)">清除</span>
                            <div style="width:200px">
                                <img v-if="form.face1" :src="form.face1" class="avatar" style="width: 100%">
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="载入图片2" prop="face2">
                            <!--<label for="upload-input">-->
                            <!--<span class="buttonBox">选择</span>-->
                            <!--</label>-->
                            <input
                                    id="upload-input2"
                                    type="file"
                                    multiple
                                    ref="upload"
                                    name="img"
                                    @change="upload($event,'2')"
                                    style="width: 70px"
                            >
                            <span class="buttonBox" @click="removeClick(2)">清除</span>
                            <div style="width:200px">
                                <img v-if="form.face2" :src="form.face2" class="avatar" style="width: 100%">
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="载入图片3" prop="face3">
                            <!--<label for="upload-input">-->
                            <!--<span class="buttonBox">选择</span>-->
                            <!--</label>-->
                            <input
                                    id="upload-input3"
                                    type="file"
                                    multiple
                                    ref="upload"
                                    name="img"
                                    @change="upload($event,'3')"
                                    style="width: 70px"
                            >
                            <span class="buttonBox" @click="removeClick(3)">清除</span>
                            <div style="width:200px">
                                <img v-if="form.face3" :src="form.face3" class="avatar" style="width: 100%">
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <zl-button :loading="staLoading" @click="operInstance(2)">保存</zl-button>
      </span>
        </el-dialog>
        <input id="upload-input_1" style="display: none" type="file"
               multiple
               ref="upload_1"
               name="file"
               @change="upload_1($event)">
        <input id="upload-input" style="display: none" type="file"
               multiple
               ref="upload"
               name="file"
               accept = "image/*"
               @change="upload($event)">
    </d2-container>
</template>

<script>
  import { Loading } from 'element-ui';
  import { tableOptions } from '../../../assets/options'
  import detailImg from './components/detailImg'
  import detailImg2 from './components/detailImg2'
  import detailImg3 from './components/detailImg3'
  import {treeNodeAll} from '@/api/face/record'
  import {getFaceManageList,getPaIdOption,uploadImagess,uploadFaceImg,getCreateFaceMessage,saveOrUpdataFaceImage,deleteFaceMess} from '@/api/face/faceManage'
  export default {
    name: 'system-merchant',
    components: {
      detailImg,
      detailImg2,
      detailImg3
    },
    data () {
      let checkUserNo = (rule, value, callback) => {
        let reg = /^\w+$/;
        if (!reg.test(value)) {
          return callback(new Error("请输入由数字或字母组成的正确编号"));
        } else {
          callback();
        }
      };
      return {
        staLoading:false,
        diaLogName:'单个添加人脸',
        operVisible:false,
        lanuchs:[],
        time:'',
        falg:true,
        leaveOverId:[],
        selection:[],
        disabled:false,
        isExpend:true,
        currentPage:1,
        tableOptions,
        loading: false,
        filter: {
          userNo: '',
          userNm: '',
          depId:'',
          lssued:"",
          paId:"",
          pageSize: 10,
          pageNum: 1
        },
        form:{
          faceUserId:"",
          face1:"",
          face2:"",
          face3:"",
          userId:"",
          userNo:"",
          userNm:"",
          lssued:''
        },
        pagination: {
          total: 0
        },
        columns: [
          {
            title: '学号/工号',
            key: 'userNo',
            minWidth: '120'
          },
          // {
          //   title: 'GUID',
          //   key: 'orgNm',
          //   minWidth: '180'
          // },
          {
            title: '人员姓名',
            key: 'userNm',
            minWidth: '120',
            showOverflowTooltip: true
          },
          {
            title: '所属部门',
            key: 'depNm',
            minWidth: '120',
            // formatter (row, column, cellValue, index) {
            //   if (cellValue === '1') {
            //     return '人脸识别'
            //   } else if (cellValue === '2') {
            //     return '卡识别'
            //   }else if (cellValue === '3') {
            //     return '人脸+卡识别'
            //   }
            // }
          },
          {
            title: '权限类型',
            key: 'paName',
            minWidth: '220'
          },
          {
            title: '是否下发设备',
            key: 'lssued',
            minWidth: '120',
            formatter (row, column, cellValue, index) {
              if (cellValue === '0') {
                return '未下发'
              } else if (cellValue === '1') {
                return '下发'
              }
            }
          },
          {
            title: '下发时间 ',
            key: 'lssuedTime',
            minWidth: '180'
          },
          {
            title: '身份证',
            key: 'extIdCard',
            minWidth: '180'
          },
          {
            title: '人脸库1',
            key: 'face1',
            minWidth: '180',
            component:{
              name:detailImg
            }
          },
          {
            title: '人脸库2',
            key: 'face2',
            minWidth: '180',
            component:{
              name:detailImg2
            }
          },
          {
            title: '人脸库3',
            key: 'face3',
            minWidth: '180',
            component:{
              name:detailImg3
            }
          },
          {
            title: '创建时间',
            key: 'creTm',
            minWidth: '180'
          },
        ],
        rowHandle: {
          columnHeader: '操作',
          minWidth: '220',
          align: 'center',
          custom: [
            {
              text: '添加人脸',
              type: 'primary',
              size: 'small',
              emit: 'set'
            },
            // {
            //   text: '更新人脸',
            //   type: 'primary',
            //   size: 'small',
            //   emit: 'edit'
            // },
            {
              text: '删除人脸',
              type: 'danger',
              size: 'small',
              emit: 'delete'
            }
          ]
        },
        currentParentId:'',
        treeData:[],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        data: [],
        rules:{

        }
      }
    },
    methods: {
      removeClick(val){
        if(val==1){
          this.$set(this.form,'face1','')
        }else if(val==2){
          this.$set(this.form,'face2','')
        }else{
          this.$set(this.form,'face3','')
        }

      },
      handleSetFace({row, index}){
        // console.log(row)
        // console.log(row.faceUserId)
        if(!row.faceUserId){
          this.$set(this.form,'userNo',row.userNo)
          this.$set(this.form,'userNm',row.userNm)
          this.$set(this.form,'userId',row.userId)
          this.$set(this.form,'lssued',row.lssued)
        }else{
          getCreateFaceMessage({faceUserId:row.faceUserId}).then(res=>{
            if(res.faceUser){
              this.form=res.faceUser
            }
            this.$set(this.form,'userNo',row.userNo)
            this.$set(this.form,'userNm',row.userNm)
            this.$set(this.form,'userId',row.userId)
            // this.$set(this.form,'lssued',row.lssued)
          })
        }
        this.operVisible=true

      },
      operInstance() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if(!this.form.face1){
              this.$message({
                message:'载入图片1不能为空',
                type: 'warning'
              })
              return
            }
            this.loading = true
            // console.log(this.form)
            saveOrUpdataFaceImage(this.form).then(res => {
              this.loading=false
              this.$message({
                message:'操作成功',
                type: 'success'
              })
              this.operVisible=false
              this.handleTreeNode()
            }).catch(err => {
              this.loading=false
            })

          }
        })
      },
      upload_1 (e) {
        //this.files= []
        let files = e.target.files
        let formData = new FormData()
        for (let k in files) {
          if (files.hasOwnProperty(k)) {
            formData.append('file', files[k])
          }
        }
        let loadingInstance_2=Loading.service({ fullscreen: true,text:'导入中...',background:"rgba(0, 0, 0, 0.8)" })
        uploadImagess(formData).then(res => {
          this.$message({
            message: res.msgDat,
            customClass: 'message-logout',
            duration:0,
            type: 'success',
            showClose: true
          })
          this.$nextTick(() => {
            loadingInstance_2.close();
          });
          this.handleList()
        }).catch(err=>{
          this.$nextTick(() => {
            loadingInstance_2.close();
          });
        })

        this.$refs.upload_1.value = null
      },
      upload(e,val) {
        this.files = [];
        let files = e.target.files;
        let formData = new FormData();
        // console.log(files)
        if(files[0].size>400000){
          this.$message({
            message: '请上传大小不超过400kb的图片',
            type: 'warning'
          })
          return false
        }
        for (let k in files) {
          if (files.hasOwnProperty(k)) {
            formData.append("file", files[k]);
          }
        }
        uploadFaceImg(formData).then(res => {
          this.$message({
            message: "上传成功",
            type: "success"
          });
          if(val==='1'){
            this.$set(this.form,'face1',res)
          }else if(val=='2'){
            this.$set(this.form,'face2',res)
          }else{
            this.$set(this.form,'face3',res)
          }

        });
        this.$refs.upload.value = null;
      },
      handleNodeClick(data) {
        if(data.alias !=='top'){
          this.falg = true
          this.filter.depId = data.id
        }else{
          this.falg = false
          this.filter.depId = ''
        }
        this.handleList()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleTreeNode () {
        treeNodeAll({
          depType: ''
        }).then(res => {
          this.treeData = JSON.parse(res.msgDat)
          // this.form.orgId = this.treeData[0].id
        })
        this.handleList()
      },

      handleList (val) {
        if(val){this.filter.pageNum=1
          this.currentPage = 1}
        this.loading = true
        getFaceManageList(this.filter).then(res => {
          this.loading = false
          this.data = res.page.list
          this.pagination.total = res.page.total
        }).catch(err => {
          this.loading = false
        })
      },

      handleCurrentChange (val) {
        this.filter.pageNum = val
        this.handleList()
      },

      handleSizeChange (val) {
        this.filter.pageNum = 1
        this.filter.pageSize = val
        this.handleList()
      },
      // handleRowEdit ({index, row}) {
      //   // this.diaLogName = '编辑'
      //   // this.form.userId=row.userId
      //   // teacherById({userId:this.form.userId}).then(res => {
      //   //   this.form = res.update
      //   //   this.operVisible = true
      //   // })
      //
      // },
      handleRowRemove ({index, row}) {
        if(!row.faceUserId){
          this.$message({
            message: '未添加人脸',
            type: 'warning'
          })
          return
        }
        this.$confirm(`确定要删除吗?`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '放弃',
          type: 'warning'
        }).then(() => {
          let faceUserId = row.faceUserId
          deleteFaceMess({
            faceUserId:faceUserId,lssued:row.lssued
          }).then(res=>{
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.handleList ()
          })
        })
      },
      getPaIdOptions(){
        getPaIdOption({paCode :''}).then(res=>{
          this.lanuchs=res.facePassageAccessList
        })
      },
      clearForm () {
        if (this.$refs['form']!==undefined) {
          this.$refs['form'].resetFields()
        }
        this.form= {}
      },
    },
    mounted () {
      this.getPaIdOptions()
      this.tableOptions = this.$calcTableHeight(tableOptions,90)
      this.filter.pageSize = this.tableOptions.pageList[0]
      this.handleTreeNode()
    }
  }
</script>
<style scoped>
</style>
<style>
    .buttonBox{
        display: inline-block;
        width: 40px;
        height: 22px;
        line-height: 25px;
        border: 1px solid #808080;
        text-align: center;
        margin-left: 20px;
        background-color: #F5F7FA;
    }
    .message-logout{
        width: 80%;
    }
    .message-logout .el-message__content{
        width: 90%;
        word-wrap: break-word;
        word-break: normal;
    }
</style>