<!--电子签章-->
<template>
  <div class="app-container dept">
    <div class="page-form-title-box">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            v-model="queryParams.deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
          <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-content-box">
      <el-table class="table-box" border v-loading="loading"
                :data="deptList" row-key="deptId" default-expand-all
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="deptName" label="部门名称">
          <template slot-scope="scope">
            <span class="scope-name">{{ scope.row.deptName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deptSign" label="电子签章">
          <template slot-scope="scope">
            <span @click="lookSign(2,scope.row.deptSign)"
                  :style="scope.row.deptSign?'cursor: pointer;color:#0183FA;':''"
                  >{{scope.row.deptSign?'查看':'未配置'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isLower" label="适用下级">
          <template slot-scope="scope">
            <span v-if="scope.row.deptSign">{{scope.row.isLower == 0?'否':'是'}}</span>
            <span v-if="!scope.row.deptSign"></span>

          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" v-if="tableButtonType">
          <template slot-scope="scope">
            <div class="table-button-box">
              <p class="table-button-null"></p>
              <p class="table-button-p"
                 v-hasPermiRouter="['system:dept_sign:edit']"
                 @click="addButton(scope.row)"
              >编辑</p>
              <p class="table-button-null"></p>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog class="up-img-box" title="电子签章" :visible.sync="upFaceOpen" width="600px" append-to-body
               :close-on-click-modal="false">
      <el-form ref="form" :model="upFaceForm" :rules="rules">
        <el-form-item label="是否适用下级" prop="isLower" style="margin-top:30px;" label-width="140px">
          <el-select v-model="upFaceForm.isLower" placeholder="请选择是否适用下级" style="width:300px;">
            <el-option label="是" :value="1"/>
            <el-option label="否" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="deptSign" style="width:200px;cursor: pointer;margin:20px 180px 0;">
          <el-upload
            @click="upImgOpenClick(1)"
            style="width:200px;height:200px;cursor: pointer;overflow: hidden"
            class="position-button"
            :action="uploadImgUrl"
            :show-file-list="false"
            accept="image/jpeg,image/jpg,image/gif,image/png"
            :on-success="handleAvatarSuccess"
            :headers="headers"
            :before-upload="beforeAvatarUpload">
            <div v-if="!upFaceForm.deptSign" style="width:200px;height:200px;border: 1px dashed #E0E0E0;">
              <p style="text-align: center;color:#999;font-weight:500;font-size: 20px;line-height:200px;margin:0;">+</p>
            </div>
            <img :src="upFaceForm.deptSign" v-if="upFaceForm.deptSign"
                 style="width:198px;height:198px;cursor: pointer;">
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deptSignUp(1)">取 消</el-button>
        <el-button type="primary" @click="deptSignUp(2)">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="电子签章" :visible.sync="signType" width="600px" append-to-body :close-on-click-modal="false">
      <img :src="signUrl" style="width:300px;height:300px;display: block;margin:0 auto;">
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="lookSign(1)" style="width:100px; margin:0 auto;display: block;">确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    signList,
    deptSign
  } from '@/api/systemManagement/index'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import { getToken } from '@/utils/auth'

  export default {
    name: 'Dept',
    components: { Treeselect },
    data() {
      return {
        tableButtonType: this.hasPermiDom(['system:dept_sign:edit']),
        uploadImgUrl: this.uploadUrl(), // 上传的图片服务器地址
        headers: {
          Authorization: getToken()
        },
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 表格树数据
        deptList: [],
        // 部门树选项
        deptOptions: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 状态数据字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          deptName: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          isLower: [
            { required: true, message: '请选择是否适用下级', trigger: 'blur' }
          ],
          deptSign: [
            { required: true, message: '请上传签章', trigger: 'blur' }
          ],
          parentId: [
            { required: true, message: '上级部门不能为空', trigger: 'blur' }
          ],
          deptName: [
            { required: true, message: '部门名称不能为空', trigger: 'blur' },
            { required: true, message: '部门名称不能为空', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          orderNum: [
            { required: true, message: '显示排序不能为空', trigger: 'blur' },
            { required: true, message: '显示排序不能为空', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          email: [
            {
              type: 'email',
              message: '\'请输入正确的邮箱地址',
              trigger: ['blur', 'change']
            },
            { required: true, message: '请输入正确的邮箱地址', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          phone: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: '请输入正确的联系方式',
              trigger: 'blur'
            },
            { required: true, message: '请输入正确的联系方式', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择是否适用下级', trigger: 'blur' }
          ]
        },
        //电子签章
        upFaceOpen: false,
        upFaceForm: {
          type: ''
        },
        upFaceUrl: '',
        signType: false,
        signUrl: ''
      }
    },
    created() {
      this.getList()
      this.getDicts('sys_normal_disable').then(response => {
        this.statusOptions = response.data
      })
    },
    methods: {
      //签章编辑窗口按钮
      deptSignUp(type) {
        if (type == 1) {
          this.upFaceOpen = false
        } else if (type == 2) {
          this.$refs['form'].validate(valid => {
            if (valid) {
              let obj = {
                deptId: this.upFaceForm.deptId,
                isLower: this.upFaceForm.isLower,
                deptSign: this.upFaceForm.deptSign

              }
              deptSign(obj).then(response => {
                this.msgSuccess(response.message)
                this.upFaceOpen = false
                this.getList()
              })
            }
          })
        }
      },
      //查看签章
      lookSign(type, url) {
        if (type == 1) {
          this.signType = false
        } else if (type == 2) {
          if(url){
            this.signUrl = url
            this.signType = true
          }
        }
      },
      //编辑签章
      addButton(row) {
        this.upFaceForm = JSON.parse(JSON.stringify(row))
        if (!this.upFaceForm.isLower) {
          this.upFaceForm.isLower = 0
        }
        this.upFaceUrl = this.upFaceForm.deptSign
        this.upFaceOpen = true
      },
      //上传
      handleAvatarSuccess(res) {
        console.log(res.data.url)
        this.upFaceForm.deptSign = res.data.url
        this.$forceUpdate()
      },
      beforeAvatarUpload(file) {
        let type = false
        console.log('file', file)
        if (file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/jpg' || file.type == 'image/gif') {
          type = true
        } else {
          this.msgError('只能上传png/jpeg/jpg/gif格式图片')
          type = false
        }
        return type
      },
      /** 查询部门列表 */
      getList() {
        let self = this
        this.loading = true
        signList(this.queryParams).then(response => {
          this.deptList = this.handleTree(response.data, 'deptId')
          let num = this.getDepth(this.deptList, 1) + 10
          let listA = JSON.parse(JSON.stringify(response.data))
          let listB = []
          //deptId 本身的名字  parentId 父名
          for (let i = 0; i < num; i++) {
            console.log('num===', i)
            for (let o = 0; o < listA.length; o++) {
              let age = 0
              for (let k = 0; k < listA.length; k++) {
                if (listA[o].deptId == listA[k].parentId) {
                  age++
                  console.log(listA[o].deptId, listA[o].deptName)
                  console.log(listA[k].parentId, listA[k].deptName)
                  break
                }
              }
              if (age == 0) {
                for (let k = 0; k < listA.length; k++) {
                  if (listA[o].parentId == listA[k].deptId) {
                    listA[k].totalPeople = listA[k].totalPeople + listA[o].totalPeople
                    listA[k].totalSub = listA[k].totalSub + listA[o].totalSub
                    listB.push(listA[o])
                    listA.splice(o, 1)
                    console.log('listA', listA)
                    console.log('listB', listB)
                    break
                    // return
                  }
                }
              }
            }
            if (listA.length == 1) {
              listB.push(listA[0])
              break
            }
          }
          this.deptList = this.handleTree(listB, 'deptId')
          this.loading = false
        })
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        }
      },
      // 字典状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status)
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      //计算层级
      getDepth(arr, depth) {
        var flag = false
        var temp = []
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].children instanceof Array) { // 判断是否是数组
            for (let j = 0; j < arr[i].children.length; j++) {
              temp.push(arr[i].children[j]) // 解析出arr下第一层
            }
            flag = true
          }
        }
        if (flag) { // 如果还有数组，则继续解析，直到最后一层有不为数组为止
          depth++
          return this.getDepth(temp, depth)
        } else {
          return depth
        }
      },
      //加法
      accAdd(arg1, arg2) {
        var r1, r2, m
        try {
          r1 = arg1.toString().split('.')[1].length
        } catch (e) {
          r1 = 0
        }
        try {
          r2 = arg2.toString().split('.')[1].length
        } catch (e) {
          r2 = 0
        }
        m = Math.pow(10, Math.max(r1, r2))
        return ((arg1 * m + arg2 * m) / m).toFixed(0)
      }
    }
  }
</script>
<style scoped lang="scss">
  .dept {
    .button-box {
      width: 300px;
      display: flex;
    }
  }
</style>
