<!--组织架构-->
<template>
  <div class="app-container dept">
    <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="inquire-button-one" @click="handleQuery">查询</p>
        <p class="reset-button-one" @click="resetQuery">重置</p>
      </el-form-item>
    </el-form>
    <el-table 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">
          <img v-if="scope.row.deptImg" class="scope-img" :src="scope.row.deptImg">
          <p class="scope-name">{{ scope.row.deptName }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="deptSign" label="电子签章" >
        <template slot-scope="scope">
          <img :src="scope.row.deptSign" style="width:40px;height:40px;" @click="lookSign(2,scope.row.deptSign)">
        </template>
      </el-table-column>
      <el-table-column prop="isLower" label="适用下级" >
        <template slot-scope="scope">
          {{scope.row.isLower == 0?'否':'是'}}
        </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-hasPermi="['system:dept_sign:edit']"
               @click="addButton(scope.row)"
            >编辑</p>
            <p class="table-button-null"></p>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <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/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="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</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 { listDept,listDeptVO, getDept, delDept, addDept, updateDept, listDeptExcludeChild,signList,deptSign } from "@/api/system/dept";
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: "Bearer " + getToken(),
      },
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: 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.msg);
              this.upFaceOpen = false;
              this.getList();
            })
          }
        })
      }
    },
    //查看签章
    lookSign(type,url){
      if(type == 1){
        this.signType = false;
      }else if(type == 2){
        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/gif') {
        type = true;
      }else{
        this.$message.error('只能上传png/jpeg/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);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.open = true;
      this.title = "添加部门";
      listDept().then(response => {
	        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改部门";
      });
      listDeptExcludeChild(row.deptId).then(response => {
	        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deptId != undefined) {
            updateDept(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDept(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDept(row.deptId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    //计算层级
    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 {
    display: flex!important;
    flex-direction: column;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
    padding:11px 20px 20px!important;
    .button-box{
      width:300px;
      display: flex;
    }
  }
</style>
